forked from standardese/cppast
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpreprocessor.cpp
More file actions
1275 lines (1103 loc) · 37.7 KB
/
preprocessor.cpp
File metadata and controls
1275 lines (1103 loc) · 37.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (C) 2017-2022 Jonathan Müller and cppast contributors
// SPDX-License-Identifier: MIT
#include "preprocessor.hpp"
#include <algorithm>
#include <atomic>
#include <cctype>
#include <cstdio>
#include <cstring>
#include <fstream>
#include <unordered_map>
#include <process.hpp>
#include <cppast/diagnostic.hpp>
#include "parse_error.hpp"
using namespace cppast;
namespace tpl = TinyProcessLib;
namespace ts = type_safe;
bool detail::pp_doc_comment::matches(const cpp_entity&, unsigned e_line)
{
if (kind == detail::pp_doc_comment::end_of_line)
return line == e_line;
else
return line + 1u == e_line;
}
namespace
{
//=== diagnostic parsing ===//
source_location parse_source_location(const char*& ptr)
{
// format: <filename>(<line>):
// or: <filename>:
auto fallback = ptr;
std::string filename;
while (*ptr && *ptr != ':' && *ptr != '(')
filename.push_back(*ptr++);
if (filename == "error" || filename == "warning" || filename == "fatal error")
{
ptr = fallback;
return {};
}
type_safe::optional<unsigned> line;
if (*ptr == '(')
{
++ptr;
std::string str;
while (*ptr != ')')
str.push_back(*ptr++);
++ptr;
line = unsigned(std::stoi(str));
}
DEBUG_ASSERT(*ptr == ':', detail::assert_handler{});
++ptr;
return {type_safe::nullopt,
filename == "<scratch space>" ? type_safe::optional<std::string>()
: std::move(filename),
std::move(line), type_safe::nullopt};
}
severity parse_severity(const char*& ptr)
{
// format: <severity>:
auto fallback = ptr;
std::string sev;
while (*ptr && *ptr != ':')
sev.push_back(*ptr++);
++ptr;
if (sev == "warning")
return severity::warning;
else if (sev == "error")
return severity::error;
else if (sev == "fatal error")
return severity::critical;
else if (sev == "note")
return severity::info;
else
ptr = fallback;
return severity::error;
}
// parse and log diagnostic
void log_diagnostic(const diagnostic_logger& logger, const std::string& msg)
{
auto ptr = msg.c_str();
auto loc = parse_source_location(ptr);
while (*ptr == ' ')
++ptr;
auto sev = parse_severity(ptr);
while (*ptr == ' ')
++ptr;
std::string message;
while (*ptr && *ptr != '\n')
message.push_back(*ptr++);
if (!loc.file && message == "expanded from here")
// Useless info.
return;
logger.log("preprocessor", diagnostic{std::move(message), std::move(loc), sev});
}
// parses missing header file diagnostic and returns the file name,
// if it is a missing header file diagnostic
ts::optional<std::string> parse_missing_file(const std::string& cur_file, const std::string& msg)
{
auto ptr = msg.c_str();
auto loc = parse_source_location(ptr);
if (loc.file != cur_file)
return type_safe::nullopt;
while (*ptr == ' ')
++ptr;
parse_severity(ptr);
while (*ptr == ' ')
++ptr;
// format 'file-name' file not found
if (*ptr != '\'')
return ts::nullopt;
++ptr;
std::string filename;
while (*ptr != '\'')
filename += *ptr++;
++ptr;
if (std::strcmp(ptr, " file not found") == 0)
return filename;
else
throw libclang_error("preprocessor: unexpected diagnostic '" + msg + "'");
}
//=== external preprocessor invocation ==//
// quote a string
std::string quote(std::string str)
{
return '"' + std::move(str) + '"';
}
std::string diagnostics_flags()
{
std::string flags;
// -fno-caret-diagnostics: don't show the source extract in diagnostics
// -fno-show-column: don't show the column number
// -fdiagnostics-format msvc: use easier to parse MSVC format
flags += " -fno-caret-diagnostics -fno-show-column -fdiagnostics-format=msvc";
// -Wno-*: hide wrong warnings if header file is directly parsed/duplicate macro handling
flags += " -Wno-macro-redefined -Wno-pragma-once-outside-header "
"-Wno-pragma-system-header-outside-header "
"-Wno-include-next-outside-header";
return flags;
}
// get the command that returns all macros defined in the TU
std::string get_macro_command(const libclang_compile_config& c, const char* full_path)
{
// -xc/-xc++: force C or C++ as input language
// -I.: add current working directory to include search path
// -E: print preprocessor output
// -dM: print macro definitions instead of preprocessed file
std::string language = c.use_c() ? "-xc" : "-xc++";
auto flags = language + " -I. -E -dM";
flags += diagnostics_flags();
std::string cmd(detail::libclang_compile_config_access::clang_binary(c) + " " + std::move(flags)
+ " ");
// other flags
for (auto& flag : detail::libclang_compile_config_access::flags(c))
{
cmd += quote(flag);
cmd += ' ';
}
return cmd + quote(full_path);
}
// get the command that preprocess a translation unit given the macros
// macro_file_path == nullptr <=> don't do fast preprocessing
std::string get_preprocess_command(const libclang_compile_config& c, const char* full_path,
const char* macro_file_path)
{
// -xc/-xc++: force C or C++ as input language
// -E: print preprocessor output
// -dD: keep macros
std::string language = c.use_c() ? "-xc" : "-xc++";
auto flags = language + " -E -dD";
// -CC: keep comments, even in macro
// -C: keep comments, but not in macro
if (!detail::libclang_compile_config_access::remove_comments_in_macro(c))
flags += " -CC";
else
flags += " -C";
if (macro_file_path)
// -no*: disable default include search paths
flags += " -nostdinc -nostdinc++";
// -Xclang -dI: print include directives as well
flags += " -Xclang -dI";
flags += diagnostics_flags();
if (macro_file_path)
{
// include file that defines all macros
flags += " -include ";
flags += macro_file_path;
}
std::string cmd(detail::libclang_compile_config_access::clang_binary(c) + " " + std::move(flags)
+ " ");
// other flags
for (const auto& flag : detail::libclang_compile_config_access::flags(c))
{
DEBUG_ASSERT(flag.size() >= 2u && flag[0] == '-', detail::assert_handler{},
("\"" + flag + "\" that's an odd flag").c_str());
if (!macro_file_path || flag[1] != 'I')
{
// only add this flag if it is not an include or we're not doing fast preprocessing
cmd += quote(flag);
cmd += ' ';
}
}
return cmd + quote(full_path);
}
std::string get_macro_file_name()
{
static std::atomic<unsigned> counter(0u);
return "standardese-macro-file-" + std::to_string(++counter) + ".delete-me";
}
template <std::size_t N>
void bump_until(std::istreambuf_iterator<char>& iter, const char (&str)[N])
{
auto ptr = &str[0];
while (ptr != &str[N - 1])
{
if (iter == std::istreambuf_iterator<char>{})
// end of file
break;
else if (*iter != *ptr)
{
// try again
ptr = &str[0];
if (*iter == *ptr)
++ptr; // it was the first character again
}
else
// okay, move forward
++ptr;
++iter;
}
}
template <typename Iter>
void skip_whitespace(Iter& begin, Iter end)
{
while (begin != end && (*begin == ' ' || *begin == '\t'))
++begin;
}
template <typename Iter>
std::string get_line(Iter& begin, Iter end)
{
std::string line;
while (begin != end && *begin != '\n')
line += *begin++;
++begin; // newline
return line;
}
type_safe::optional<std::string> get_include_guard_macro(const std::string& full_path)
{
std::ifstream file(full_path);
auto iter = std::istreambuf_iterator<char>(file);
while (iter != std::istreambuf_iterator<char>{})
{
if (*iter == '/')
{
++iter;
if (*iter == '/')
// C++ style comment, bump until \n
bump_until(iter, "\n");
else if (*iter == '*')
// C style comment
bump_until(iter, "*/");
}
else if (*iter == ' ' || *iter == '\t' || *iter == '\n')
++iter; // empty
else if (*iter == '#')
{
// preprocessor line
auto if_line = get_line(iter, {});
if (if_line.compare(0, 3, "#if") != 0)
// not something starting with #if
break;
skip_whitespace(iter, {});
auto macro_line = get_line(iter, {});
if (macro_line.compare(0, 7, "#define") != 0)
// not a corresponding define
break;
auto macro_name_begin = std::next(macro_line.begin(), 7);
// skip whitespace after define
skip_whitespace(macro_name_begin, macro_line.end());
auto macro_name_end = macro_name_begin;
// skip over identifier
while (macro_name_end != macro_line.end()
&& (*macro_name_end == '_' || std::isalnum(*macro_name_end)))
++macro_name_end;
auto trailing_ws = macro_line.rbegin();
skip_whitespace(trailing_ws, macro_line.rend());
if (macro_name_end != trailing_ws.base())
// anything else after macro
break;
std::string macro_name(macro_name_begin, macro_name_end);
if (if_line.find(macro_name) == std::string::npos)
// macro name doesn't occur in if line
break;
else
return macro_name;
}
else
// line is neither empty, comment, nor preprocessor
break;
}
// assume no include guard followed a bad line
return type_safe::nullopt;
}
std::string write_macro_file(const libclang_compile_config& c, const std::string& full_path,
const diagnostic_logger& logger)
{
std::string diagnostic;
auto diagnostic_logger = [&](const char* str, std::size_t n) {
diagnostic.reserve(diagnostic.size() + n);
for (auto end = str + n; str != end; ++str)
if (*str == '\r')
continue;
else if (*str == '\n')
{
// consume current diagnostic
log_diagnostic(logger, diagnostic);
diagnostic.clear();
}
else
diagnostic.push_back(*str);
};
auto file = get_macro_file_name();
std::ofstream stream(file);
auto cmd = get_macro_command(c, full_path.c_str());
tpl::Process process(
cmd, "", [&](const char* str, std::size_t n) { stream.write(str, std::streamsize(n)); },
diagnostic_logger);
if (auto include_guard = get_include_guard_macro(full_path))
// undefine include guard
stream << "#undef " << include_guard.value();
auto exit_code = process.get_exit_status();
DEBUG_ASSERT(diagnostic.empty(), detail::assert_handler{});
if (exit_code != 0)
throw libclang_error("preprocessor (macro): command '" + cmd
+ "' exited with non-zero exit code (" + std::to_string(exit_code)
+ ")");
return file;
}
struct clang_preprocess_result
{
std::string file;
std::vector<std::string> included_files; // needed for pre-clang 4.0.0
};
clang_preprocess_result clang_preprocess_impl(const libclang_compile_config& c,
const diagnostic_logger& logger,
const std::string& full_path, const char* macro_path)
{
clang_preprocess_result result;
std::string diagnostic;
auto expect_bad_exit_code = false;
auto diagnostic_handler = [&](const char* str, std::size_t n) {
diagnostic.reserve(diagnostic.size() + n);
for (auto end = str + n; str != end; ++str)
if (*str == '\r')
continue;
else if (*str == '\n')
{
// handle current diagnostic
if (macro_path)
{
// hide diagnostics
auto file = parse_missing_file(full_path, diagnostic);
if (file)
// save for clang without -dI flag
result.included_files.push_back(file.value());
expect_bad_exit_code = true;
}
else
log_diagnostic(logger, diagnostic);
diagnostic.clear();
}
else
diagnostic.push_back(*str);
};
auto cmd = get_preprocess_command(c, full_path.c_str(), macro_path);
tpl::Process process(
cmd, "",
[&](const char* str, std::size_t n) {
for (auto ptr = str; ptr != str + n; ++ptr)
if (*ptr == '\t')
result.file += ' '; // convert to single spaces
else if (*ptr != '\r')
result.file += *ptr;
},
diagnostic_handler);
// wait for process end
auto exit_code = process.get_exit_status();
DEBUG_ASSERT(diagnostic.empty(), detail::assert_handler{});
if (exit_code != 0 && !expect_bad_exit_code)
throw libclang_error("preprocessor: command '" + cmd + "' exited with non-zero exit code ("
+ std::to_string(exit_code) + ")");
return result;
}
clang_preprocess_result clang_preprocess(const libclang_compile_config& c, const char* full_path,
const diagnostic_logger& logger)
{
if (!std::ifstream(full_path))
throw libclang_error("preprocessor: file '" + std::string(full_path) + "' doesn't exist");
// if we're fast preprocessing we only preprocess the main file, not includes
// this is done by disabling all include search paths when doing the preprocessing
// to allow macros a separate preprocessing with the -dM flag is done that extracts all macros
// they are then manually defined before
auto fast_preprocessing = detail::libclang_compile_config_access::fast_preprocessing(c);
auto macro_file = fast_preprocessing ? write_macro_file(c, full_path, logger) : "";
clang_preprocess_result result;
try
{
result = clang_preprocess_impl(c, logger, full_path,
fast_preprocessing ? macro_file.c_str() : nullptr);
}
catch (...)
{
if (fast_preprocessing)
{
auto err = std::remove(macro_file.c_str());
DEBUG_ASSERT(err == 0, detail::assert_handler{});
}
throw;
}
if (fast_preprocessing)
{
auto err = std::remove(macro_file.c_str());
DEBUG_ASSERT(err == 0, detail::assert_handler{});
}
return result;
}
//==== parsing ===//
class position
{
public:
position(ts::object_ref<std::string> result, const char* ptr) noexcept
: result_(result), cur_line_(1u), cur_column_(0u), ptr_(ptr), write_disabled_count_(0)
{
// We strip all conditional defines and pragmas from the input, which includes the include
// guard. If the source includes a file, which includes itself again (for some reason), this
// leads to a duplicate include, as we no longer have an include guard. So we manually add
// one.
*result += "#pragma once\n";
// We also need to reset the line afterwards to ensure comments still match.
*result += "#line 1\n";
}
void set_line(unsigned line)
{
if (write_enabled() && cur_line_ != line)
{
*result_ += "#line " + std::to_string(line) + "\n";
cur_line_ = line;
cur_column_ = 0;
}
}
void write_str(std::string str)
{
if (!write_enabled())
return;
for (auto c : str)
{
*result_ += c;
++cur_column_;
if (c == '\n')
{
++cur_line_;
cur_column_ = 0;
}
}
}
void bump() noexcept
{
if (write_enabled())
{
result_->push_back(*ptr_);
++cur_column_;
if (*ptr_ == '\n')
{
++cur_line_;
cur_column_ = 0;
}
}
++ptr_;
}
void bump(std::size_t offset) noexcept
{
if (write_enabled())
{
for (std::size_t i = 0u; i != offset; ++i)
bump();
}
else
{
skip(offset);
}
}
// no write, no newline detection
void skip(std::size_t offset = 1u) noexcept
{
ptr_ += offset;
}
void skip_with_linecount() noexcept
{
if (write_enabled())
{
++cur_column_;
if (*ptr_ == '\n')
{
result_->push_back('\n');
++cur_line_;
cur_column_ = 0;
}
}
++ptr_;
}
void enable_write() noexcept
{
DEBUG_ASSERT(write_disabled_count_ > 0, detail::assert_handler{});
--write_disabled_count_;
}
void disable_write() noexcept
{
++write_disabled_count_;
}
bool write_enabled() const noexcept
{
return write_disabled_count_ == 0;
}
explicit operator bool() const noexcept
{
return *ptr_ != '\0';
}
const char* ptr() const noexcept
{
return ptr_;
}
unsigned cur_line() const noexcept
{
return cur_line_;
}
unsigned cur_column() const noexcept
{
return cur_column_;
}
bool was_newl() const noexcept
{
return result_->empty() || result_->back() == '\n';
}
private:
ts::object_ref<std::string> result_;
unsigned cur_line_, cur_column_;
const char* ptr_;
unsigned write_disabled_count_;
};
bool starts_with(const position& p, const char* str, std::size_t len)
{
return std::strncmp(p.ptr(), str, len) == 0;
}
template <std::size_t N>
bool starts_with(const position& p, const char (&str)[N])
{
return std::strncmp(p.ptr(), str, N - 1) == 0;
}
void skip(position& p, const char* str)
{
DEBUG_ASSERT(starts_with(p, str, std::strlen(str)), detail::assert_handler{});
p.skip(std::strlen(str));
}
void bump_spaces(position& p, bool bump = false)
{
while (starts_with(p, " "))
if (bump)
p.bump();
else
p.skip();
}
detail::pp_doc_comment parse_c_doc_comment(position& p)
{
detail::pp_doc_comment result;
result.kind = detail::pp_doc_comment::c;
auto indent = p.cur_column() + 3;
if (starts_with(p, " "))
{
// skip one whitespace at most
p.skip();
++indent;
}
while (!starts_with(p, "*/"))
{
if (starts_with(p, "\n"))
{
// remove trailing spaces
while (!result.comment.empty() && result.comment.back() == ' ')
result.comment.pop_back();
// skip newline(s)
while (starts_with(p, "\n"))
{
p.skip_with_linecount();
result.comment += '\n';
}
// skip indentation
auto actual_indent = 0u;
for (auto i = 0u; i < indent && starts_with(p, " "); ++i)
{
++actual_indent;
p.skip();
}
auto extra_indent = 0u;
while (starts_with(p, " "))
{
++extra_indent;
p.skip();
}
// skip continuation star, if any
if (starts_with(p, "*") && !starts_with(p, "*/"))
{
p.skip();
if (starts_with(p, " "))
// skip one whitespace at most
p.skip();
}
else
{
// insert extra indent again
result.comment += std::string(extra_indent, ' ');
// use minimum indent in the future
indent = std::min(actual_indent, indent);
}
}
else
{
result.comment += *p.ptr();
p.skip();
}
}
p.skip(2u);
// remove trailing star
if (!result.comment.empty() && result.comment.back() == '*')
result.comment.pop_back();
// remove trailing spaces
while (!result.comment.empty() && result.comment.back() == ' ')
result.comment.pop_back();
result.line = p.cur_line();
return result;
}
bool skip_c_comment(position& p, detail::preprocessor_output& output)
{
if (!starts_with(p, "/*"))
return false;
p.skip(2u);
if (starts_with(p, "*/"))
// empty comment
p.skip(2u);
else if (p.write_enabled() && (starts_with(p, "*") || starts_with(p, "!")))
{
// doc comment
p.skip();
output.comments.push_back(parse_c_doc_comment(p));
}
else
{
while (!starts_with(p, "*/"))
p.skip_with_linecount();
p.skip(2u);
}
return true;
}
detail::pp_doc_comment parse_cpp_doc_comment(position& p, bool end_of_line)
{
detail::pp_doc_comment result;
result.kind = end_of_line ? detail::pp_doc_comment::end_of_line : detail::pp_doc_comment::cpp;
if (starts_with(p, " "))
// skip one whitespace at most
p.skip();
while (!starts_with(p, "\n"))
{
result.comment += *p.ptr();
p.skip();
}
// don't skip newline
// remove trailing spaces
while (!result.comment.empty() && result.comment.back() == ' ')
result.comment.pop_back();
result.line = p.cur_line();
return result;
}
bool can_merge_comment(const detail::pp_doc_comment& comment, unsigned cur_line)
{
return comment.line + 1 == cur_line
&& (comment.kind == detail::pp_doc_comment::cpp
|| comment.kind == detail::pp_doc_comment::end_of_line);
}
void merge_or_add(detail::preprocessor_output& output, detail::pp_doc_comment comment)
{
if (output.comments.empty() || !can_merge_comment(output.comments.back(), comment.line))
output.comments.push_back(std::move(comment));
else
{
auto& result = output.comments.back();
result.comment += "\n" + std::move(comment.comment);
if (result.kind != detail::pp_doc_comment::end_of_line)
result.line = comment.line;
}
}
bool skip_cpp_comment(position& p, detail::preprocessor_output& output)
{
if (!starts_with(p, "//"))
return false;
p.skip(2u);
if (p.write_enabled() && (starts_with(p, "/") || starts_with(p, "!")))
{
// C++ style doc comment
p.skip();
auto comment = parse_cpp_doc_comment(p, false);
merge_or_add(output, std::move(comment));
}
else if (p.write_enabled() && starts_with(p, "<"))
{
// end of line doc comment
p.skip();
auto comment = parse_cpp_doc_comment(p, true);
output.comments.push_back(std::move(comment));
}
else
{
auto newline = std::strchr(p.ptr(), '\n');
p.skip(std::size_t(newline - p.ptr())); // don't skip newline
}
return true;
}
std::unique_ptr<cpp_macro_definition> build(std::string name, ts::optional<std::string> args,
std::string rep)
{
if (!args)
return cpp_macro_definition::build_object_like(std::move(name), std::move(rep));
cpp_macro_definition::function_like_builder builder{std::move(name)};
builder.replacement(std::move(rep));
auto cur_ptr = args.value().c_str();
auto cur_param = cur_ptr;
while (*cur_ptr)
{
while (*cur_ptr && *cur_ptr != ',')
++cur_ptr;
if (*cur_param == '.')
builder.is_variadic();
else
builder.parameter(std::string(cur_param, cur_ptr));
if (*cur_ptr)
cur_param = ++cur_ptr;
}
return builder.finish();
}
std::unique_ptr<cpp_macro_definition> parse_macro(position& p, detail::preprocessor_output& output)
{
// format (at new line): #define <name> [replacement]
// or: #define <name>(<args>) [replacement]
// note: keep macro definition in file
if (!p.was_newl() || !starts_with(p, "#define"))
return nullptr;
// read line here for comment matching
auto cur_line = p.cur_line();
p.bump(std::strlen("#define"));
bump_spaces(p, true);
std::string name;
while (!starts_with(p, "(") && !starts_with(p, " ") && !starts_with(p, "\n"))
{
name += *p.ptr();
p.bump();
}
ts::optional<std::string> args;
if (starts_with(p, "("))
{
std::string str;
for (p.bump(); !starts_with(p, ")"); p.bump())
str += *p.ptr();
p.bump();
args = std::move(str);
}
std::string rep;
auto in_c_comment = false;
for (bump_spaces(p, true); in_c_comment || !starts_with(p, "\n"); p.bump())
{
if (starts_with(p, "/*"))
in_c_comment = true;
else if (in_c_comment && starts_with(p, "*/"))
in_c_comment = false;
rep += *p.ptr();
}
// don't skip newline
if (!p.write_enabled())
return nullptr;
auto result = build(std::move(name), std::move(args), std::move(rep));
// match comment directly
if (!output.comments.empty() && output.comments.back().matches(*result, cur_line))
{
result->set_comment(std::move(output.comments.back().comment));
output.comments.pop_back();
}
return result;
}
ts::optional<std::string> parse_undef(position& p)
{
// format (at new line): #undef <name>
// due to a clang bug (http://bugs.llvm.org/show_bug.cgi?id=32631) I'll also an undef in the
// middle of the line
if (/*!p.was_newl() ||*/ !starts_with(p, "#undef"))
return ts::nullopt;
p.bump(std::strlen("#undef"));
std::string result;
for (bump_spaces(p, true); !starts_with(p, "\n"); p.bump())
result += *p.ptr();
// don't skip newline
return result;
}
type_safe::optional<detail::pp_include> parse_include(position& p)
{
// format (at new line, literal <>): #include <filename>
// or: #include "filename"
// note: write include back
if (!p.was_newl() || !starts_with(p, "#include"))
return type_safe::nullopt;
p.bump(std::strlen("#include"));
if (starts_with(p, "_next"))
p.bump(std::strlen("_next"));
bump_spaces(p);
auto include_kind = cpp_include_kind::system;
auto end_str = "";
if (starts_with(p, "\""))
{
include_kind = cpp_include_kind::local;
end_str = "\"";
}
else if (starts_with(p, "<"))
{
include_kind = cpp_include_kind::system;
end_str = ">";
}
else
DEBUG_UNREACHABLE(detail::assert_handler{});
p.bump();
std::string filename;
for (; !starts_with(p, "\"") && !starts_with(p, ">"); p.bump())
filename += *p.ptr();
DEBUG_ASSERT(starts_with(p, end_str, std::strlen(end_str)), detail::assert_handler{},
"bad termination");
p.bump();
skip(p, " /* clang -E -dI */");
DEBUG_ASSERT(starts_with(p, "\n"), detail::assert_handler{});
// don't skip newline
if (!p.write_enabled())
return type_safe::nullopt;
if (filename.size() > 2u && filename[0] == '.' && (filename[1] == '/' || filename[1] == '\\'))
filename = filename.substr(2);
return detail::pp_include{std::move(filename), "", include_kind, p.cur_line()};
}
bool bump_pragma(position& p)
{
// format (at new line): #pragma <stuff..>\n
if (!p.was_newl() || !starts_with(p, "#pragma"))
return false;