/
parser.cpp
791 lines (625 loc) · 18.6 KB
/
parser.cpp
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
/*
Copyright (C) 2005 - 2024
by Philippe Plantier <ayin@anathas.org>
Copyright (C) 2005 by Guillaume Melquiond <guillaume.melquiond@gmail.com>
Copyright (C) 2003 by David White <dave@whitevine.net>
Part of the Battle for Wesnoth Project https://www.wesnoth.org/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY.
See the COPYING file for more details.
*/
/**
* @file
* Read/Write & analyze WML- and config-files.
*/
#include "serialization/parser.hpp"
#include "config.hpp"
#include "gettext.hpp"
#include "log.hpp"
#include "serialization/preprocessor.hpp"
#include "serialization/string_utils.hpp"
#include "serialization/tokenizer.hpp"
#include "serialization/validator.hpp"
#include "wesconfig.h"
#include <boost/algorithm/string/replace.hpp>
#include <boost/iostreams/filter/bzip2.hpp>
#include <boost/iostreams/filtering_stream.hpp>
#if defined(_MSC_VER)
#pragma warning(push)
#pragma warning(disable : 4456)
#pragma warning(disable : 4458)
#endif
#include <boost/iostreams/filter/gzip.hpp>
#if defined(_MSC_VER)
#pragma warning(pop)
#endif
#include <stack>
static lg::log_domain log_config("config");
#define ERR_CF LOG_STREAM(err, log_config)
#define WRN_CF LOG_STREAM(warn, log_config)
#define LOG_CF LOG_STREAM(info, log_config)
static const std::size_t max_recursion_levels = 1000;
namespace
{
// ==================================================================================
// PARSER
// ==================================================================================
class parser
{
parser() = delete;
parser(const parser&) = delete;
parser& operator=(const parser&) = delete;
public:
parser(config& cfg, std::istream& in, abstract_validator* validator = nullptr)
: cfg_(cfg)
, tok_(in)
, validator_(validator)
, elements()
{
}
~parser()
{
}
void operator()();
private:
void parse_element();
void parse_variable();
std::string lineno_string(utils::string_map& map,
const std::string& lineno,
const std::string& error_string,
const std::string& hint_string = "",
const std::string& debug_string = "");
void error(const std::string& message, const std::string& pos_format = "");
struct element
{
element(config* cfg, const std::string& name, int start_line = 0, const std::string& file = "")
: cfg(cfg)
, name(name)
, start_line(start_line)
, file(file)
{
}
config* cfg;
std::string name;
int start_line;
std::string file;
};
config& cfg_;
tokenizer tok_;
abstract_validator* validator_;
std::stack<element> elements;
};
void parser::operator()()
{
cfg_.clear();
elements.emplace(&cfg_, "");
if(validator_) {
validator_->open_tag("", cfg_, tok_.get_start_line(), tok_.get_file());
}
do {
tok_.next_token();
switch(tok_.current_token().type) {
case token::LF:
continue;
case '[':
parse_element();
break;
case token::STRING:
parse_variable();
break;
default:
if(static_cast<unsigned char>(tok_.current_token().value[0]) == 0xEF &&
static_cast<unsigned char>(tok_.next_token().value[0]) == 0xBB &&
static_cast<unsigned char>(tok_.next_token().value[0]) == 0xBF
) {
utils::string_map i18n_symbols;
std::stringstream ss;
ss << tok_.get_start_line() << " " << tok_.get_file();
ERR_CF << lineno_string(i18n_symbols, ss.str(), "Skipping over a utf8 BOM at $pos");
} else {
error(_("Unexpected characters at line start"));
}
break;
case token::END:
break;
}
} while(tok_.current_token().type != token::END);
// The main element should be there. If it is not, this is a parser error.
assert(!elements.empty());
if(validator_) {
element& el = elements.top();
validator_->validate(*el.cfg, el.name, el.start_line, el.file);
validator_->close_tag();
}
if(elements.size() != 1) {
utils::string_map i18n_symbols;
i18n_symbols["tag"] = elements.top().name;
std::stringstream ss;
ss << elements.top().start_line << " " << elements.top().file;
error(lineno_string(i18n_symbols, ss.str(),
_("Missing closing tag for tag [$tag]"),
_("expected at $pos")),
_("opened at $pos")
);
}
}
void parser::parse_element()
{
tok_.next_token();
std::string elname;
config* current_element = nullptr;
config* parent = nullptr;
switch(tok_.current_token().type) {
case token::STRING: // [element]
elname = tok_.current_token().value;
if(tok_.next_token().type != ']') {
error(_("Unterminated [element] tag"));
}
// Add the element
parent = elements.top().cfg;
current_element = &(parent->add_child(elname));
elements.emplace(current_element, elname, tok_.get_start_line(), tok_.get_file());
if(validator_) {
validator_->open_tag(elname, *parent, tok_.get_start_line(), tok_.get_file());
}
break;
case '+': // [+element]
if(tok_.next_token().type != token::STRING) {
error(_("Invalid tag name"));
}
elname = tok_.current_token().value;
if(tok_.next_token().type != ']') {
error(_("Unterminated [+element] tag"));
}
// Find the last child of the current element whose name is element
parent = elements.top().cfg;
if(auto c = parent->optional_child(elname, -1)) {
current_element = c.ptr();
if(validator_) {
validator_->open_tag(elname, *parent, tok_.get_start_line(), tok_.get_file(), true);
}
} else {
current_element = &parent->add_child(elname);
if(validator_) {
validator_->open_tag(elname, *parent, tok_.get_start_line(), tok_.get_file());
}
}
elements.emplace(current_element, elname, tok_.get_start_line(), tok_.get_file());
break;
case '/': // [/element]
if(tok_.next_token().type != token::STRING) {
error(_("Invalid closing tag name"));
}
elname = tok_.current_token().value;
if(tok_.next_token().type != ']') {
error(_("Unterminated closing tag"));
}
if(elements.size() <= 1) {
error(_("Unexpected closing tag"));
}
if(elname != elements.top().name) {
utils::string_map i18n_symbols;
i18n_symbols["tag1"] = elements.top().name;
i18n_symbols["tag2"] = elname;
std::stringstream ss;
ss << elements.top().start_line << " " << elements.top().file;
error(lineno_string(i18n_symbols, ss.str(),
_("Found invalid closing tag [/$tag2] for tag [$tag1]"),
_("opened at $pos")),
_("closed at $pos")
);
}
if(validator_) {
element& el = elements.top();
validator_->validate(*el.cfg, el.name, el.start_line, el.file);
validator_->close_tag();
}
elements.pop();
break;
default:
error(_("Invalid tag name"));
}
}
void parser::parse_variable()
{
config& cfg = *elements.top().cfg;
std::vector<std::string> variables;
variables.emplace_back();
while(tok_.current_token().type != '=') {
switch(tok_.current_token().type) {
case token::STRING:
if(!variables.back().empty()) {
variables.back() += ' ';
}
variables.back() += tok_.current_token().value;
break;
case ',':
if(variables.back().empty()) {
error(_("Empty variable name"));
} else {
variables.emplace_back();
}
break;
default:
error(_("Unexpected characters after variable name (expected , or =)"));
break;
}
tok_.next_token();
}
if(variables.back().empty()) {
error(_("Empty variable name"));
}
t_string_base buffer;
std::vector<std::string>::const_iterator curvar = variables.begin();
bool ignore_next_newlines = false, previous_string = false;
while(true) {
tok_.next_token();
assert(curvar != variables.end());
switch(tok_.current_token().type) {
case ',':
if((curvar + 1) != variables.end()) {
if(buffer.translatable()) {
cfg[*curvar] = t_string(buffer);
} else {
cfg[*curvar] = buffer.value();
}
if(validator_) {
validator_->validate_key(cfg, *curvar, cfg[*curvar], tok_.get_start_line(), tok_.get_file());
}
buffer = t_string_base();
++curvar;
} else {
buffer += ",";
}
break;
case '_':
tok_.next_token();
switch(tok_.current_token().type) {
case token::UNTERMINATED_QSTRING:
error(_("Unterminated quoted string"));
break;
case token::QSTRING:
buffer += t_string_base(tok_.current_token().value, tok_.textdomain());
break;
default:
buffer += "_";
buffer += tok_.current_token().value;
break;
case token::END:
case token::LF:
buffer += "_";
goto finish;
}
break;
case '+':
ignore_next_newlines = true;
continue;
case token::STRING:
if(previous_string) {
buffer += " ";
}
[[fallthrough]];
default:
buffer += tok_.current_token().value;
break;
case token::QSTRING:
buffer += tok_.current_token().value;
break;
case token::UNTERMINATED_QSTRING:
error(_("Unterminated quoted string"));
break;
case token::LF:
if(ignore_next_newlines) {
continue;
}
[[fallthrough]];
case token::END:
goto finish;
}
previous_string = tok_.current_token().type == token::STRING;
ignore_next_newlines = false;
}
finish:
if(buffer.translatable()) {
cfg[*curvar] = t_string(buffer);
} else {
cfg[*curvar] = buffer.value();
}
if(validator_) {
validator_->validate_key(cfg, *curvar, cfg[*curvar], tok_.get_start_line(), tok_.get_file());
}
while(++curvar != variables.end()) {
cfg[*curvar] = "";
}
}
/**
* This function is crap. Don't use it on a string_map with prefixes.
*/
std::string parser::lineno_string(utils::string_map& i18n_symbols,
const std::string& lineno,
const std::string& error_string,
const std::string& hint_string,
const std::string& debug_string)
{
i18n_symbols["pos"] = ::lineno_string(lineno);
std::string result = error_string;
if(!hint_string.empty()) {
result += '\n' + hint_string;
}
if(!debug_string.empty()) {
result += '\n' + debug_string;
}
for(utils::string_map::value_type& var : i18n_symbols) {
boost::algorithm::replace_all(result, std::string("$") + var.first, std::string(var.second));
}
return result;
}
void parser::error(const std::string& error_type, const std::string& pos_format)
{
std::string hint_string = pos_format;
if(hint_string.empty()) {
hint_string = _("at $pos");
}
utils::string_map i18n_symbols;
i18n_symbols["error"] = error_type;
std::stringstream ss;
ss << tok_.get_start_line() << " " << tok_.get_file();
#ifdef DEBUG_TOKENIZER
i18n_symbols["value"] = tok_.current_token().value;
i18n_symbols["previous_value"] = tok_.previous_token().value;
const std::string& tok_state = _("Value: '$value' Previous: '$previous_value'");
#else
const std::string& tok_state = "";
#endif
const std::string& message = lineno_string(i18n_symbols, ss.str(), "$error", hint_string, tok_state);
throw config::error(message);
}
// ==================================================================================
// HELPERS FOR WRITE_KEY_VAL
// ==================================================================================
/**
* Copies a string fragment and converts it to a suitable format for WML.
* (I.e., quotes are doubled.)
*/
std::string escaped_string(const std::string::const_iterator& begin, const std::string::const_iterator& end)
{
std::string res;
std::string::const_iterator iter = begin;
while(iter != end) {
const char c = *iter;
res.append(c == '"' ? 2 : 1, c);
++iter;
}
return res;
}
/**
* Copies a string and converts it to a suitable format for WML.
* (I.e., quotes are doubled.)
*/
inline std::string escaped_string(const std::string& value)
{
return escaped_string(value.begin(), value.end());
}
class write_key_val_visitor
#ifdef USING_BOOST_VARIANT
: public boost::static_visitor<void>
#endif
{
public:
write_key_val_visitor(std::ostream& out, unsigned level, std::string& textdomain, const std::string& key)
: out_(out)
, level_(level)
, textdomain_(textdomain)
, key_(key)
{
}
// Generic visitor just streams "key=value".
template<typename T>
void operator()(const T& v) const
{
indent();
out_ << key_ << '=' << v << '\n';
}
//
// Specialized visitors for things that go in quotes:
//
void operator()(const utils::monostate&) const
{
// Treat blank values as nonexistent which fits better than treating them as empty strings.
}
void operator()(const std::string& s) const
{
indent();
out_ << key_ << '=' << '"' << escaped_string(s) << '"' << '\n';
}
void operator()(const t_string& s) const;
private:
void indent() const
{
for(unsigned i = 0; i < level_; ++i) {
out_ << '\t';
}
}
std::ostream& out_;
const unsigned level_;
std::string& textdomain_;
const std::string& key_;
};
/**
* Writes all the parts of a translatable string.
*
* @note If the first part is translatable and in the wrong textdomain,
* the textdomain change has to happen before the attribute name.
* That is the reason for not outputting the key beforehand and
* letting this function do it.
*/
void write_key_val_visitor::operator()(const t_string& value) const
{
bool first = true;
for(t_string::walker w(value); !w.eos(); w.next()) {
if(!first) {
out_ << " +\n";
}
if(w.translatable() && w.textdomain() != textdomain_) {
textdomain_ = w.textdomain();
out_ << "#textdomain " << textdomain_ << '\n';
}
indent();
if(first) {
out_ << key_ << '=';
} else {
out_ << '\t';
}
if(w.translatable()) {
out_ << '_';
}
out_ << '"' << escaped_string(w.begin(), w.end()) << '"';
first = false;
}
out_ << '\n';
}
} // end anon namespace
// ==================================================================================
// PUBLIC FUNCTION IMPLEMENTATIONS
// ==================================================================================
void read(config& cfg, std::istream& in, abstract_validator* validator)
{
parser(cfg, in, validator)();
}
void read(config& cfg, const std::string& in, abstract_validator* validator)
{
std::istringstream ss(in);
parser(cfg, ss, validator)();
}
template<typename decompressor>
void read_compressed(config& cfg, std::istream& file, abstract_validator* validator)
{
// An empty gzip file seems to confuse boost on MSVC, so return early if this is the case.
if(file.peek() == EOF) {
return;
}
boost::iostreams::filtering_stream<boost::iostreams::input> filter;
filter.push(decompressor());
filter.push(file);
/* This causes gzip_error (and the corresponding bz2 error, std::ios_base::failure) to be
* thrown here. save_index_class::data expects that and config_cache::read_cache and other
* functions are also capable of catching.
*
* Note that parser(cuff, filter,validator)(); -> tokenizer::tokenizer can throw exceptions
* too (meaning this function already threw these exceptions before this patch).
*
* We try to fix https://svn.boost.org/trac/boost/ticket/5237 by not creating empty gz files.
*/
filter.exceptions(filter.exceptions() | std::ios_base::badbit);
/*
* It sometimes seems the file is not empty but still has no real data.
* Filter that case here. The previous test might be no longer required but keep it for now.
*
* On msvc filter.peek() != EOF does not imply filter.good().
* We never create empty compressed gzip files because boosts gzip fails at doing that, but
* empty compressed bz2 files are possible.
*/
if(filter.peek() == EOF) {
LOG_CF << "Empty compressed file or error at reading a compressed file.";
return;
}
if(!filter.good()) {
LOG_CF << " filter.peek() != EOF but !filter.good()."
<< "This indicates a malformed gz stream and can make Wesnoth crash.";
}
parser(cfg, filter, validator)();
}
/** Might throw a std::ios_base::failure especially a gzip_error. */
void read_gz(config& cfg, std::istream& file, abstract_validator* validator)
{
read_compressed<boost::iostreams::gzip_decompressor>(cfg, file, validator);
}
/** Might throw a std::ios_base::failure especially bzip2_error. */
void read_bz2(config& cfg, std::istream& file, abstract_validator* validator)
{
read_compressed<boost::iostreams::bzip2_decompressor>(cfg, file, validator);
}
void write_key_val(std::ostream& out,
const std::string& key,
const config::attribute_value& value,
unsigned level,
std::string& textdomain)
{
value.apply_visitor(write_key_val_visitor(out, level, textdomain, key));
}
void write_open_child(std::ostream& out, const std::string& child, unsigned int level)
{
out << std::string(level, '\t') << '[' << child << "]\n";
}
void write_close_child(std::ostream& out, const std::string& child, unsigned int level)
{
out << std::string(level, '\t') << "[/" << child << "]\n";
}
static void write_internal(const config& cfg, std::ostream& out, std::string& textdomain, std::size_t tab = 0)
{
if(tab > max_recursion_levels) {
throw config::error("Too many recursion levels in config write");
}
for(const config::attribute& i : cfg.attribute_range()) {
if(!config::valid_attribute(i.first)) {
ERR_CF << "Config contains invalid attribute name '" << i.first << "', skipping...";
continue;
}
write_key_val(out, i.first, i.second, tab, textdomain);
}
for(const config::any_child item : cfg.all_children_range()) {
if(!config::valid_tag(item.key)) {
ERR_CF << "Config contains invalid tag name '" << item.key << "', skipping...";
continue;
}
write_open_child(out, item.key, tab);
write_internal(item.cfg, out, textdomain, tab + 1);
write_close_child(out, item.key, tab);
}
}
static void write_internal(const configr_of& cfg, std::ostream& out, std::string& textdomain, std::size_t tab = 0)
{
if(tab > max_recursion_levels) {
throw config::error("Too many recursion levels in config write");
}
if(cfg.data_) {
write_internal(*cfg.data_, out, textdomain, tab);
}
for(const auto& pair : cfg.subtags_) {
assert(pair.first && pair.second);
if(!config::valid_tag(*pair.first)) {
ERR_CF << "Config contains invalid tag name '" << *pair.first << "', skipping...";
continue;
}
write_open_child(out, *pair.first, tab);
write_internal(*pair.second, out, textdomain, tab + 1);
write_close_child(out, *pair.first, tab);
}
}
void write(std::ostream& out, const configr_of& cfg, unsigned int level)
{
std::string textdomain = PACKAGE;
write_internal(cfg, out, textdomain, level);
}
template<typename compressor>
void write_compressed(std::ostream& out, const configr_of& cfg)
{
boost::iostreams::filtering_stream<boost::iostreams::output> filter;
filter.push(compressor());
filter.push(out);
write(filter, cfg);
// prevent empty gz files because of https://svn.boost.org/trac/boost/ticket/5237
filter << "\n";
}
void write_gz(std::ostream& out, const configr_of& cfg)
{
write_compressed<boost::iostreams::gzip_compressor>(out, cfg);
}
void write_bz2(std::ostream& out, const configr_of& cfg)
{
write_compressed<boost::iostreams::bzip2_compressor>(out, cfg);
}