/
preprocessor.cpp
1735 lines (1410 loc) · 45.7 KB
/
preprocessor.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
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright (C) 2003 by David White <dave@whitevine.net>
Copyright (C) 2005 - 2017 by Guillaume Melquiond <guillaume.melquiond@gmail.com>
Part of the Battle for Wesnoth Project http://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
* WML preprocessor.
*/
#include "buffered_istream.hpp"
#include "config.hpp"
#include "filesystem.hpp"
#include "game_config.hpp"
#include "log.hpp"
#include "serialization/binary_or_text.hpp"
#include "serialization/parser.hpp"
#include "serialization/string_utils.hpp"
#include "version.hpp"
#include "wesconfig.h"
#include <stdexcept>
#include <deque>
static lg::log_domain log_preprocessor("preprocessor");
#define ERR_PREPROC LOG_STREAM(err, log_preprocessor)
#define WRN_PREPROC LOG_STREAM(warn, log_preprocessor)
#define LOG_PREPROC LOG_STREAM(info, log_preprocessor)
#define DBG_PREPROC LOG_STREAM(debug, log_preprocessor)
static std::string current_file_str = "CURRENT_FILE";
static std::string current_dir_str = "CURRENT_DIRECTORY";
// map associating each filename encountered to a number
static std::map<std::string, int> file_number_map;
static bool encode_filename = true;
static std::string preprocessor_error_detail_prefix = "\n ";
static const char OUTPUT_SEPARATOR = '\xFE';
// get filename associated to this code
static std::string get_filename(const std::string& file_code)
{
if(!encode_filename) {
return file_code;
}
std::stringstream s;
s << file_code;
int n = 0;
s >> std::hex >> n;
for(const auto& p : file_number_map) {
if(p.second == n) {
return p.first;
}
}
return "<unknown>";
}
// Get code associated to this filename
static std::string get_file_code(const std::string& filename)
{
if(!encode_filename) {
return filename;
}
// Current number of encountered filenames
static int current_file_number = 0;
int& fnum = file_number_map[utils::escape(filename, " \\")];
if(fnum == 0) {
fnum = ++current_file_number;
}
std::ostringstream shex;
shex << std::hex << fnum;
return shex.str();
}
// decode the filenames placed in a location
static std::string get_location(const std::string& loc)
{
std::string res;
std::vector<std::string> pos = utils::quoted_split(loc, ' ');
if(pos.empty()) {
return res;
}
std::vector<std::string>::const_iterator i = pos.begin(), end = pos.end();
while(true) {
res += get_filename(*(i++));
if(i == end) {
break;
}
res += ' ';
res += *(i++);
if(i == end) {
break;
}
res += ' ';
}
return res;
}
// ==================================================================================
// PREPROC_DEFINE IMPLEMENTATION
// ==================================================================================
bool preproc_define::operator==(const preproc_define& v) const
{
return value == v.value && arguments == v.arguments;
}
bool preproc_define::operator<(const preproc_define& v) const
{
if(location < v.location) {
return true;
}
if(v.location < location) {
return false;
}
return linenum < v.linenum;
}
void preproc_define::write_argument(config_writer& writer, const std::string& arg) const
{
const std::string key = "argument";
writer.open_child(key);
writer.write_key_val("name", arg);
writer.close_child(key);
}
void preproc_define::write(config_writer& writer, const std::string& name) const
{
const std::string key = "preproc_define";
writer.open_child(key);
writer.write_key_val("name", name);
writer.write_key_val("value", value);
writer.write_key_val("textdomain", textdomain);
writer.write_key_val("linenum", std::to_string(linenum));
writer.write_key_val("location", get_location(location));
for(const std::string& arg : arguments) {
write_argument(writer, arg);
}
writer.close_child(key);
}
void preproc_define::read_argument(const config& cfg)
{
arguments.push_back(cfg["name"]);
}
void preproc_define::read(const config& cfg)
{
value = cfg["value"].str();
textdomain = cfg["textdomain"].str();
linenum = cfg["linenum"];
location = cfg["location"].str();
for(const config& arg : cfg.child_range("argument")) {
read_argument(arg);
}
}
preproc_map::value_type preproc_define::read_pair(const config& cfg)
{
preproc_define second;
second.read(cfg);
return preproc_map::value_type(cfg["name"], second);
}
std::ostream& operator<<(std::ostream& stream, const preproc_define& def)
{
return stream << "value: " << def.value << " arguments: " << def.location;
}
std::ostream& operator<<(std::ostream& stream, const preproc_map::value_type& def)
{
return stream << def.second;
}
// ==================================================================================
// PREPROCESSOR BASE
// ==================================================================================
class preprocessor_streambuf;
/**
* Base class for preprocessing an input.
*/
class preprocessor
{
friend class preprocessor_streambuf;
protected:
/**
* Sets up a new preprocessor for stream buffer \a t.
* Saves the current preprocessing context of #parent_. It will be automatically restored on destruction.
*
* It relies on preprocessor_streambuf so it's implemented after that class is declared.
*/
preprocessor(preprocessor_streambuf& t);
preprocessor_streambuf& parent_;
public:
virtual ~preprocessor()
{
}
/** Allows specifying any actions that need to be called after the constructor completes. */
virtual void init()
{
}
/**
* Preprocesses and sends some text to the #parent_ buffer.
* @return false when the input has no data left.
*/
virtual bool get_chunk() = 0;
enum MODE { NO_PARSING, PARSES_FILE, PARSES_MACRO };
/** Returns the appropriate parsing mode for this preprocessor. */
virtual MODE parse_mode()
{
return NO_PARSING;
}
private:
std::string old_textdomain_;
std::string old_location_;
int old_linenum_;
};
// ==================================================================================
// PREPROCESSOR BUFFER
// ==================================================================================
/**
* Target for sending preprocessed output.
* Objects of this class can be plugged into an STL stream.
*/
class preprocessor_streambuf : public std::streambuf
{
public:
preprocessor_streambuf(preproc_map* def)
: std::streambuf()
, out_buffer_("")
, buffer_()
, preprocessor_queue_()
, defines_(def)
, default_defines_()
, textdomain_(PACKAGE)
, location_("")
, linenum_(0)
, quoted_(false)
{
}
/** Decodes the filenames placed in a location. */
std::string get_current_file();
void error(const std::string&, int);
void warning(const std::string&, int);
template<typename T, typename... A>
void add_preprocessor(A&&... args)
{
preprocessor_queue_.emplace_back(new T(*this, std::forward<A>(args)...));
preprocessor_queue_.back()->init();
}
void drop_preprocessor()
{
preprocessor_queue_.pop_back();
}
int depth() const
{
return preprocessor_queue_.size();
}
preprocessor* current() const
{
return preprocessor_queue_.empty() ? nullptr : preprocessor_queue_.back().get();
}
private:
preprocessor_streambuf(const preprocessor_streambuf& t)
: std::streambuf()
, out_buffer_("")
, buffer_()
, preprocessor_queue_()
, defines_(t.defines_)
, default_defines_()
, textdomain_(PACKAGE)
, location_("")
, linenum_(0)
, quoted_(t.quoted_)
{
}
/** Inherited from basic_streambuf. */
virtual int underflow() override;
void restore_old_preprocessor();
/** Buffer read by the STL stream. */
std::string out_buffer_;
/** Buffer filled by the #current_ preprocessor. */
std::stringstream buffer_;
/** Input preprocessor queue. */
std::deque<std::unique_ptr<preprocessor>> preprocessor_queue_;
preproc_map* defines_;
preproc_map default_defines_;
std::string textdomain_;
std::string location_;
int linenum_;
/**
* Set to true if one preprocessor for this target started to read a string.
* Deeper-nested preprocessors are then forbidden to.
*/
bool quoted_;
friend class preprocessor;
friend class preprocessor_file;
friend class preprocessor_data;
friend struct preprocessor_scope_helper;
};
/** Preprocessor constructor. */
preprocessor::preprocessor(preprocessor_streambuf& t)
: parent_(t)
, old_textdomain_(t.textdomain_)
, old_location_(t.location_)
, old_linenum_(t.linenum_)
{
}
/**
* Called by an STL stream whenever it has reached the end of #out_buffer_.
* Fills #buffer_ by calling the #current_ preprocessor, then copies its
* content into #out_buffer_.
* @return the first character of #out_buffer_ if any, EOF otherwise.
*/
int preprocessor_streambuf::underflow()
{
unsigned sz = 0;
if(char* gp = gptr()) {
if(gp < egptr()) {
// Sanity check: the internal buffer has not been totally consumed,
// should we force the caller to use what remains first?
return *gp;
}
// The buffer has been completely read; fill it again.
// Keep part of the previous buffer, to ensure putback capabilities.
sz = out_buffer_.size();
buffer_.str(std::string());
if(sz > 3) {
buffer_ << out_buffer_.substr(sz - 3);
sz = 3;
} else {
buffer_ << out_buffer_;
}
} else {
// The internal get-data pointer is null
}
const int desired_fill_amount = 2000;
while(current() && buffer_.rdbuf()->in_avail() < desired_fill_amount) {
// Process files and data chunks until the desired buffer size is reached
if(!current()->get_chunk()) {
// Drop the current preprocessor item from the queue.
restore_old_preprocessor();
}
}
// Update the internal state and data pointers
out_buffer_ = buffer_.str();
if(out_buffer_.empty()) {
return EOF;
}
char* begin = &*out_buffer_.begin();
unsigned bs = out_buffer_.size();
setg(begin, begin + sz, begin + bs);
if(sz >= bs) {
return EOF;
}
return static_cast<unsigned char>(*(begin + sz));
}
/**
* Restores the old preprocessing context.
* Appends location and domain directives to the buffer, so that the parser
* notices these changes.
*/
void preprocessor_streambuf::restore_old_preprocessor()
{
preprocessor* current = this->current();
if(!current->old_location_.empty()) {
buffer_ << OUTPUT_SEPARATOR << "line " << current->old_linenum_ << ' ' << current->old_location_ << '\n';
}
if(!current->old_textdomain_.empty() && textdomain_ != current->old_textdomain_) {
buffer_ << OUTPUT_SEPARATOR << "textdomain " << current->old_textdomain_ << '\n';
}
location_ = current->old_location_;
linenum_ = current->old_linenum_;
textdomain_ = current->old_textdomain_;
// Drop the preprocessor from the queue.
drop_preprocessor();
}
std::string preprocessor_streambuf::get_current_file()
{
unsigned nested_level = 0;
preprocessor* pre = nullptr;
// Iterate backwards over queue to get the last non-macro preprocessor.
for(auto p = preprocessor_queue_.rbegin(); p != preprocessor_queue_.rend(); ++p) {
pre = p->get();
if(!pre || pre->parse_mode() == preprocessor::PARSES_FILE) {
break;
}
if(pre->parse_mode() == preprocessor::PARSES_MACRO) {
++nested_level;
}
}
std::string res;
std::vector<std::string> pos = utils::quoted_split(location_, ' ');
if(pos.size() <= 2 * nested_level) {
return res;
}
return get_filename(pos[2 * nested_level]);
}
std::string lineno_string(const std::string& lineno)
{
std::vector<std::string> pos = utils::quoted_split(lineno, ' ');
std::vector<std::string>::const_iterator i = pos.begin(), end = pos.end();
std::string included_from = preprocessor_error_detail_prefix + "included from ";
std::string res;
while(i != end) {
const std::string& line = *(i++);
if(!res.empty()) {
res += included_from;
}
if(i != end) {
res += get_filename(*(i++));
} else {
res += "<unknown>";
}
res += ':' + line;
}
if(res.empty()) {
res = "???";
}
return res;
}
void preprocessor_streambuf::error(const std::string& error_type, int l)
{
std::string position, error;
std::ostringstream pos;
pos << l << ' ' << location_;
position = lineno_string(pos.str());
error = error_type + '\n';
error += "at " + position;
ERR_PREPROC << error << '\n';
throw preproc_config::error(error);
}
void preprocessor_streambuf::warning(const std::string& warning_type, int l)
{
std::string position, warning;
std::ostringstream pos;
pos << l << ' ' << location_;
position = lineno_string(pos.str());
warning = warning_type + '\n';
warning += "at " + position;
WRN_PREPROC << warning << '\n';
}
// ==================================================================================
// PREPROCESSOR FILE
// ==================================================================================
/**
* Specialized preprocessor for handling a file or a set of files.
* A preprocessor_file object is created when a preprocessor encounters an
* inclusion directive that resolves to a file or directory, e.g. '{themes/}'.
*/
class preprocessor_file : public preprocessor
{
public:
/** Constructor. It relies on preprocessor_data so it's implemented after that class is declared. */
preprocessor_file(preprocessor_streambuf& t, const std::string& name, size_t symbol_index = -1);
virtual void init() override;
/**
* Inserts and processes the next file in the list of included files.
* @return false if there is no next file.
*/
virtual bool get_chunk() override
{
while(pos_ != end_) {
const std::string& name = *(pos_++);
unsigned sz = name.size();
// Use reverse iterator to optimize testing
if(sz < 5 || !std::equal(name.rbegin(), name.rbegin() + 4, "gfc.")) {
continue;
}
parent_.add_preprocessor<preprocessor_file>(name);
return true;
}
return false;
}
private:
std::vector<std::string> files_;
std::vector<std::string>::const_iterator pos_, end_;
const std::string& name_;
bool is_directory_;
};
// ==================================================================================
// PREPROCESSOR DATA
// ==================================================================================
/**
* Specialized preprocessor for handling any kind of input stream.
* This is the core of the preprocessor.
*/
class preprocessor_data : public preprocessor
{
/** Description of a preprocessing chunk. */
struct token_desc
{
enum TOKEN_TYPE {
START, // Toplevel
PROCESS_IF, // Processing the "if" branch of a ifdef/ifndef (the "else" branch will be skipped)
PROCESS_ELSE, // Processing the "else" branch of a ifdef/ifndef
SKIP_IF, // Skipping the "if" branch of a ifdef/ifndef (the "else" branch, if any, will be processed)
SKIP_ELSE, // Skipping the "else" branch of a ifdef/ifndef
STRING, // Processing a string
VERBATIM, // Processing a verbatim string
MACRO_SPACE, // Processing between chunks of a macro call (skip spaces)
MACRO_CHUNK, // Processing inside a chunk of a macro call (stop on space or '(')
MACRO_PARENS // Processing a parenthesized macro argument
};
token_desc(TOKEN_TYPE type, const int stack_pos, const int linenum)
: type(type)
, stack_pos(stack_pos)
, linenum(linenum)
{
}
TOKEN_TYPE type;
/** Starting position in #strings_ of the delayed text for this chunk. */
int stack_pos;
int linenum;
};
/**
* Manages the lifetime of the @c std::istream pointer we own.
*
* Since @ref in_ uses the stream as well this object must be created
* before @ref in_ and destroyed after @ref in_ is destroyed.
*/
filesystem::scoped_istream in_scope_;
/** Input stream. */
buffered_istream in_;
std::string directory_;
/** Buffer for delayed input processing. */
std::vector<std::string> strings_;
/** Mapping of macro arguments to their content. */
std::unique_ptr<std::map<std::string, std::string>> local_defines_;
/** Stack of nested preprocessing chunks. */
std::vector<token_desc> tokens_;
/**
* Set to true whenever input tokens cannot be directly sent to the target
* buffer. For instance, this happens with macro arguments. In that case,
* the output is redirected toward #strings_ until it can be processed.
*/
int slowpath_;
/**
* Non-zero when the preprocessor has to skip some input text.
* Increased whenever entering a conditional branch that is not useful,
* e.g. a ifdef that evaluates to false.
*/
int skipping_;
int linenum_;
/** True iff we are currently parsing a macros content, otherwise false. */
bool is_define_;
std::string read_word();
std::string read_line();
std::string read_rest_of_line();
void skip_spaces();
void skip_eol();
void push_token(token_desc::TOKEN_TYPE);
void pop_token();
void put(char);
void put(const std::string& /*, int change_line = 0 */);
void conditional_skip(bool skip);
public:
preprocessor_data(preprocessor_streambuf&,
filesystem::scoped_istream,
const std::string& history,
const std::string& name,
int line,
const std::string& dir,
const std::string& domain,
std::unique_ptr<std::map<std::string, std::string>> defines,
bool is_define = false);
virtual bool get_chunk() override;
virtual preprocessor::MODE parse_mode() override
{
return is_define_ ? PARSES_MACRO : PARSES_FILE;
}
friend bool operator==(preprocessor_data::token_desc::TOKEN_TYPE, char);
friend bool operator==(char, preprocessor_data::token_desc::TOKEN_TYPE);
friend bool operator!=(preprocessor_data::token_desc::TOKEN_TYPE, char);
friend bool operator!=(char, preprocessor_data::token_desc::TOKEN_TYPE);
};
bool operator==(preprocessor_data::token_desc::TOKEN_TYPE, char)
{
throw std::logic_error("don't compare tokens with characters");
}
bool operator==(char lhs, preprocessor_data::token_desc::TOKEN_TYPE rhs)
{
return rhs == lhs;
}
bool operator!=(preprocessor_data::token_desc::TOKEN_TYPE rhs, char lhs)
{
return !(lhs == rhs);
}
bool operator!=(char lhs, preprocessor_data::token_desc::TOKEN_TYPE rhs)
{
return rhs != lhs;
}
/** preprocessor_file constructor. */
preprocessor_file::preprocessor_file(preprocessor_streambuf& t, const std::string& name, size_t symbol_index)
: preprocessor(t)
, files_()
, pos_()
, end_()
, name_(name)
, is_directory_(filesystem::is_directory(name))
{
if(is_directory_) {
filesystem::get_files_in_dir(name, &files_, nullptr,
filesystem::ENTIRE_FILE_PATH,
filesystem::SKIP_MEDIA_DIR,
filesystem::DO_REORDER
);
for(const std::string& fname : files_) {
size_t cpos = fname.rfind(" ");
if(cpos != std::string::npos && cpos >= symbol_index) {
std::stringstream ss;
ss << "Found filename containing whitespace: '" << filesystem::base_name(fname)
<< "' in included directory '" << name << "'.\nThe included symbol probably looks similar to '"
<< filesystem::directory_name(fname.substr(symbol_index)) << "'";
// TODO: find a real linenumber
parent_.error(ss.str(), -1);
}
}
} else {
// Handled in the init() function.
}
pos_ = files_.begin();
end_ = files_.end();
}
void preprocessor_file::init()
{
if(is_directory_) {
return;
}
filesystem::scoped_istream file_stream = filesystem::istream_file(name_);
if(!file_stream->good()) {
ERR_PREPROC << "Could not open file " << name_ << std::endl;
} else {
parent_.add_preprocessor<preprocessor_data>(std::move(file_stream), "",
filesystem::get_short_wml_path(name_), 1,
filesystem::directory_name(name_), parent_.textdomain_, nullptr
);
}
}
preprocessor_data::preprocessor_data(preprocessor_streambuf& t,
filesystem::scoped_istream i,
const std::string& history,
const std::string& name,
int linenum,
const std::string& directory,
const std::string& domain,
std::unique_ptr<std::map<std::string, std::string>> defines,
bool is_define)
: preprocessor(t)
, in_scope_(std::move(i))
, in_(*in_scope_)
, directory_(directory)
, strings_()
, local_defines_(std::move(defines))
, tokens_()
, slowpath_(0)
, skipping_(0)
, linenum_(linenum)
, is_define_(is_define)
{
std::ostringstream s;
s << history;
if(!name.empty()) {
if(!history.empty()) {
s << ' ';
}
s << get_file_code(name);
}
if(!t.location_.empty()) {
s << ' ' << t.linenum_ << ' ' << t.location_;
}
t.location_ = s.str();
t.linenum_ = linenum;
t.buffer_ << OUTPUT_SEPARATOR << "line " << linenum << ' ' << t.location_ << '\n';
if(t.textdomain_ != domain) {
t.buffer_ << OUTPUT_SEPARATOR << "textdomain " << domain << '\n';
t.textdomain_ = domain;
}
push_token(token_desc::START);
}
void preprocessor_data::push_token(token_desc::TOKEN_TYPE t)
{
tokens_.emplace_back(t, strings_.size(), linenum_);
if(t == token_desc::MACRO_SPACE) {
// Macro expansions do not have any associated storage at start.
return;
} else if(t == token_desc::STRING || t == token_desc::VERBATIM) {
/* Quoted strings are always inlined in the parent token. So
* they need neither storage nor metadata, unless the parent
* token is a macro expansion.
*/
token_desc::TOKEN_TYPE& outer_type = tokens_[tokens_.size() - 2].type;
if(outer_type != token_desc::MACRO_SPACE) {
return;
}
outer_type = token_desc::MACRO_CHUNK;
tokens_.back().stack_pos = strings_.size() + 1;
}
std::ostringstream s;
if(!skipping_ && slowpath_) {
s << OUTPUT_SEPARATOR << "line " << linenum_ << ' ' << parent_.location_ << "\n"
<< OUTPUT_SEPARATOR << "textdomain " << parent_.textdomain_ << '\n';
}
strings_.push_back(s.str());
}
void preprocessor_data::pop_token()
{
token_desc::TOKEN_TYPE inner_type = tokens_.back().type;
unsigned stack_pos = tokens_.back().stack_pos;
tokens_.pop_back();
token_desc::TOKEN_TYPE& outer_type = tokens_.back().type;
if(inner_type == token_desc::MACRO_PARENS) {
// Parenthesized macro arguments are left on the stack.
assert(outer_type == token_desc::MACRO_SPACE);
return;
}
if(inner_type == token_desc::STRING || inner_type == token_desc::VERBATIM) {
// Quoted strings are always inlined.
assert(stack_pos == strings_.size());
return;
}
if(outer_type == token_desc::MACRO_SPACE) {
/* A macro expansion does not have any associated storage.
* Instead, storage of the inner token is not discarded
* but kept as a new macro argument. But if the inner token
* was a macro expansion, it is about to be appended, so
* prepare for it.
*/
if(inner_type == token_desc::MACRO_SPACE || inner_type == token_desc::MACRO_CHUNK) {
strings_.erase(strings_.begin() + stack_pos, strings_.end());
strings_.emplace_back();
}
assert(stack_pos + 1 == strings_.size());
outer_type = token_desc::MACRO_CHUNK;
return;
}
strings_.erase(strings_.begin() + stack_pos, strings_.end());
}
void preprocessor_data::skip_spaces()
{
for(;;) {
int c = in_.peek();
if(in_.eof() || (c != ' ' && c != '\t')) {
return;
}
in_.get();
}
}
void preprocessor_data::skip_eol()
{
for(;;) {
int c = in_.get();
if(c == '\n') {
++linenum_;
return;
}
if(in_.eof()) {
return;
}
}
}
std::string preprocessor_data::read_word()
{
std::string res;
for(;;) {
int c = in_.peek();
if(c == preprocessor_streambuf::traits_type::eof() || utils::portable_isspace(c)) {
// DBG_PREPROC << "(" << res << ")\n";
return res;
}
in_.get();
res += static_cast<char>(c);
}
}
std::string preprocessor_data::read_line()
{
std::string res;
for(;;) {
int c = in_.get();
if(c == '\n') {
++linenum_;
return res;
}
if(in_.eof()) {
return res;
}
if(c != '\r') {
res += static_cast<char>(c);
}
}
}
std::string preprocessor_data::read_rest_of_line()
{
std::string res;
while(in_.peek() != '\n' && !in_.eof()) {
int c = in_.get();
if(c != '\r') {
res += static_cast<char>(c);
}
}
return res;
}
void preprocessor_data::put(char c)
{
if(skipping_) {
return;