-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathParseUtil.hpp
More file actions
727 lines (624 loc) · 27.2 KB
/
Copy pathParseUtil.hpp
File metadata and controls
727 lines (624 loc) · 27.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
#ifndef RUNCPP2_PARSE_UTIL_HPP
#define RUNCPP2_PARSE_UTIL_HPP
#include "runcpp2/LibYAML_Wrapper.hpp"
#include "runcpp2/Data/ParseCommon.hpp"
#include "runcpp2/StringUtil.hpp"
#include "ssLogger/ssLog.hpp"
#include "DSResult/DSResult.hpp"
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <stddef.h>
#include <memory>
#include <ostream>
#include <string>
namespace runcpp2
{
struct NodeRequirement
{
std::string Name;
YAML::NodeType NodeType;
bool Required;
bool Nullable;
inline NodeRequirement() : Name(""),
NodeType(YAML::NodeType::Scalar),
Required(false),
Nullable(true)
{}
inline NodeRequirement( const std::string& name,
YAML::NodeType nodeType,
bool required,
bool nullable) : Name(name),
NodeType(nodeType),
Required(required),
Nullable(nullable)
{}
};
inline bool ExistAndHasChild( YAML::ConstNodePtr node,
const std::string& childName,
bool nullable = false)
{
ssLOG_FUNC_DEBUG();
if(node->GetChildrenCount() > 0 && node->IsMap() && node->HasMapKey(childName))
{
YAML::ConstNodePtr mapVal = node->GetMapValueNode(childName);
if(!mapVal)
return false;
if(!nullable && mapVal->IsScalar() && mapVal->GetScalar<StringView>().value_or("").empty())
return false;
return true;
}
return false;
}
inline bool CheckNodeRequirement( YAML::ConstNodePtr parentNode,
const std::string childName,
YAML::NodeType childType,
bool required,
bool nullable)
{
ssLOG_FUNC_DEBUG();
if(!parentNode->IsMap())
{
ssLOG_ERROR("Node is not a map: " << parentNode->Value.index());
return false;
}
ssLOG_DEBUG("Checking: " << childName << " exists");
if(!ExistAndHasChild(parentNode, childName, nullable))
{
if(required)
{
if(false)
{
ssLOG_DEBUG("node.num_children(): " << parentNode->GetChildrenCount());
for(int j = 0; j < parentNode->GetChildrenCount(); ++j)
ssLOG_DEBUG(parentNode->GetMapKeyScalarAt<std::string>(j).value_or(""));
}
ssLOG_ERROR("Required field not found: " << childName);
return false;
}
return true;
}
//If type is nullable, we cannot verify it's type, so just continue
YAML::ConstNodePtr childNode = parentNode->GetMapValueNode(childName);
if(nullable && childNode->IsScalar() && childNode->GetScalar<StringView>().value_or("").empty())
return true;
if(childNode->GetType() != childType)
{
ssLOG_ERROR("Field type is invalid: " << childName);
ssLOG_ERROR("Expected: " << YAML::NodeTypeToString(childType));
ssLOG_ERROR("Found: " << YAML::NodeTypeToString(childNode->GetType()));
return false;
}
return true;
}
inline bool CheckNodeRequirements( YAML::ConstNodePtr node,
const std::vector<NodeRequirement>& requirements)
{
ssLOG_FUNC_DEBUG();
if(!node->IsMap())
{
ssLOG_ERROR("Node is not a map: " << YAML::NodeTypeToString(node->GetType()));
ssLOG_ERROR("Node is not a map");
return false;
}
//All keys must be unique
{
std::unordered_set<std::string> childKeys;
for(int i = 0; i < node->GetChildrenCount(); ++i)
{
YAML::ConstNodePtr keyNode = node->GetMapKeyNodeAt(i);
if(!keyNode->IsScalar())
{
ssLOG_ERROR("Key must be scalar");
return false;
}
std::string currentKey = (std::string)keyNode->GetScalar<StringView>().value_or("");
if(childKeys.count(currentKey) != 0)
{
ssLOG_ERROR("Duplicate key found for: " << currentKey);
return false;
}
else
childKeys.insert(currentKey);
}
}
for(int i = 0; i < requirements.size(); ++i)
{
if(!CheckNodeRequirement( node,
requirements[i].Name,
requirements[i].NodeType,
requirements[i].Required,
requirements[i].Nullable))
{
return false;
}
}
return true;
}
inline DS::Result<void> GetParsableInfo(const std::string& contentToParse,
std::string& outParsableInfo)
{
ssLOG_FUNC_DEBUG();
std::string source = contentToParse;
//Remove all \r characters
for(int i = 0; i < source.size(); i++)
{
if(source[i] == '\r')
{
source.erase(i, 1);
--i;
}
}
const std::string prefix = "runcpp2";
std::string currentLine;
bool insideCommentToParse = false;
bool singleLineComments = false;
bool preceedingSpace = false;
bool contentReadyToParse = false;
auto resetPrefixState = [&]()
{
//Clear values
insideCommentToParse = false;
singleLineComments = false;
preceedingSpace = false;
outParsableInfo.clear();
contentReadyToParse = false;
};
auto checkFinishedGettingParsableContent = [&]() -> DS::Result<bool>
{
if(singleLineComments)
{
//Check for end of continuous section
if(currentLine.size() < 2 || currentLine[0] != '/' || currentLine[1] != '/')
{
contentReadyToParse = true;
return true;
}
if(preceedingSpace && currentLine.size() < 3)
{
resetPrefixState();
return DS_ERROR_MSG("Inconsistent spacing for single line comment");
}
}
else
{
//Check for closing */
if( currentLine.size() >= 2 &&
currentLine[currentLine.size() - 1] == '/' &&
currentLine[currentLine.size() - 2] == '*')
{
currentLine.erase(currentLine.size() - 2, 2);
TrimRight(currentLine);
outParsableInfo += currentLine;
contentReadyToParse = true;
return true;
}
}
return false;
};
for(int i = 0; i < source.size(); i++)
{
//Just append character if not newline
if(source[i] != '\n')
currentLine.push_back(source[i]);
//Newline is reached, parse the current line
else
{
//Try to find prefix that indicates the content inside the comment for parsing
if(!insideCommentToParse)
{
Trim(currentLine);
if(currentLine == "// " + prefix || currentLine == "//" + prefix)
{
insideCommentToParse = true;
singleLineComments = true;
preceedingSpace = (currentLine + prefix).at(2) == ' ';
currentLine.clear();
continue;
}
if(currentLine == "/* " + prefix || currentLine == "/*" + prefix)
{
insideCommentToParse = true;
singleLineComments = false;
preceedingSpace = false;
currentLine.clear();
continue;
}
currentLine.clear();
}
//Parse the content
else
{
if(singleLineComments)
{
Trim(currentLine);
bool check = checkFinishedGettingParsableContent().DS_TRY();
if(check)
break;
currentLine.erase(0, (preceedingSpace ? 3 : 2));
currentLine += '\n';
outParsableInfo += currentLine;
}
//If inside block comment
else
{
TrimRight(currentLine);
bool check = checkFinishedGettingParsableContent().DS_TRY();
if(check)
break;
currentLine += '\n';
outParsableInfo += currentLine;
}
currentLine.clear();
}
} //else
//Special case for last character/line
if(i == source.size() - 1 && insideCommentToParse)
{
TrimRight(currentLine);
if(singleLineComments)
{
bool check = checkFinishedGettingParsableContent().DS_TRY();
if(check)
break;
currentLine.erase(0, (preceedingSpace ? 3 : 2));
outParsableInfo += currentLine;
contentReadyToParse = true;
}
else
{
bool check = checkFinishedGettingParsableContent().DS_TRY();
if(check)
break;
//resetPrefixState();
return DS_ERROR_MSG("Missing closing */ in block comment");
}
}
} //for(int i = 0; i < source.size(); i++)
if(!contentReadyToParse)
outParsableInfo.clear();
return {};
}
inline bool MergeYAML_NodeChildren( YAML::NodePtr nodeToMergeFrom,
YAML::NodePtr nodeToMergeTo,
YAML::ResourceHandle& yamlResouce)
{
ssLOG_FUNC_DEBUG();
if(!nodeToMergeFrom->IsMap() || !nodeToMergeTo->IsMap())
{
ssLOG_ERROR("Merge node is not map");
return false;
}
for(int i = 0; i < nodeToMergeFrom->GetChildrenCount(); ++i)
{
std::string key = nodeToMergeFrom ->GetMapKeyScalarAt<std::string>(i)
.DS_TRY_ACT(return false);
if(!ExistAndHasChild(nodeToMergeTo, key, true))
{
YAML::NodePtr fromNode = nodeToMergeFrom->GetMapValueNodeAt(i);
fromNode->CloneToMapChild(key, nodeToMergeTo, yamlResouce).DS_TRY_ACT(return false);
}
}
return true;
}
//TODO: Replace with string escape in libyaml wrapper
inline std::string GetEscapedYAMLString(const std::string& input)
{
std::string output = "\"";
for(char c : input)
{
switch(c)
{
case '\\': output += "\\\\"; break;
case '\"': output += "\\\""; break;
case '\'': output += "\\\'"; break;
case '\n': output += "\\n"; break;
case '\t': output += "\\t"; break;
default: output += c;
}
}
output += "\"";
return output;
}
inline bool ParseIncludes(const std::string& line, std::string& outIncludePath)
{
//Skip if not an include line
if(line.find("#include") == std::string::npos)
return false;
size_t firstQuote = line.find('\"');
size_t firstBracket = line.find('<');
//Skip if no valid include format found
if(firstQuote == std::string::npos && firstBracket == std::string::npos)
return false;
bool isQuoted = firstQuote != std::string::npos &&
(firstBracket == std::string::npos || firstQuote < firstBracket);
size_t start = isQuoted ? firstQuote + 1 : firstBracket + 1;
size_t end = line.find(isQuoted ? '\"' : '>', start);
if(end == std::string::npos)
return false;
outIncludePath = line.substr(start, end - start);
return true;
}
template<typename T>
bool ParsePlatformProfileMap( YAML::ConstNodePtr node,
const std::string& key,
std::unordered_map<PlatformName, T>& result,
const std::string& errorMessage)
{
if(ExistAndHasChild(node, key))
{
YAML::ConstNodePtr mapNode = node->GetMapValueNode(key);
//If we skip platform profile
T defaultValue;
if(defaultValue.IsYAML_NodeParsableAsDefault(mapNode))
{
if(defaultValue.ParseYAML_NodeWithProfile(mapNode, "DefaultProfile"))
result["DefaultPlatform"] = defaultValue;
else
return false;
}
else
{
if(!CheckNodeRequirement(node, key, YAML::NodeType::Map, false, true))
return false;
for(int i = 0; i < mapNode->GetChildrenCount(); ++i)
{
PlatformName platform =
mapNode ->GetMapKeyScalarAt<std::string>(i)
.DS_TRY_ACT(ssLOG_ERROR(DS_TMP_ERROR.ToString()); return false);
T value;
YAML::ConstNodePtr currentNode = mapNode->GetMapValueNodeAt(i);
if(!value.ParseYAML_Node(currentNode))
{
ssLOG_ERROR("ScriptInfo: Failed to parse " << errorMessage);
return false;
}
result[platform] = value;
}
}
}
return true;
}
using SubstitutionMap = std::unordered_map<std::string, std::vector<std::string>>;
DS::Result<void>
PerformSubstitutionsWithInfo( const SubstitutionMap& substitutionMap,
const std::string& escapedString,
const std::vector<std::string>& foundSubstitutions,
const std::vector<int>& substitutionsLocations,
const std::vector<int>& substitutionsLengths,
std::string& inOutSubstitutedString,
const std::vector<char>& escapeChars,
int substituteValueIndex = 0)
{
ssLOG_FUNC_DEBUG();
inOutSubstitutedString = escapedString;
for(int i = foundSubstitutions.size() - 1; i >= 0; --i)
{
const std::string& substitution = foundSubstitutions[i];
if(substitutionMap.count(substitution) == 0)
{
ssLOG_DEBUG("substitution: " << substitution << " not found in substitution map, "
"skipping...");
continue;
}
//The substitution values can either be 1
//(in which case will be the same value regardless of substituteValueIndex)
//Or the index being requested.
int useIndex = substituteValueIndex;
if(substitutionMap.at(substitution).size() == 1)
useIndex = 0;
DS_ASSERT_LT(useIndex, substitutionMap.at(substitution).size());
std::string currentValue = substitutionMap.at(substitution).at(useIndex);
//Escape escapes character at the end if any
{
if(!currentValue.empty())
{
int currentValIndex = currentValue.size();
while(currentValIndex-- > 0)
{
bool found = false;
for(int j = 0; j < escapeChars.size(); ++j)
{
if(currentValue[currentValIndex] == escapeChars[j])
{
found = true;
break;
}
}
if(!found)
{
++currentValIndex;
break;
}
}
if(currentValIndex < currentValue.size())
{
const std::string foundEscapes = currentValue.substr(currentValIndex);
std::string newEndEscapes;
//Just repeat the escape characters
for(int j = 0; j < foundEscapes.size(); ++j)
{
newEndEscapes.push_back(foundEscapes[j]);
newEndEscapes.push_back(foundEscapes[j]);
}
currentValue = currentValue.substr(0, currentValIndex) + newEndEscapes;
}
}
}
ssLOG_DEBUG("Replacing \"" << substitution << "\" with \"" << currentValue <<
"\" in \"" << escapedString << "\"");
//TODO: Instead of doing replace, we should just memcpy and rebuild the string
inOutSubstitutedString.replace( substitutionsLocations.at(i),
substitutionsLengths.at(i),
currentValue);
}
return {};
}
//NOTE: This extracts substitutions and also allow escapes to happen for substitution characters.
// To escape a substitution character, just repeat it. (i.e. {{text}} will be escaped as {text})
void GetEscapedStringAndExtractSubstitutions( const std::string& processString,
std::string& outEscapedString,
std::vector<std::string>& outFoundSubstitutions,
std::vector<int>& outFoundLocations,
std::vector<int>& outFoundLength)
{
ssLOG_FUNC_DEBUG();
outEscapedString.clear();
std::string currentSubstitution;
int lastOpenBracketIndex = -1;
for(int i = 0; i < processString.size(); ++i)
{
if(processString[i] == '{')
{
if(i == processString.size() - 1)
{
if(lastOpenBracketIndex == -1 || lastOpenBracketIndex != i - 1)
ssLOG_WARNING("Unescaped { at the end: " << processString);
outEscapedString += '{';
continue;
}
//If we have opening bracket for the next character,
//this is an escaping character
if(processString[i + 1] == '{')
{
outEscapedString += '{';
if(lastOpenBracketIndex != -1)
currentSubstitution += '{';
++i;
continue;
}
if(lastOpenBracketIndex != -1)
{
ssLOG_WARNING( "Unescaped { at index " << lastOpenBracketIndex <<
": " << processString);
}
lastOpenBracketIndex = i;
currentSubstitution = "{";
outEscapedString += '{';
}
else if(processString[i] == '}')
{
//If we have closing bracket for the next character,
//this is an escaping character
if(i < processString.size() - 1 && processString[i + 1] == '}')
{
outEscapedString += '}';
if(lastOpenBracketIndex != -1)
currentSubstitution += '}';
++i;
continue;
}
//If there's no open bracket, give warning
if(lastOpenBracketIndex == -1)
{
ssLOG_WARNING("Unescaped } at index " << i << ": " << processString);
continue;
}
//Add substitution
outEscapedString += '}';
currentSubstitution += '}';
ssLOG_DEBUG("Substitution " << currentSubstitution << " found");
outFoundSubstitutions.push_back(currentSubstitution);
outFoundLocations.push_back(outEscapedString.size() - currentSubstitution.size());
outFoundLength.push_back(currentSubstitution.size());
//Reset
lastOpenBracketIndex = -1;
currentSubstitution.clear();
}
//Normal characters
else
{
outEscapedString += processString[i];
if(lastOpenBracketIndex != -1)
currentSubstitution += processString[i];
}
}
}
inline DS::Result<void> PerformSubstitutions( const SubstitutionMap& substitutionMap,
const std::vector<char>& escapeChars,
std::string& inOutSubstitutedString)
{
std::string escapedString;
std::vector<std::string> foundSubstitutions;
std::vector<int> substitutionsLocations;
std::vector<int> substitutionsLengths;
GetEscapedStringAndExtractSubstitutions(inOutSubstitutedString,
escapedString,
foundSubstitutions,
substitutionsLocations,
substitutionsLengths);
DS_ASSERT_EQ(foundSubstitutions.size(), substitutionsLocations.size());
DS_ASSERT_EQ(foundSubstitutions.size(), substitutionsLengths.size());
PerformSubstitutionsWithInfo( substitutionMap,
escapedString,
foundSubstitutions,
substitutionsLocations,
substitutionsLengths,
inOutSubstitutedString,
escapeChars)
.DS_TRY();
return {};
}
inline DS::Result<void> PerformMultiSubstitutions( const SubstitutionMap& substitutionMap,
const std::vector<char>& escapeChars,
const std::string& inString,
std::vector<std::string>& outStrings)
{
std::string escapedString;
std::vector<std::string> foundSubstitutions;
std::vector<int> substitutionsLocations;
std::vector<int> substitutionsLengths;
GetEscapedStringAndExtractSubstitutions(inString,
escapedString,
foundSubstitutions,
substitutionsLocations,
substitutionsLengths);
DS_ASSERT_EQ(foundSubstitutions.size(), substitutionsLocations.size());
DS_ASSERT_EQ(foundSubstitutions.size(), substitutionsLengths.size());
int foundSize = -1;
for(int i = 0; i < foundSubstitutions.size(); ++i)
{
if(substitutionMap.count(foundSubstitutions[i]) > 0)
{
if(foundSize == -1)
foundSize = substitutionMap.at(foundSubstitutions[i]).size();
else
{
if(substitutionMap.at(foundSubstitutions[i]).size() != 1)
{
if(foundSize == 1)
{
foundSize = substitutionMap.at(foundSubstitutions[i]).size();
continue;
}
else if(foundSize == substitutionMap.at(foundSubstitutions[i]).size())
continue;
return DS_ERROR_MSG("Mismatching array size when substituting with " +
foundSubstitutions[i]);
}
}
}
}
//No substitutions in the input, just pass it back out
if(foundSize == -1)
{
outStrings.emplace_back(inString);
return {};
}
for(int i = 0; i < foundSize; ++i)
{
outStrings.emplace_back(std::string());
PerformSubstitutionsWithInfo( substitutionMap,
escapedString,
foundSubstitutions,
substitutionsLocations,
substitutionsLengths,
outStrings.back(),
escapeChars,
i)
.DS_TRY();
}
return {};
}
}
#endif