forked from include-what-you-use/include-what-you-use
-
Notifications
You must be signed in to change notification settings - Fork 6
/
iwyu_output.cc
2242 lines (2028 loc) · 91.5 KB
/
iwyu_output.cc
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
//===--- iwyu_output.cc - output-emitting code for include-what-you-use ---===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "iwyu_output.h"
#include <algorithm> // for sort, find
#include <cstdio> // for snprintf
#include <iterator> // for inserter
#include <map> // for _Rb_tree_const_iterator, etc
#include <utility> // for pair, make_pair, operator>
#include <vector> // for vector, vector<>::iterator, etc
#include "iwyu_ast_util.h"
#include "iwyu_globals.h"
#include "iwyu_include_picker.h"
#include "iwyu_location_util.h"
#include "iwyu_path_util.h"
#include "iwyu_preprocessor.h"
#include "iwyu_stl_util.h"
#include "iwyu_string_util.h"
#include "iwyu_verrs.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/raw_ostream.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclBase.h"
#include "clang/AST/DeclTemplate.h"
#include "clang/AST/Type.h"
#include "clang/Basic/SourceLocation.h"
namespace include_what_you_use {
using clang::ClassTemplateDecl;
using clang::ClassTemplateSpecializationDecl;
using clang::CXXMethodDecl;
using clang::CXXRecordDecl;
using clang::Decl;
using clang::DeclContext;
using clang::EnumDecl;
using clang::FileEntry;
using clang::FunctionDecl;
using clang::NamedDecl;
using clang::NamespaceDecl;
using clang::RecordDecl;
using clang::SourceLocation;
using clang::SourceRange;
using clang::TagDecl;
using clang::TemplateDecl;
using clang::UsingDecl;
using llvm::cast;
using llvm::dyn_cast;
using llvm::errs;
using llvm::isa;
using llvm::raw_string_ostream;
using std::map;
using std::multimap;
using std::pair;
using std::sort;
using std::to_string;
using std::vector;
namespace internal {
namespace {
class OutputLine {
public:
OutputLine() = default;
explicit OutputLine(const string& line)
: line_(line) {}
OutputLine(const string& line, const vector<string>& symbols)
: line_(line),
symbols_(symbols) {
symbols_.erase(std::remove_if(symbols_.begin(), symbols_.end(),
[](const string& v) { return v.empty(); }),
symbols_.end());
}
size_t line_length() const {
return line_.size();
}
bool needs_alignment() const {
return !symbols_.empty();
}
void add_prefix(const string& prefix) { line_ = prefix + line_; }
string printable_line(size_t min_length, size_t max_length) const;
private:
string line_; // '#include XXX' or 'class YYY;'
vector<string> symbols_; // symbols used from included header
};
// Append a helpful 'why' comment to the include line, containing the symbols
// used from the header. Align nicely at lower verbosity levels.
string OutputLine::printable_line(size_t min_length, size_t max_length) const {
// If there are no symbols to mention, return the line as-is.
if (symbols_.empty())
return line_;
CHECK_(max_length > 0);
--max_length; // Spare a char for newline character.
// Before first symbol, print ' // for ' and pad it so 'why' comments are
// nicely aligned.
string symbol_prefix = " // for ";
if (line_.length() < min_length)
symbol_prefix.insert(0, min_length - line_.length(), ' ');
string result = line_;
for (string symbol : symbols_) {
// At verbose levels 0-2, truncate output to max_length columns.
if (!ShouldPrint(3)) {
// Calculate number of chars remaining.
size_t remaining = 0;
size_t result_length = result.length() + symbol_prefix.length();
if (result_length < max_length)
remaining = max_length - result_length;
// Ellipsize, and if we can't fit any fragment of the symbol, give up.
symbol = Ellipsize(symbol, remaining);
if (symbol.empty())
break;
}
result += symbol_prefix;
result += symbol;
symbol_prefix = ", ";
}
return result;
}
// A map that effectively allows us to dynamic cast from a NamedDecl
// to a FakeNamedDecl. When a FakeNamedDecl is created, it will be
// inserted into the map with itself as the key (implicitly casted to
// a NamedDecl).
std::map<const clang::NamedDecl*, const FakeNamedDecl*>
g_fake_named_decl_map;
// Since dynamic casting is not an option, this method is provided to
// determine if a decl is actually a FakeNamedDecl.
const FakeNamedDecl* FakeNamedDeclIfItIsOne(const clang::NamedDecl* decl) {
return GetOrDefault(g_fake_named_decl_map, decl, nullptr);
}
std::string PrintableUnderlyingType(const EnumDecl* enum_decl) {
if (const clang::TypeSourceInfo* type_source_info =
enum_decl->getIntegerTypeSourceInfo()) {
return " : " + type_source_info->getType().getAsString(
enum_decl->getASTContext().getPrintingPolicy());
}
return std::string();
}
} // anonymous namespace
FakeNamedDecl::FakeNamedDecl(const string& kind_name, const string& qual_name,
const string& decl_filepath, int decl_linenum)
: clang::NamedDecl(clang::Decl::Record, nullptr, clang::SourceLocation(),
clang::DeclarationName()),
kind_name_(kind_name),
qual_name_(qual_name),
decl_filepath_(decl_filepath), decl_linenum_(decl_linenum) {
g_fake_named_decl_map[this] = this;
}
// When testing IWYU, we provide a fake object (FakeNamedDecl) that
// needs to provide its own version of NamedDecl::getKindName() and
// NamedDecl::getQualifiedNameAsString(). Unfortunately they aren't
// virtual. Hence we define the following helpers to dispatch the
// call ourselves.
string GetKindName(const TagDecl* tag_decl) {
const clang::NamedDecl* const named_decl = tag_decl;
if (const FakeNamedDecl* fake = FakeNamedDeclIfItIsOne(named_decl)) {
return fake->kind_name();
}
if (const auto* enum_decl = dyn_cast<EnumDecl>(tag_decl)) {
if (enum_decl->isScoped())
return enum_decl->isScopedUsingClassTag() ? "enum class" : "enum struct";
}
return tag_decl->getKindName().str();
}
string GetQualifiedNameAsString(const clang::NamedDecl* named_decl) {
if (const FakeNamedDecl* fake = FakeNamedDeclIfItIsOne(named_decl)) {
return fake->qual_name();
}
return GetWrittenQualifiedNameAsString(named_decl);
}
// Name we put in the comments next to an #include.
string GetShortNameAsString(const clang::NamedDecl* named_decl) {
if (const FakeNamedDecl* fake = FakeNamedDeclIfItIsOne(named_decl)) {
return fake->qual_name();
}
// This is modified from NamedDecl::getQualifiedNameAsString:
// http://clang.llvm.org/doxygen/Decl_8cpp_source.html#l00742
const DeclContext *decl_context = named_decl->getDeclContext();
if (decl_context->isFunctionOrMethod())
return named_decl->getNameAsString();
vector<const DeclContext*> contexts;
while (decl_context && isa<NamedDecl>(decl_context)) {
contexts.push_back(decl_context);
decl_context = decl_context->getParent();
};
std::string retval;
raw_string_ostream ostream(retval);
for (vector<const DeclContext*>::reverse_iterator it = contexts.rbegin();
it != contexts.rend(); ++it) {
if (const ClassTemplateSpecializationDecl* tpl_decl = DynCastFrom(*it)) {
ostream << tpl_decl->getName() << "<>::";
} else if (isa<NamespaceDecl>(*it)) {
// We don't want to include namespaces in our shortname.
} else if (const RecordDecl *record_decl = DynCastFrom(*it)) {
if (!record_decl->getIdentifier())
ostream << "(anonymous " << record_decl->getKindName() << ")::";
else
ostream << *record_decl << "::";
} else if (const FunctionDecl *function_decl = DynCastFrom(*it)) {
ostream << *function_decl << "::"; // could also add in '<< "()"'
} else if (const EnumDecl* enum_decl = DynCastFrom(*it)) {
if (enum_decl->isScoped()) {
ostream << *(cast<NamedDecl>(*it)) << "::";
} else {
// Don't add a scope prefix for old-style unscoped enums.
}
} else {
ostream << *(cast<NamedDecl>(*it)) << "::";
}
}
// Due to the way DeclarationNameInfo::printName() is written, this
// will show template arguments for templated constructors and
// destructors. Since iwyu only shows these when they're defined in
// a -inl.h file, I'm not going to worry about it.
if (named_decl->getDeclName())
ostream << *named_decl;
else
ostream << "(anonymous)";
return ostream.str();
}
} // namespace internal
// Holds information about a single full or fwd-decl use of a symbol.
OneUse::OneUse(const NamedDecl* decl, SourceLocation use_loc,
SourceLocation decl_loc, OneUse::UseKind use_kind,
UseFlags flags, const char* comment)
: symbol_name_(internal::GetQualifiedNameAsString(decl)),
short_symbol_name_(internal::GetShortNameAsString(decl)),
decl_(decl),
decl_loc_(GetInstantiationLoc(decl_loc)),
decl_file_(GetFileEntry(decl_loc_)),
decl_filepath_(GetFilePath(decl_file_)),
use_loc_(use_loc),
use_kind_(use_kind), // full use or fwd-declare use
use_flags_(flags),
comment_(comment ? comment : ""),
ignore_use_(false),
is_iwyu_violation_(false) {
}
// This constructor always creates a full use.
OneUse::OneUse(const string& symbol_name, const FileEntry* dfn_file,
const string& dfn_filepath, SourceLocation use_loc)
: symbol_name_(symbol_name),
short_symbol_name_(symbol_name),
decl_(nullptr),
decl_file_(dfn_file),
decl_filepath_(dfn_filepath),
use_loc_(use_loc),
use_kind_(kFullUse),
use_flags_(UF_None),
ignore_use_(false),
is_iwyu_violation_(false) {
// Sometimes dfn_filepath is actually a fully quoted include. In
// that case, we take that as an unchangable mapping that we
// should never remove, so we make it the suggested header.
CHECK_(!decl_filepath_.empty() && "Must pass a real filepath to OneUse");
if (decl_filepath_[0] == '"' || decl_filepath_[0] == '<')
suggested_header_ = decl_filepath_;
}
void OneUse::reset_decl(const clang::NamedDecl* decl) {
CHECK_(decl_ && "Need existing decl to reset it");
CHECK_(decl && "Need to reset decl with existing decl");
decl_ = decl;
decl_file_ = GetFileEntry(decl);
decl_filepath_ = GetFilePath(decl);
}
int OneUse::UseLinenum() const {
return GetLineNumber(use_loc_);
}
string OneUse::PrintableUseLoc() const {
return PrintableLoc(use_loc());
}
void OneUse::SetPublicHeaders() {
// We should never need to deal with public headers if we already know
// who we map to.
CHECK_(suggested_header_.empty() && "Should not need a public header here");
const IncludePicker& picker = GlobalIncludePicker(); // short alias
const string use_path = GetFilePath(use_loc_);
// If the symbol has a special mapping, use it, otherwise map its file.
public_headers_ = picker.GetCandidateHeadersForSymbolUsedFrom(
symbol_name_, use_path);
if (public_headers_.empty())
public_headers_ = picker.GetCandidateHeadersForFilepathIncludedFrom(
decl_filepath(), use_path);
if (public_headers_.empty())
public_headers_.push_back(ConvertToQuotedInclude(decl_filepath()));
}
const vector<string>& OneUse::public_headers() {
if (public_headers_.empty()) {
SetPublicHeaders();
CHECK_(!public_headers_.empty() && "Should always have at least one hdr");
}
return public_headers_;
}
bool OneUse::PublicHeadersContain(const string& elt) {
// TODO(csilvers): get rid of this method.
return ContainsValue(public_headers(), elt);
}
bool OneUse::NeedsSuggestedHeader() const {
return (!ignore_use() && is_full_use() && suggested_header_.empty());;
}
namespace internal {
// At verbose level 7 and above, returns a printable version of
// the pointer, suitable for being emitted after AnnotatedName.
// At lower verbose levels, returns the empty string.
string PrintablePtr(const void* ptr) {
if (ShouldPrint(7)) {
char buffer[32];
snprintf(buffer, sizeof(buffer), "%p ", ptr);
return buffer;
}
return "";
}
// Helpers for printing a forward declaration of a tag type or
// record type template that can be put in source code. The hierarchy
// of the Decl classes used in these helpers looks like:
//
// NamedDecl
// |-- NamespaceDecl
// |-- TemplateDecl
// `-- TypeDecl
// `-- TagDecl (class, struct, union, enum)
// `-- RecordDecl (class, struct, union)
// Given a NamedDecl that presents a (possibly template) tag
// (i.e. class, struct, union, or enum) type declaration, and the print-out
// of its (possible) template parameters and kind (e.g. "template
// <typename T> struct"), returns its forward declaration line.
string PrintForwardDeclare(const NamedDecl* decl,
const string& tpl_params_and_kind,
bool cxx17ns) {
// We need to short-circuit the logic for testing.
if (const FakeNamedDecl* fake = FakeNamedDeclIfItIsOne(decl)) {
return tpl_params_and_kind + " " + fake->qual_name() + ";";
}
CHECK_((isa<TagDecl>(decl) || isa<TemplateDecl>(decl)) &&
"IWYU only allows forward declaring (possibly template) tag types");
std::string fwd_decl = std::string(decl->getName());
if (const auto* enum_decl = dyn_cast<EnumDecl>(decl)) {
fwd_decl += PrintableUnderlyingType(enum_decl);
}
fwd_decl += ";";
bool seen_namespace = false;
// Anonymous namespaces are not using the more concise syntax.
bool concat_namespaces = cxx17ns && !decl->isInAnonymousNamespace();
for (const DeclContext* ctx = decl->getDeclContext();
ctx && isa<NamedDecl>(ctx); ctx = ctx->getParent()) {
if (const RecordDecl* rec = DynCastFrom(ctx)) {
fwd_decl = std::string(rec->getName()) + "::" + fwd_decl;
} else if (const NamespaceDecl* ns = DynCastFrom(ctx)) {
bool first = !seen_namespace;
if (!seen_namespace) {
seen_namespace = true;
fwd_decl = tpl_params_and_kind + " " + fwd_decl;
}
if (concat_namespaces) {
std::string ns_name = std::string(ns->getName());
std::string prefix = ns_name;
std::string suffix;
if (first) {
first = false;
prefix = prefix + " { ";
}
if (ctx->getParent() && isa<NamedDecl>(ctx->getParent())) {
prefix = "::" + prefix;
} else {
prefix = "namespace " + prefix;
suffix = " }";
}
fwd_decl = prefix + fwd_decl + suffix;
} else {
std::string ns_name = ns->isAnonymousNamespace() ?
std::string() : (std::string(ns->getName()) + " ");
fwd_decl = "namespace " + ns_name + "{ " + fwd_decl + " }";
}
} else if (const FunctionDecl* fn = DynCastFrom(ctx)) {
// A local class (class defined inside a function).
fwd_decl = std::string(fn->getName()) + "::" + fwd_decl;
} else {
CHECK_UNREACHABLE_("Unexpected decoration for type");
}
}
if (!seen_namespace) {
fwd_decl = tpl_params_and_kind + " " + fwd_decl;
}
return fwd_decl;
}
// Given a TagDecl, return the line that could be put in source
// code to forward-declare the type, e.g. "namespace ns { class Foo; }".
string MungedForwardDeclareLineForNontemplates(const TagDecl* decl) {
return PrintForwardDeclare(decl, GetKindName(decl), GlobalFlags().cxx17ns);
}
// Given a TemplateDecl representing a class|struct|union template
// declaration, return the line that could be put in source code to
// forward-declare the template, e.g.
// "namespace ns { template <typename T> class Foo; }".
string MungedForwardDeclareLineForTemplates(const TemplateDecl* decl) {
// DeclPrinter prints the class name just as we like it (with
// default args and everything) -- with logic that doesn't exist
// elsewhere in clang that I can see. Unfortunately, it also prints
// the full class body. So, as a hack, we use PrintableDecl to get
// the full declaration, and then hack off everything after the
// template name. We also have to replace the name with the fully
// qualified name. TODO(csilvers): prepend namespaces instead.
std::string line; // llvm wants regular string, not our versa-string
raw_string_ostream ostream(line);
decl->print(ostream); // calls DeclPrinter
line = ostream.str();
// Remove "final" specifier which isn't needed for forward
// declarations.
ReplaceAll(&line, " final ", " ");
// Get rid of the superclasses, if any (this will nix the body too).
line = Split(line, " :", 2)[0];
// Get rid of the template body, if any (true if no superclasses).
line = Split(line, " {", 2)[0];
// The template name is now the last word on the line. Replace it
// by its fully-qualified form.
const string::size_type name = line.rfind(' ');
CHECK_(name != string::npos && "Unexpected printable template-type");
line = line.substr(0, name);
return PrintForwardDeclare(decl, line, GlobalFlags().cxx17ns);
}
string MungedForwardDeclareLine(const NamedDecl* decl) {
if (const TagDecl* tag_decl = DynCastFrom(decl))
return MungedForwardDeclareLineForNontemplates(tag_decl);
else if (const TemplateDecl* template_decl = DynCastFrom(decl))
return MungedForwardDeclareLineForTemplates(template_decl);
CHECK_UNREACHABLE_("Unexpected decl type for MungedForwardDeclareLine");
}
} // namespace internal
OneIncludeOrForwardDeclareLine::OneIncludeOrForwardDeclareLine(
const NamedDecl* fwd_decl)
: line_(internal::MungedForwardDeclareLine(fwd_decl)),
start_linenum_(-1), // set 'for real' below
end_linenum_(-1), // set 'for real' below
is_desired_(false),
is_present_(false),
included_file_(nullptr),
fwd_decl_(fwd_decl) {
const SourceRange decl_lines = GetSourceRangeOfClassDecl(fwd_decl);
// We always want to use the instantiation line numbers: for code like
// FORWARD_DECLARE_CLASS(MyClass);
// we care about where this macro is called, not where it's defined.
start_linenum_ = GetLineNumber(GetInstantiationLoc(decl_lines.getBegin()));
end_linenum_ = GetLineNumber(GetInstantiationLoc(decl_lines.getEnd()));
}
OneIncludeOrForwardDeclareLine::OneIncludeOrForwardDeclareLine(
const FileEntry* included_file, const string& quoted_include, int linenum)
: line_("#include " + quoted_include),
start_linenum_(linenum),
end_linenum_(linenum),
is_desired_(false),
is_present_(false),
quoted_include_(quoted_include),
included_file_(included_file),
fwd_decl_(nullptr) {
}
bool OneIncludeOrForwardDeclareLine::HasSymbolUse(const string& symbol_name)
const {
return ContainsKey(symbol_counts_, symbol_name);
}
void OneIncludeOrForwardDeclareLine::AddSymbolUse(const string& symbol_name) {
++symbol_counts_[symbol_name];
}
bool OneIncludeOrForwardDeclareLine::IsIncludeLine() const {
// Since we construct line_, we know it's in canonical form, and
// can't look like ' # include <foo.h>' or some such.
return StartsWith(line_, "#include");
}
string OneIncludeOrForwardDeclareLine::LineNumberString() const {
char buf[64]; // big enough for any two numbers
snprintf(buf, sizeof(buf), "%d-%d", start_linenum_, end_linenum_);
return buf;
}
IwyuFileInfo::IwyuFileInfo(const clang::FileEntry* this_file,
const IwyuPreprocessorInfo* preprocessor_info,
const string& quoted_include_name)
: file_(this_file),
preprocessor_info_(preprocessor_info),
quoted_file_(quoted_include_name),
is_prefix_header_(false),
is_pch_in_code_(false),
desired_includes_have_been_calculated_(false)
{}
void IwyuFileInfo::AddAssociatedHeader(const IwyuFileInfo* other) {
VERRS(6) << "Adding " << GetFilePath(other->file_)
<< " as associated header for " << GetFilePath(file_) << "\n";
associated_headers_.insert(other);
}
void IwyuFileInfo::AddInclude(const clang::FileEntry* includee,
const string& quoted_includee, int linenumber) {
OneIncludeOrForwardDeclareLine new_include(includee, quoted_includee,
linenumber);
new_include.set_present();
// It's possible for the same #include to be seen multiple times
// (for instance, if we include a .h file twice, and that .h file
// does not have a header guard). Ignore all but the first.
// TODO(csilvers): could rewrite this so it's constant-time.
for (const OneIncludeOrForwardDeclareLine& line : lines_) {
if (line.LineNumbersMatch(new_include)) {
VERRS(6) << "Ignoring repeated include: "
<< GetFilePath(file_) << ":" << linenumber
<< " -> " << GetFilePath(includee) << "\n";
return;
}
}
lines_.push_back(new_include);
// Store in a few other ways as well.
direct_includes_as_fileentries_.insert(includee);
direct_includes_.insert(quoted_includee);
VERRS(6) << "Found include: "
<< GetFilePath(file_) << ":" << linenumber
<< " -> " << GetFilePath(includee) << "\n";
}
void IwyuFileInfo::AddForwardDeclare(const clang::NamedDecl* fwd_decl,
bool definitely_keep_fwd_decl) {
CHECK_(fwd_decl && "forward_declare_decl unexpectedly nullptr");
CHECK_((isa<ClassTemplateDecl>(fwd_decl) || isa<TagDecl>(fwd_decl)) &&
"Can only forward declare tag types and class templates");
lines_.push_back(OneIncludeOrForwardDeclareLine(fwd_decl));
lines_.back().set_present();
if (definitely_keep_fwd_decl)
lines_.back().set_desired();
direct_forward_declares_.insert(fwd_decl); // store in another way as well
VERRS(6) << "Found forward-declare: "
<< GetFilePath(file_) << ":" << lines_.back().LineNumberString()
<< ": " << internal::PrintablePtr(fwd_decl)
<< internal::GetQualifiedNameAsString(fwd_decl) << "\n";
}
void IwyuFileInfo::AddUsingDecl(const UsingDecl* using_decl) {
CHECK_(using_decl && "using_decl unexpectedly nullptr");
using_decl_referenced_.insert(std::make_pair(using_decl, false));
const SourceRange decl_lines = using_decl->getSourceRange();
int start_linenum = GetLineNumber(GetInstantiationLoc(decl_lines.getBegin()));
int end_linenum = GetLineNumber(GetInstantiationLoc(decl_lines.getEnd()));
VERRS(6) << "Found using-decl: "
<< GetFilePath(file_) << ":"
<< to_string(start_linenum) << "-" << to_string(end_linenum) << ": "
<< internal::PrintablePtr(using_decl)
<< internal::GetQualifiedNameAsString(using_decl) << "\n";
}
static void LogSymbolUse(const string& prefix, const OneUse& use) {
string decl_loc;
string printable_ptr;
if (use.decl()) {
decl_loc = PrintableLoc(GetLocation(use.decl()));
printable_ptr = internal::PrintablePtr(use.decl());
} else {
decl_loc = use.decl_filepath();
}
VERRS(6) << prefix << " " << printable_ptr << use.symbol_name()
<< " (from " << decl_loc << ")"
<< " at " << use.PrintableUseLoc() << "\n";
}
void IwyuFileInfo::ReportFullSymbolUse(SourceLocation use_loc,
const NamedDecl* decl,
UseFlags flags,
const char* comment) {
if (decl) {
const NamedDecl* report_decl;
SourceLocation report_decl_loc;
if ((flags & (UF_FunctionDfn | UF_ExplicitInstantiation)) == 0) {
// Since we need the full symbol, we need the decl's definition-site too.
// Also, by default we canonicalize the location, using GetLocation.
report_decl = GetDefinitionAsWritten(decl);
report_decl_loc = GetLocation(report_decl);
} else {
// However, if we're defining the function or we are targeting an explicit
// instantiation, we want to use it as-is and not try to canonicalize at all.
report_decl = decl;
report_decl_loc = decl->getLocation();
}
symbol_uses_.push_back(OneUse(report_decl, use_loc, report_decl_loc,
OneUse::kFullUse, flags, comment));
LogSymbolUse("Marked full-info use of decl", symbol_uses_.back());
}
}
void IwyuFileInfo::ReportFullSymbolUse(SourceLocation use_loc,
const FileEntry* dfn_file,
const string& symbol) {
symbol_uses_.push_back(
OneUse(symbol, dfn_file, GetFilePath(dfn_file), use_loc));
LogSymbolUse("Marked full-info use of symbol", symbol_uses_.back());
}
void IwyuFileInfo::ReportMacroUse(clang::SourceLocation use_loc,
clang::SourceLocation dfn_loc,
const string& symbol) {
symbol_uses_.push_back(OneUse(symbol, GetFileEntry(dfn_loc),
GetFilePath(dfn_loc), use_loc));
LogSymbolUse("Marked full-info use of macro", symbol_uses_.back());
}
void IwyuFileInfo::ReportDefinedMacroUse(const clang::FileEntry* used_in) {
macro_users_.insert(used_in);
}
void IwyuFileInfo::ReportIncludeFileUse(const clang::FileEntry* included_file,
const string& quoted_include) {
symbol_uses_.push_back(OneUse("", included_file, quoted_include,
SourceLocation()));
LogSymbolUse("Marked use of include-file", symbol_uses_.back());
}
void IwyuFileInfo::ReportKnownDesiredFile(const FileEntry* included_file) {
kept_includes_.insert(included_file);
}
void IwyuFileInfo::ReportForwardDeclareUse(SourceLocation use_loc,
const NamedDecl* decl,
UseFlags flags,
const char* comment) {
if (!decl)
return;
// Sometimes, a bug in clang (http://llvm.org/bugs/show_bug.cgi?id=8669)
// combines friend decls with true forward-declare decls. If that
// happened here, replace the friend with a real fwd decl.
decl = GetNonfriendClassRedecl(decl);
symbol_uses_.push_back(OneUse(decl, use_loc, GetLocation(decl),
OneUse::kForwardDeclareUse, flags, comment));
LogSymbolUse("Marked fwd-decl use of decl", symbol_uses_.back());
}
void IwyuFileInfo::ReportUsingDeclUse(SourceLocation use_loc,
const UsingDecl* using_decl,
UseFlags flags,
const char* comment) {
// If accessing a symbol through a using decl in the same file that contains
// the using decl, we must mark the using decl as referenced. At the end of
// traversing the AST, we check to see if a using decl is unreferenced and
// add a full use of one of its shadow decls so that the source file
// continues to compile.
auto using_decl_status = using_decl_referenced_.find(using_decl);
if (using_decl_status != using_decl_referenced_.end()) {
using_decl_status->second = true;
}
// When a symbol is accessed through a using decl, we must report
// that as a full use of the using decl because whatever file that
// using decl is in is now required.
ReportFullSymbolUse(use_loc, using_decl, flags, comment);
}
// Given a collection of symbol-uses for symbols defined in various
// files, figures out the minimal set of #includes needed to get those
// definitions. Typically this is a trivial task: if we need the full
// information from a decl, we just have to #include the header file
// with the decl's definition. But if that header file is a private
// decl -- e.g. <bits/stl_vector.h> -- we need to map that to a public
// decl first. And if more than one public decl fits the bill, we
// want to pick the one that minimizes the number of new #includes
// added. Stores its results by updating the input vector of
// OneUse's. For convenience, returns the set of "desired" includes:
// all includes that were added to suggested_header.
static void LogIncludeMapping(const string& reason, const OneUse& use) {
VERRS(6) << "Mapped " << use.decl_filepath() << " to "
<< use.suggested_header() << " for " << use.symbol_name()
<< " (" << reason << ")\n";
}
namespace internal {
bool DeclCanBeForwardDeclared(const Decl* decl, string* reason) {
// Nothing inside an inline namespace can be forward-declared.
if (IsInInlineNamespace(decl)) {
*reason = "in inline namespace";
return false;
}
if (isa<ClassTemplateDecl>(decl)) {
// Class templates can always be forward-declared.
} else if (const auto* tag_decl = dyn_cast<TagDecl>(decl)) {
// Tag decls can be forward-declared unless they don't have
// a type name to forward-declare (that includes lambdas).
if (!tag_decl->getIdentifier()) {
*reason = "declaration has no name";
return false;
}
} else {
// Other decl types are not forward-declarable.
*reason = "not a record, enumeration or class template";
return false;
}
return true;
}
bool DeclCanBeForwardDeclared(const Decl* decl) {
string reason;
return DeclCanBeForwardDeclared(decl, &reason);
}
// Helper to tell whether a forward-declare use is 'preceded' by a
// declaration inside the same file. 'Preceded' is in quotes, because
// it's actually ok if the declaration follows the use, inside a
// class. (You can write a method using a Foo* before defining the
// nested class Foo later in the class.)
bool DeclIsVisibleToUseInSameFile(const Decl* decl, const OneUse& use) {
if (GetFileEntry(decl) != GetFileEntry(use.use_loc()))
return false;
// If the decl comes before the use, it's visible to it. (The
// decl can also be at the same location as the use, e.g. for
// struct Foo { int x, y; } myvar
// ) It can even be visible if the decl comes after, if the decl
// is inside the class definition and the use is in the body of a
// method.
return (IsBeforeInSameFile(decl, use.use_loc()) ||
GetLocation(decl) == use.use_loc() ||
(DeclsAreInSameClass(decl, use.decl()) && !decl->isOutOfLine() &&
(use.flags() & UF_InCxxMethodBody)));
}
// This makes a best-effort attempt to find the smallest set of
// #include files that satisfy all uses. A more accurate name
// might be "calculate minimal-ish includes". :-) It populates
// each OneUse in uses with the best #include for that use.
// direct_includes: this file's direct includes only.
// associated_direct_includes: direct includes for 'associated'
// files. For everything but foo.cc, this is empty; for foo.cc it's
// foo.h's includes and foo-inl.h's includes.
set<string> CalculateMinimalIncludes(
const string& use_quoted_include,
const set<string>& direct_includes,
const set<string>& associated_direct_includes,
vector<OneUse>* uses) {
set<string> desired_headers;
// TODO(csilvers): if a use's decl supports equivalent redecls
// (such as a FunctionDecl or TypedefDecl), pick the redecl
// that yields the "best" #include.
// Step (1) The easy case: decls that map to just one file. This
// captures both decls that aren't in private header files, and
// those in private header files that only map to one public file.
// For every other decl, we store the (decl, public-headers) pair.
for (OneUse& use : *uses) {
// We don't need to add any #includes for non-full-use.
if (use.ignore_use() || !use.is_full_use())
continue;
// Special case #1: Some uses come with a suggested header already picked.
if (use.has_suggested_header()) {
desired_headers.insert(use.suggested_header());
continue;
}
// Special case #2: if the dfn-file maps to the use-file, then
// this is a file that the use-file is re-exporting symbols for,
// and we should keep the #include as-is.
const string use_file = ConvertToQuotedInclude(GetFilePath(use.use_loc()));
const string decl_file = ConvertToQuotedInclude(use.decl_filepath());
if (use.PublicHeadersContain(use_file) &&
ContainsKey(direct_includes, decl_file)) {
use.set_suggested_header(decl_file);
desired_headers.insert(use.suggested_header());
LogIncludeMapping("private header", use);
} else if (use.public_headers().size() == 1) {
use.set_suggested_header(use.public_headers()[0]);
desired_headers.insert(use.suggested_header());
LogIncludeMapping("only candidate", use);
}
}
// Steps (2): Go through the needed private-includes that map to
// more than one public #include. Use the following priority order:
// - Ourselves.
// - An include in associated_direct_includes (those are includes
// that are not going away, since we can't change associated
// files).
// - Includes in direct_includes that are also already in
// desired_headers.
// - Includes in desired_headers.
// - Includes in direct_includes.
// Picking in this order minimizes the number of #includes we add,
// while allowing us to remove #includes if need be.
for (OneUse& use : *uses) {
if (!use.NeedsSuggestedHeader())
continue;
const vector<string>& public_headers = use.public_headers();
for (const string& choice : public_headers) {
if (use.has_suggested_header())
break;
if (choice == use_quoted_include) {
use.set_suggested_header(choice);
LogIncludeMapping("in self", use);
}
}
// TODO(csilvers): write ElementInBoth() in iwyu_stl_util.h
for (const string& choice : public_headers) {
if (use.has_suggested_header())
break;
if (ContainsKey(associated_direct_includes, choice)) {
use.set_suggested_header(choice);
desired_headers.insert(use.suggested_header());
LogIncludeMapping("in associated header", use);
}
}
for (const string& choice : public_headers) {
if (use.has_suggested_header())
break;
if (ContainsKey(direct_includes, choice) &&
ContainsKey(desired_headers, choice)) {
use.set_suggested_header(choice);
desired_headers.insert(use.suggested_header());
LogIncludeMapping("#include already present and needed", use);
}
}
for (const string& choice : public_headers) {
if (use.has_suggested_header())
break;
if (ContainsKey(desired_headers, choice)) {
use.set_suggested_header(choice);
desired_headers.insert(use.suggested_header());
LogIncludeMapping("#include already needed", use);
}
}
for (const string& choice : public_headers) {
if (use.has_suggested_header())
break;
if (ContainsKey(direct_includes, choice)) {
use.set_suggested_header(choice);
desired_headers.insert(use.suggested_header());
LogIncludeMapping("#include already present", use);
}
}
}
// Step (3): Now we have a set-cover problem: we need to end up with
// a set of headers, called cover, so that for every i:
// intersection(cover, public_headers[i]) != empty_set
// We do this greedily: we find the header that's listed the most
// often. Among those, we prefer the one that's listed first in
// public_headers[i] the most often (each list is in approximate
// best-fit order). Among those, we choose arbitrarily. We repeat
// until we cover all sets.
set<OneUse*> unmapped_uses;
for (OneUse& use : *uses) {
if (use.NeedsSuggestedHeader())
unmapped_uses.insert(&use);
}
while (!unmapped_uses.empty()) {
map<string, pair<int,int>> header_counts; // total appearances, 1st's
for (OneUse* use : unmapped_uses) {
CHECK_(!use->has_suggested_header());
const vector<string>& public_headers = use->public_headers();
for (const string& choice : public_headers) {
if (use->has_suggested_header())
break;
++header_counts[choice].first; // increment total count
if (choice == use->public_headers()[0])
++header_counts[choice].second; // increment first-in-list count
}
}
pair<string, pair<int, int>> best = *header_counts.begin();
for (const auto& header_count : header_counts) {
// Use pair<>'s operator> to order for us.
if (header_count.second > best.second)
best = header_count;
}
const string hdr = best.first;
desired_headers.insert(hdr);
// Now go through and assign to symbols satisfied by this header.
for (set<OneUse*>::iterator it = unmapped_uses.begin();
it != unmapped_uses.end(); ) {
if ((*it)->NeedsSuggestedHeader() && (*it)->PublicHeadersContain(hdr)) {
(*it)->set_suggested_header(hdr);
LogIncludeMapping("set cover", *(*it));
// set<> has nice property that erasing doesn't invalidate iterators.
unmapped_uses.erase(it++); // because we just mapped it!
} else {
++it;
}
}
}
return desired_headers;
}
// Calculating iwyu violations is a multi-step process. The basic
// idea is we trim the existing uses to ones that might plausibly be
// iwyu violations, for both forward-declares (A) and full uses (B).
// Then we calculate the desired (end-result) set of #includes (C).
// After that we can do suggested trimming, with knowledge of all
// #includes, to reduce to full-use (D) and forward-declare uses (E)
// that are actually iwyu violations.
//
// Trimming forward-declare uses (1st pass):
// A1) If not a class or a templated class, recategorize as a full use.
// A2) If a templated class with default template params, recategorize
// as a full use (forward-declaring in that case is too error-prone).
// A3) If a symbol in std, __gnu_cxx, or another system namespace,
// recategorize as a full use. This is entirely a policy
// decision: we've decided never to forward-declare anything in
// a system namespace, because it's best not to expose the internals
// of system headers in user code, if possible.
// A4) If the file containing the use has a pragma inhibiting the forward
// declaration of the symbol, change the use to a full info use in order
// to make sure that the compiler can see some declaration of the symbol.
// A5) If declaration is nested inside a class or a function, discard this use.
// The containing class/function is required to use the nested decl, and
// so will force use of the containing header.
// A6) If any of the redeclarations of this declaration is in the same
// file as the use (and before it), and is actually a definition,
// discard the forward-declare use.
// A7) If any redeclaration is marked with IWYU pragma: export, mark as a
// full use of this decl to keep its containing file included.
// A8) If --no_fwd_decls has been passed, recategorize as a full use.
// Trimming symbol uses (1st pass):
// B1) If declaration is nested inside a function, discard this use.
// The function is required to use the nested decl, and so will force use of
// the containing header.
// B2) If the definition of a full use comes after the use, change the
// full use to a forward-declare use that points to a fwd-decl
// that comes before the use. (This is for cases like typedefs
// where iwyu demands a full use but the language allows a
// forward-declare.)
// B3) Discard symbol uses of a symbol defined in the same file it's used.
// If the symbol is a typedef, function, or var -- every decl
// that is re-declarable except for TagDecl -- discard if *any*