File: JsonValidator.cpp

package info (click to toggle)
vcmi 1.6.5%2Bdfsg-2
  • links: PTS, VCS
  • area: contrib
  • in suites: forky, sid, trixie
  • size: 32,060 kB
  • sloc: cpp: 238,971; python: 265; sh: 224; xml: 157; ansic: 78; objc: 61; makefile: 49
file content (702 lines) | stat: -rw-r--r-- 22,635 bytes parent folder | download
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
/*
 * JsonValidator.cpp, part of VCMI engine
 *
 * Authors: listed in file AUTHORS in main folder
 *
 * License: GNU General Public License v2.0 or later
 * Full text of license available in license.txt file, in main folder
 *
 */

#include "StdInc.h"
#include "JsonValidator.h"

#include "JsonUtils.h"

#include "../VCMI_Lib.h"
#include "../filesystem/Filesystem.h"
#include "../modding/ModScope.h"
#include "../modding/CModHandler.h"
#include "../texts/TextOperations.h"
#include "../ScopeGuard.h"

VCMI_LIB_NAMESPACE_BEGIN

/// Searches for keys similar to 'target' in 'candidates' map
/// Returns closest match or empty string if no suitable candidates are found
static std::string findClosestMatch(const JsonMap & candidates, const std::string & target)
{
	// Maximum distance at which we can consider strings to be similar
	// If strings have more different symbols than this number then it is not a typo, but a completely different word
	static constexpr int maxDistance = 5;
	int bestDistance = maxDistance;
	std::string bestMatch;

	for (auto const & candidate : candidates)
	{
		int newDistance = TextOperations::getLevenshteinDistance(candidate.first, target);

		if (newDistance < bestDistance)
		{
			bestDistance = newDistance;
			bestMatch = candidate.first;
		}
	}
	return bestMatch;
}

static std::string emptyCheck(JsonValidator & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
{
	// check is not needed - e.g. incorporated into another check
	return "";
}

static std::string notImplementedCheck(JsonValidator & validator,
								const JsonNode & baseSchema,
								const JsonNode & schema,
								const JsonNode & data)
{
	return "Not implemented entry in schema";
}

static std::string schemaListCheck(JsonValidator & validator,
							const JsonNode & baseSchema,
							const JsonNode & schema,
							const JsonNode & data,
							const std::string & errorMsg,
							const std::function<bool(size_t)> & isValid)
{
	std::string errors = "<tested schemas>\n";
	size_t result = 0;

	for(const auto & schemaEntry : schema.Vector())
	{
		std::string error = validator.check(schemaEntry, data);
		if (error.empty())
		{
			result++;
		}
		else
		{
			errors += error;
			errors += "<end of schema>\n";
		}
	}
	if (isValid(result))
		return "";
	else
		return validator.makeErrorMessage(errorMsg) + errors;
}

static std::string allOfCheck(JsonValidator & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
{
	return schemaListCheck(validator, baseSchema, schema, data, "Failed to pass all schemas", [&schema](size_t count)
	{
		return count == schema.Vector().size();
	});
}

static std::string anyOfCheck(JsonValidator & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
{
	return schemaListCheck(validator, baseSchema, schema, data, "Failed to pass any schema", [](size_t count)
	{
		return count > 0;
	});
}

static std::string oneOfCheck(JsonValidator & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
{
	return schemaListCheck(validator, baseSchema, schema, data, "Failed to pass exactly one schema", [](size_t count)
	{
		return count == 1;
	});
}

static std::string notCheck(JsonValidator & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
{
	if (validator.check(schema, data).empty())
		return validator.makeErrorMessage("Successful validation against negative check");
	return "";
}

static std::string enumCheck(JsonValidator & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
{
	for(const auto & enumEntry : schema.Vector())
	{
		if (data == enumEntry)
			return "";
	}

	std::string errorMessage = "Key must have one of predefined values:" + schema.toCompactString();

	return validator.makeErrorMessage(errorMessage);
}

static std::string constCheck(JsonValidator & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
{
	if (data == schema)
		return "";

	return validator.makeErrorMessage("Key must have have constant value");
}

static std::string typeCheck(JsonValidator & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
{
	static const std::unordered_map<std::string, JsonNode::JsonType> stringToType =
	{
		{"null",   JsonNode::JsonType::DATA_NULL},
		{"boolean", JsonNode::JsonType::DATA_BOOL},
		{"number", JsonNode::JsonType::DATA_FLOAT},
		{"integer", JsonNode::JsonType::DATA_INTEGER},
		{"string",  JsonNode::JsonType::DATA_STRING},
		{"array",  JsonNode::JsonType::DATA_VECTOR},
		{"object",  JsonNode::JsonType::DATA_STRUCT}
	};

	const auto & typeName = schema.String();
	auto it = stringToType.find(typeName);
	if(it == stringToType.end())
	{
		return validator.makeErrorMessage("Unknown type in schema:" + typeName);
	}

	JsonNode::JsonType type = it->second;

	// for "number" type both float and integer are allowed
	if(type == JsonNode::JsonType::DATA_FLOAT && data.isNumber())
		return "";

	if(type != data.getType() && data.getType() != JsonNode::JsonType::DATA_NULL)
		return validator.makeErrorMessage("Type mismatch! Expected " + schema.String());
	return "";
}

static std::string refCheck(JsonValidator & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
{
	std::string URI = schema.String();
	//node must be validated using schema pointed by this reference and not by data here
	//Local reference. Turn it into more easy to handle remote ref
	if (boost::algorithm::starts_with(URI, "#"))
	{
		const std::string name = validator.usedSchemas.back();
		const std::string nameClean = name.substr(0, name.find('#'));
		URI = nameClean + URI;
	}
	return validator.check(URI, data);
}

static std::string formatCheck(JsonValidator & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
{
	auto formats = validator.getKnownFormats();
	std::string errors;
	auto checker = formats.find(schema.String());
	if (checker != formats.end())
	{
		if (data.isString())
		{
			std::string result = checker->second(data);
			if (!result.empty())
				errors += validator.makeErrorMessage(result);
		}
		else
		{
			errors += validator.makeErrorMessage("Format value must be string: " + schema.String());
		}
	}
	else
		errors += validator.makeErrorMessage("Unsupported format type: " + schema.String());
	return errors;
}

static std::string maxLengthCheck(JsonValidator & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
{
	if (data.String().size() > schema.Float())
		return validator.makeErrorMessage((boost::format("String is longer than %d symbols") % schema.Float()).str());
	return "";
}

static std::string minLengthCheck(JsonValidator & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
{
	if (data.String().size() < schema.Float())
		return validator.makeErrorMessage((boost::format("String is shorter than %d symbols") % schema.Float()).str());
	return "";
}

static std::string maximumCheck(JsonValidator & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
{
	if (data.Float() > schema.Float())
		return validator.makeErrorMessage((boost::format("Value is bigger than %d") % schema.Float()).str());
	return "";
}

static std::string minimumCheck(JsonValidator & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
{
	if (data.Float() < schema.Float())
		return validator.makeErrorMessage((boost::format("Value is smaller than %d") % schema.Float()).str());
	return "";
}

static std::string exclusiveMaximumCheck(JsonValidator & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
{
	if (data.Float() >= schema.Float())
		return validator.makeErrorMessage((boost::format("Value is bigger than %d") % schema.Float()).str());
	return "";
}

static std::string exclusiveMinimumCheck(JsonValidator & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
{
	if (data.Float() <= schema.Float())
		return validator.makeErrorMessage((boost::format("Value is smaller than %d") % schema.Float()).str());
	return "";
}

static std::string multipleOfCheck(JsonValidator & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
{
	double result = data.Integer() / schema.Integer();
	if (!vstd::isAlmostEqual(floor(result), result))
		return validator.makeErrorMessage((boost::format("Value is not divisible by %d") % schema.Float()).str());
	return "";
}

static std::string itemEntryCheck(JsonValidator & validator, const JsonVector & items, const JsonNode & schema, size_t index)
{
	validator.currentPath.emplace_back();
	validator.currentPath.back().Float() = static_cast<double>(index);
	auto onExit = vstd::makeScopeGuard([&validator]()
	{
		validator.currentPath.pop_back();
	});

	if (!schema.isNull())
		return validator.check(schema, items[index]);
	return "";
}

static std::string itemsCheck(JsonValidator & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
{
	std::string errors;
	for (size_t i=0; i<data.Vector().size(); i++)
	{
		if (schema.getType() == JsonNode::JsonType::DATA_VECTOR)
		{
			if (schema.Vector().size() > i)
				errors += itemEntryCheck(validator, data.Vector(), schema.Vector()[i], i);
		}
		else
		{
			errors += itemEntryCheck(validator, data.Vector(), schema, i);
		}
	}
	return errors;
}

static std::string additionalItemsCheck(JsonValidator & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
{
	std::string errors;
	// "items" is struct or empty (defaults to empty struct) - validation always successful
	const JsonNode & items = baseSchema["items"];
	if (items.getType() != JsonNode::JsonType::DATA_VECTOR)
		return "";

	for (size_t i=items.Vector().size(); i<data.Vector().size(); i++)
	{
		if (schema.getType() == JsonNode::JsonType::DATA_STRUCT)
			errors += itemEntryCheck(validator, data.Vector(), schema, i);
		else if(!schema.isNull() && !schema.Bool())
			errors += validator.makeErrorMessage("Unknown entry found");
	}
	return errors;
}

static std::string minItemsCheck(JsonValidator & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
{
	if (data.Vector().size() < schema.Float())
		return validator.makeErrorMessage((boost::format("Length is smaller than %d") % schema.Float()).str());
	return "";
}

static std::string maxItemsCheck(JsonValidator & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
{
	if (data.Vector().size() > schema.Float())
		return validator.makeErrorMessage((boost::format("Length is bigger than %d") % schema.Float()).str());
	return "";
}

static std::string uniqueItemsCheck(JsonValidator & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
{
	if (schema.Bool())
	{
		for (auto itA = schema.Vector().begin(); itA != schema.Vector().end(); itA++)
		{
			auto itB = itA;
			while (++itB != schema.Vector().end())
			{
				if (*itA == *itB)
					return validator.makeErrorMessage("List must consist from unique items");
			}
		}
	}
	return "";
}

static std::string maxPropertiesCheck(JsonValidator & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
{
	if (data.Struct().size() > schema.Float())
		return validator.makeErrorMessage((boost::format("Number of entries is bigger than %d") % schema.Float()).str());
	return "";
}

static std::string minPropertiesCheck(JsonValidator & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
{
	if (data.Struct().size() < schema.Float())
		return validator.makeErrorMessage((boost::format("Number of entries is less than %d") % schema.Float()).str());
	return "";
}

static std::string uniquePropertiesCheck(JsonValidator & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
{
	for (auto itA = data.Struct().begin(); itA != data.Struct().end(); itA++)
	{
		auto itB = itA;
		while (++itB != data.Struct().end())
		{
			if (itA->second == itB->second)
				return validator.makeErrorMessage("List must consist from unique items");
		}
	}
	return "";
}

static std::string requiredCheck(JsonValidator & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
{
	std::string errors;
	for(const auto & required : schema.Vector())
	{
		if (data[required.String()].isNull() && data.getModScope() != "core")
			errors += validator.makeErrorMessage("Required entry " + required.String() + " is missing");
	}
	return errors;
}

static std::string dependenciesCheck(JsonValidator & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
{
	std::string errors;
	for(const auto & deps : schema.Struct())
	{
		if (!data[deps.first].isNull())
		{
			if (deps.second.getType() == JsonNode::JsonType::DATA_VECTOR)
			{
				JsonVector depList = deps.second.Vector();
				for(auto & depEntry : depList)
				{
					if (data[depEntry.String()].isNull())
						errors += validator.makeErrorMessage("Property " + depEntry.String() + " required for " + deps.first + " is missing");
				}
			}
			else
			{
				if (!validator.check(deps.second, data).empty())
					errors += validator.makeErrorMessage("Requirements for " + deps.first + " are not fulfilled");
			}
		}
	}
	return errors;
}

static std::string propertyEntryCheck(JsonValidator & validator, const JsonNode &node, const JsonNode & schema, const std::string & nodeName)
{
	validator.currentPath.emplace_back();
	validator.currentPath.back().String() = nodeName;
	auto onExit = vstd::makeScopeGuard([&validator]()
	{
		validator.currentPath.pop_back();
	});

	// there is schema specifically for this item
	if (!schema.isNull())
		return validator.check(schema, node);
	return "";
}

static std::string propertiesCheck(JsonValidator & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
{
	std::string errors;

	for(const auto & entry : data.Struct())
		errors += propertyEntryCheck(validator, entry.second, schema[entry.first], entry.first);
	return errors;
}

static std::string additionalPropertiesCheck(JsonValidator & validator, const JsonNode & baseSchema, const JsonNode & schema, const JsonNode & data)
{
	std::string errors;
	for(const auto & entry : data.Struct())
	{
		if (baseSchema["properties"].Struct().count(entry.first) == 0)
		{
			// try generic additionalItems schema
			if (schema.getType() == JsonNode::JsonType::DATA_STRUCT)
				errors += propertyEntryCheck(validator, entry.second, schema, entry.first);

			// or, additionalItems field can be bool which indicates if such items are allowed
			else if(!schema.isNull() && !schema.Bool()) // present and set to false - error
			{
				std::string bestCandidate = findClosestMatch(baseSchema["properties"].Struct(), entry.first);
				if (!bestCandidate.empty())
					errors += validator.makeErrorMessage("Unknown entry found: '" + entry.first + "'. Perhaps you meant '" + bestCandidate + "'?");
				else
					errors += validator.makeErrorMessage("Unknown entry found: " + entry.first);
			}
		}
	}
	return errors;
}

static bool testFilePresence(const std::string & scope, const ResourcePath & resource)
{
#ifndef ENABLE_MINIMAL_LIB
	std::set<std::string> allowedScopes;
	if(scope != ModScope::scopeBuiltin() && !scope.empty()) // all real mods may have dependencies
	{
		//NOTE: recursive dependencies are not allowed at the moment - update code if this changes
		bool found = true;
		allowedScopes = VLC->modh->getModDependencies(scope, found);

		if(!found)
			return false;

		allowedScopes.insert(ModScope::scopeBuiltin()); // all mods can use H3 files
	}
	allowedScopes.insert(scope); // mods can use their own files

	for(const auto & entry : allowedScopes)
	{
		if (CResourceHandler::get(entry)->existsResource(resource))
			return true;
	}
#endif
	return false;
}

#define TEST_FILE(scope, prefix, file, type) \
	if (testFilePresence(scope, ResourcePath(prefix + file, type))) \
	return ""

static std::string testAnimation(const std::string & path, const std::string & scope)
{
	TEST_FILE(scope, "Sprites/", path, EResType::ANIMATION);
	TEST_FILE(scope, "Sprites/", path, EResType::JSON);
	return "Animation file \"" + path + "\" was not found";
}

static std::string textFile(const JsonNode & node)
{
	TEST_FILE(node.getModScope(), "", node.String(), EResType::JSON);
	return "Text file \"" + node.String() + "\" was not found";
}

static std::string musicFile(const JsonNode & node)
{
	TEST_FILE(node.getModScope(), "Music/", node.String(), EResType::SOUND);
	TEST_FILE(node.getModScope(), "", node.String(), EResType::SOUND);
	return "Music file \"" + node.String() + "\" was not found";
}

static std::string soundFile(const JsonNode & node)
{
	TEST_FILE(node.getModScope(), "Sounds/", node.String(), EResType::SOUND);
	return "Sound file \"" + node.String() + "\" was not found";
}

static std::string animationFile(const JsonNode & node)
{
	return testAnimation(node.String(), node.getModScope());
}

static std::string imageFile(const JsonNode & node)
{
	TEST_FILE(node.getModScope(), "Data/", node.String(), EResType::IMAGE);
	TEST_FILE(node.getModScope(), "Sprites/", node.String(), EResType::IMAGE);
	if (node.String().find(':') != std::string::npos)
		return testAnimation(node.String().substr(0, node.String().find(':')), node.getModScope());
	return "Image file \"" + node.String() + "\" was not found";
}

static std::string videoFile(const JsonNode & node)
{
	TEST_FILE(node.getModScope(), "Video/", node.String(), EResType::VIDEO);
	TEST_FILE(node.getModScope(), "Video/", node.String(), EResType::VIDEO_LOW_QUALITY);
	return "Video file \"" + node.String() + "\" was not found";
}
#undef TEST_FILE

JsonValidator::TValidatorMap createCommonFields()
{
	JsonValidator::TValidatorMap ret;

	ret["format"] =  formatCheck;
	ret["allOf"] = allOfCheck;
	ret["anyOf"] = anyOfCheck;
	ret["oneOf"] = oneOfCheck;
	ret["enum"]  = enumCheck;
	ret["const"]  = constCheck;
	ret["type"]  = typeCheck;
	ret["not"]   = notCheck;
	ret["$ref"]  = refCheck;

	// fields that don't need implementation
	ret["title"] = emptyCheck;
	ret["$schema"] = emptyCheck;
	ret["default"] = emptyCheck;
	ret["defaultIOS"] = emptyCheck;
	ret["defaultAndroid"] = emptyCheck;
	ret["defaultWindows"] = emptyCheck;
	ret["description"] = emptyCheck;
	ret["definitions"] = emptyCheck;

	// Not implemented
	ret["propertyNames"] = notImplementedCheck;
	ret["contains"] = notImplementedCheck;
	ret["examples"] = notImplementedCheck;

	return ret;
}

JsonValidator::TValidatorMap createStringFields()
{
	JsonValidator::TValidatorMap ret = createCommonFields();
	ret["maxLength"] = maxLengthCheck;
	ret["minLength"] = minLengthCheck;

	ret["pattern"] = notImplementedCheck;
	return ret;
}

JsonValidator::TValidatorMap createNumberFields()
{
	JsonValidator::TValidatorMap ret = createCommonFields();
	ret["maximum"]    = maximumCheck;
	ret["minimum"]    = minimumCheck;
	ret["multipleOf"] = multipleOfCheck;

	ret["exclusiveMaximum"] = exclusiveMaximumCheck;
	ret["exclusiveMinimum"] = exclusiveMinimumCheck;
	return ret;
}

JsonValidator::TValidatorMap createVectorFields()
{
	JsonValidator::TValidatorMap ret = createCommonFields();
	ret["items"]           = itemsCheck;
	ret["minItems"]        = minItemsCheck;
	ret["maxItems"]        = maxItemsCheck;
	ret["uniqueItems"]     = uniqueItemsCheck;
	ret["additionalItems"] = additionalItemsCheck;
	return ret;
}

JsonValidator::TValidatorMap createStructFields()
{
	JsonValidator::TValidatorMap ret = createCommonFields();
	ret["additionalProperties"]  = additionalPropertiesCheck;
	ret["uniqueProperties"]      = uniquePropertiesCheck;
	ret["maxProperties"]         = maxPropertiesCheck;
	ret["minProperties"]         = minPropertiesCheck;
	ret["dependencies"]          = dependenciesCheck;
	ret["properties"]            = propertiesCheck;
	ret["required"]              = requiredCheck;

	ret["patternProperties"] = notImplementedCheck;
	return ret;
}

JsonValidator::TFormatMap createFormatMap()
{
	JsonValidator::TFormatMap ret;
	ret["textFile"]      = textFile;
	ret["musicFile"]     = musicFile;
	ret["soundFile"]     = soundFile;
	ret["animationFile"] = animationFile;
	ret["imageFile"]     = imageFile;
	ret["videoFile"]     = videoFile;

	//TODO:
	// uri-reference
	// uri-template
	// json-pointer

	return ret;
}

std::string JsonValidator::makeErrorMessage(const std::string &message)
{
	std::string errors;
	errors += "At ";
	if (!currentPath.empty())
	{
		for(const JsonNode &path : currentPath)
		{
			errors += "/";
			if (path.getType() == JsonNode::JsonType::DATA_STRING)
				errors += path.String();
			else
				errors += std::to_string(static_cast<unsigned>(path.Float()));
		}
	}
	else
		errors += "<root>";
	errors += "\n\t Error: " + message + "\n";
	return errors;
}

std::string JsonValidator::check(const std::string & schemaName, const JsonNode & data)
{
	usedSchemas.push_back(schemaName);
	auto onscopeExit = vstd::makeScopeGuard([this]()
	{
		usedSchemas.pop_back();
	});
	return check(JsonUtils::getSchema(schemaName), data);
}

std::string JsonValidator::check(const JsonNode & schema, const JsonNode & data)
{
	const TValidatorMap & knownFields = getKnownFieldsFor(data.getType());
	std::string errors;
	for(const auto & entry : schema.Struct())
	{
		auto checker = knownFields.find(entry.first);
		if (checker != knownFields.end())
			errors += checker->second(*this, schema, entry.second, data);
	}
	return errors;
}

const JsonValidator::TValidatorMap & JsonValidator::getKnownFieldsFor(JsonNode::JsonType type)
{
	static const TValidatorMap commonFields = createCommonFields();
	static const TValidatorMap numberFields = createNumberFields();
	static const TValidatorMap stringFields = createStringFields();
	static const TValidatorMap vectorFields = createVectorFields();
	static const TValidatorMap structFields = createStructFields();

	switch (type)
	{
		case JsonNode::JsonType::DATA_FLOAT:
		case JsonNode::JsonType::DATA_INTEGER:
			return numberFields;
		case JsonNode::JsonType::DATA_STRING: return stringFields;
		case JsonNode::JsonType::DATA_VECTOR: return vectorFields;
		case JsonNode::JsonType::DATA_STRUCT: return structFields;
		default: return commonFields;
	}
}

const JsonValidator::TFormatMap & JsonValidator::getKnownFormats()
{
	static const TFormatMap knownFormats = createFormatMap();
	return knownFormats;
}

VCMI_LIB_NAMESPACE_END