-
Notifications
You must be signed in to change notification settings - Fork 124
/
Copy pathmatcher.cc
3046 lines (2868 loc) · 120 KB
/
matcher.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
// ############################################################################
// PLEASE UPDATE
// kMatcherVersionStamp
// IN matcher.h WHEN THERE ARE NEW FEATURES OR BEHAVIOR CHANGES.
// ############################################################################
// Copyright 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Takes clif protos and matches the functions referenced the
// appropriate C++ functions and types.
#include "clif/backend/matcher.h"
#include <algorithm>
#include <deque>
#include <memory>
#include "absl/container/btree_map.h"
#include "absl/log/log.h"
#include "clif/backend/strutil.h"
#include "clang/AST/Expr.h"
#include "clang/AST/Mangle.h"
#include "clang/AST/QualTypeNames.h"
#include "clang/Sema/Initialization.h"
#include "clang/Sema/Sema.h"
#include "clang/Sema/SemaDiagnostic.h"
#include "clang/Sema/Template.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#if PYCLIF_LLVM_VERSION_MAJOR > 16
#include "clang/Sema/EnterExpressionEvaluationContext.h"
#endif
// TODO: Switch to clang diagnostics mechanism for errors.
#define DEBUG_TYPE "clif_matcher"
namespace clif {
// Currently only UNIX-like pathnames are supported.
// For Windows this would be '\\'.
static const char kFilesystemPathSep = '/';
// Support for auxiliary header files with C++ customizations specifically
// for CLIF.
// TODO: Point to new documentation under go/pyclif once it is available.
static const char kClifAux[] = "_clif_aux";
static constexpr std::size_t kClifAuxLen = sizeof(kClifAux) - 1;
using clang::ClassTemplateSpecializationDecl;
using clang::CXXRecordDecl;
using clang::DeclarationName;
using clang::DeclContext;
using clang::EnumConstantDecl;
using clang::FunctionDecl;
using clang::FunctionTemplateDecl;
using clang::InitializedEntity;
using clang::NamedDecl;
using clang::NamespaceDecl;
using clang::QualType;
using clang::Sema;
const std::string GetDeclNativeName(const Decl& decl) {
const char unknown_name[] = "(unknown)";
switch (decl.decltype_()) {
case Decl::CLASS: return decl.class_().name().native();
case Decl::ENUM: return decl.enum_().name().native();
case Decl::VAR: return decl.var().name().native();
case Decl::CONST: return decl.const_().name().native();
case Decl::FUNC: return decl.func().name().native();
case Decl::TYPE: return decl.fdecl().name().cpp_name();
case Decl::UNKNOWN: return unknown_name;
}
LOG(FATAL) << "Unknown decl.decltype_(): " << decl.decltype_();
}
std::string GetGloballyQualifiedName(const NamedDecl* decl) {
std::string name("::");
StrAppend(&name, decl->getQualifiedNameAsString());
return name;
}
static const char kConstToken[] = "const "; // Trailing space is important.
#if PYCLIF_LLVM_VERSION_MAJOR < 14
static const char kCppCharArray[] = "const char [";
#else
static const char kCppCharArray[] = "const char[";
#endif
static const char kClifCharArray[] = "::clif::char_ptr";
static std::string GetErrorCodeString(ClifErrorCode code) {
switch (code) {
case kOK:
return "";
case kNotFound:
return "C++ symbol not found.";
case kMultipleMatches:
return ("Multiple C++ symbols with same name found. "
"Possibilities include:");
case kNotInImportFile:
return "Declaration was found, but not inside the required file.";
case kTypeMismatch:
// TypeCheckLookupResult will fill in dynamic message.
return "";
case kReturnValueMismatch:
return "C++ function return type didn't match.";
case kParameterMismatch:
return "Function parameter types didn't match.";
case kConstVarError:
return ("Symbol declared constant in Clif, but matched"
" with non-constant C++ declaration.");
case kMissingEnumerator:
return "Clif enumerator not present in C++:";
case kNonConstParameterType:
return "A pointer or reference input parameter must be constant.";
case kNonPointerReturnType:
return "An output parameter must be either a pointer or a reference.";
case kNonPointerType:
return "Clif requires this parameter to be a pointer.";
case kConstReturnType:
return "Output parameter is constant.";
case kConstVariable:
return "Clif expects a variable, but C++ declares it constant.";
case kUncopyableUnmovableReturnType:
return ("Clif expects output parameters or return types to be copyable "
"or movable.");
case kIncompatibleTypes:
return "Non-matching types.";
case kParameterCountsDiffer:
return "Parameter counts differ.";
case kUnexpectedDefaultSpecifier:
return "Clif contains unexpected default specifiers.";
case kWrongOrderDefault:
return ("Clif expects all required parameters to be placed before "
"default arguments.");
case kMultipleInheritance:
return "Clif doesn't support classes with multiple inheritance.";
case kNoDefinitionAvailable:
return ("Clif requests matching class-members, but C++ didn't include "
"the class definition.");
case kNotCallable:
return "Clif callables require a std::function.";
case kUnspecializableTemplate:
return "Function template can't be specialized with these arguments.";
case kConstructorNotFound:
return "Class constructor not found.";
case kClassMethod:
return ("Clif function with @classmember decorator matches a "
"non-static C++ class member function.");
case kCppStaticMethod:
return ("Clif function without a @classmethod decorator matches a "
"static C++ class member function.");
case kNonStaticClassGlobalFunctionDecl:
return ("Globally-declared function matches a non-static C++ class "
"member function.");
case kNonVirtualDiamondInheritance:
return ("Non-virtual diamond inheritance.");
case kMustUseResultIgnored:
return ("Clif can not ignore ABSL_MUST_USE_RESULT return values.");
}
LOG(FATAL) << "Unknown ClifErrorCode: " << code;
}
static void ReportMultimatchError(
const ClifMatcher& matcher, const TranslationUnitAST* ast,
const std::vector<std::pair<const FunctionDecl*, FuncDecl>>& matches,
Decl* clif_decl, const std::string& message = "") {
ClifError multimatch_error(matcher, kMultipleMatches);
for (const auto& decl_pair : matches) {
multimatch_error.AddClangDeclAndLocation(ast, decl_pair.first);
}
multimatch_error.AddMessage(message);
multimatch_error.Report(clif_decl);
}
void ClifError::AddMessage(const std::string& message) {
messages_.push_back(message);
}
const char kMessageIndent[] = " ";
void ClifError::AddClangDeclAndLocation(const TranslationUnitAST* ast,
const NamedDecl* decl) {
// Weird spacing to make final message parsable to humans.
std::string message;
StrAppend(&message,
"Rejected Candidate:\n ",
kMessageIndent, ast->GetClangDeclNameForError(*decl),
" at ", ast->GetClangDeclLocForError(*decl));
AddMessage(message);
}
std::string ClifError::Report(Decl* clif_decl) {
std::string name = GetDeclNativeName(*clif_decl);
if (name.empty()) {
name = matcher_.GetDeclCppName(*clif_decl);
}
std::string error;
StrAppend(&error, "No suitable matches found for ", name);
if (name != matcher_.GetDeclCppName(*clif_decl)) {
StrAppend(&error,
" (with C++ name: ",
matcher_.GetDeclCppName(*clif_decl), ")");
}
if (clif_decl->line_number() != 0) {
StrAppend(&error, " on line ", clif_decl->line_number());
}
StrAppend(&error, ".\n");
if (code_ != kOK &&
code_ != kTypeMismatch &&
code_ != kNotFound &&
code_ != kConstructorNotFound) {
StrAppend(&error, kMessageIndent, GetErrorCodeString(code_), "\n");
} else {
if (code_ == kNotFound) {
// First message contains the lookup location.
StrAppend(&error, kMessageIndent, "C++ symbol \"",
matcher_.GetDeclCppName(*clif_decl),
"\" not found in ", messages_.front(), ".\n");
messages_.erase(messages_.begin());
} else if (code_ == kConstructorNotFound) {
// First message contains the lookup location.
StrAppend(&error, kMessageIndent,
"No viable constructor found in",
messages_.front(), ".\n");
messages_.erase(messages_.begin());
}
}
for (const auto& message : messages_) {
StrAppend(&error, kMessageIndent, message, "\n");
}
llvm::errs() << error;
// For a single clif decl, more than one error might be reported. The
// not_found field should record all of the error messages.
std::string error_message;
StrAppend(&error_message, clif_decl->not_found(), error);
clif_decl->set_not_found(error_message);
return error;
}
const std::string ClifMatcher::GetDeclCppName(const Decl& decl) const {
const char unknown_name[] = "(unknown)";
std::string cpp_name;
switch (decl.decltype_()) {
case Decl::CLASS: cpp_name = decl.class_().name().cpp_name(); break;
case Decl::ENUM: cpp_name = decl.enum_().name().cpp_name(); break;
case Decl::VAR: return decl.var().name().cpp_name();
case Decl::CONST: return decl.const_().name().cpp_name();
case Decl::FUNC: return decl.func().name().cpp_name();
case Decl::TYPE: cpp_name = decl.fdecl().name().cpp_name(); break;
case Decl::UNKNOWN: return unknown_name;
}
const CodeBuilder::NameMap& name_map = builder_.OriginalNames();
auto pair = name_map.find(cpp_name);
assert(pair != name_map.end() &&
"Original name of a class/enum/type not present.");
return pair->second;
}
std::string ClifMatcher::GetParallelTypeNames() const {
std::string message;
for (const auto& types : type_mismatch_stack_) {
StrAppend(&message,
"\n Compare:\n",
" Clif Type: \"", types.second, "\" with \n",
" C++ Type: \"", types.first, "\"");
}
return message;
}
std::string ClifMatcher::GetErrorMessageForNonTargetDecl(
const clang::NamedDecl& clang_decl) const {
std::string message;
StrAppend(&message,
"Clif Error: UsingShadowDecl does not have the target decl\n",
"Rejected Candidate:\n ", kMessageIndent,
ast_->GetClangDeclNameForError(clang_decl), " at ",
ast_->GetClangDeclLocForError(clang_decl));
return message;
}
bool ClifTypeDerivedFromClangType(const QualType& clang_type,
const QualType& clif_type) {
CXXRecordDecl* clang_type_decl = clang_type->getAsCXXRecordDecl();
if (clang_type_decl == nullptr) {
return false;
}
CXXRecordDecl* clif_type_decl = clif_type->getAsCXXRecordDecl();
if (clif_type_decl == nullptr) {
return false;
}
if (clif_type_decl->isDerivedFrom(clang_type_decl)) {
return true;
}
return false;
}
ClifErrorCode ClifMatcher::CheckForLookupError(
const ClifLookupResult& decls) const {
ClifError wrong_file(*this, kOK);
ClifLookupResult valid_decls;
for (auto decl : decls.GetResults()) {
if (ImportedFromCorrectFile(*decl, &wrong_file)) {
valid_decls.AddResult(decl);
}
}
if (valid_decls.Size() == 0) {
// Nothing found at all vs things found in wrong file.
if (decls.Size() == 0) {
ClifError error(*this, kNotFound, ast_->GetLookupScopeName());
error.Report(CurrentDecl());
return kNotFound;
}
wrong_file.Report(CurrentDecl());
return kNotInImportFile;
}
if (valid_decls.Size() > 1) {
ClifError error(*this, kMultipleMatches);
for (auto decl : valid_decls.GetResults()) {
error.AddClangDeclAndLocation(ast_.get(), decl);
}
error.Report(CurrentDecl());
return kMultipleMatches;
}
return kOK;
}
bool ClifMatcher::CompileMatchAndSet(
const std::vector<std::string>& compiler_args,
const std::string& input_file_name,
const AST& clif_ast,
AST* modified_clif_ast) {
LLVM_DEBUG(llvm::dbgs() << ProtoDebugString(clif_ast));
*modified_clif_ast = clif_ast;
modified_clif_ast->set_clif_matcher_argv0(clif_matcher_argv0_);
modified_clif_ast->set_clif_matcher_version_stamp(kMatcherVersionStamp);
BuildClifToClangTypeMap(clif_ast);
if (RunCompiler(
builder_.BuildCode(modified_clif_ast, &clif_to_clang_type_map_),
compiler_args, input_file_name) == false) {
return false;
}
BuildTypeTable();
modified_clif_ast->set_catch_exceptions(
ast_->GetASTContext().getLangOpts().Exceptions);
return MatchAndSetAST(modified_clif_ast);
}
bool ClifMatcher::RunCompiler(const std::string& code,
const std::vector<std::string>& args,
const std::string& input_file_name) {
ast_.reset(new TranslationUnitAST);
return ast_->Init(code, args, input_file_name);
}
bool ClifMatcher::CheckConstant(QualType type) const {
if (!type.isConstQualified()) {
ClifError error(*this, kConstVarError);
error.Report(CurrentDecl());
return false;
}
return true;
}
std::string ClifMatcher::GetQualTypeClifName(QualType qual_type) const {
if (qual_type.getTypePtrOrNull() == nullptr) {
return "";
}
std::string name = clang::TypeName::getFullyQualifiedName(
qual_type, ast_->GetASTContext(),
ast_->GetASTContext().getPrintingPolicy(),
true /* Include "::" prefix */);
// Clang desugars template parameters in unpredictable places, and
// often in unpredictable ways. Strings are such a common case that
// we special case them, which avoids that uglyness for the
// users.
if ((name == "::std::basic_string<char, char_traits<char>, allocator<char> >") || // NOLINT linelength
(name == "::std::basic_string<char, ::std::char_traits<char>, ::std::allocator<char> >")) { // NOLINT linelength
name = "::std::string";
}
return name;
}
bool ClifMatcher::MatchAndSetAST(AST* clif_ast) {
assert(ast_ != nullptr && "RunCompiler must be called prior to this.");
int num_unmatched = MatchAndSetDecls(clif_ast->mutable_decls());
LLVM_DEBUG(llvm::dbgs() << "Matched proto:\n" << ProtoDebugString(*clif_ast));
return num_unmatched == 0;
}
int ClifMatcher::MatchAndSetDecls(DeclList* decls) {
int num_unmatched = 0;
for (auto& decl : *decls) {
if (!MatchAndSetOneDecl(&decl)) {
++num_unmatched;
}
}
return num_unmatched;
}
bool ClifMatcher::MatchAndSetOneDecl(Decl* clif_decl) {
bool matched = false;
decl_stack_.push_back(clif_decl);
switch (clif_decl->decltype_()) {
case Decl::CLASS:
matched = MatchAndSetClass(clif_decl->mutable_class_());
break;
case Decl::ENUM:
matched = MatchAndSetEnum(clif_decl->mutable_enum_());
break;
case Decl::VAR:
matched = MatchAndSetVar(clif_decl->mutable_var());
break;
case Decl::CONST:
matched = MatchAndSetConst(clif_decl->mutable_const_());
break;
case Decl::FUNC:
matched = MatchAndSetFunc(clif_decl->mutable_func());
break;
case Decl::TYPE:
matched = MatchAndSetClassName(clif_decl->mutable_fdecl());
break;
case Decl::UNKNOWN:
matched = kTypeMismatch;
break;
}
decl_stack_.pop_back();
return matched;
}
bool ClifMatcher::ImportedFromCorrectFile(const NamedDecl& named_decl,
ClifError* error) const {
// TODO: Suffix checking is not a particularly robust
// way of checking that we imported a declaration from a particular
// file. There could be many files with the given name. This is
// less of an issue if the path in the proto is long, or even a full
// path. We need to figure out some rules. GetSourceFile returns
// strings of the form:
//
// /fully/qualified/path/to/clif/backend/test.h
//
// or a simlar form when not run under a test.
const Decl& clif_decl = *CurrentDecl();
if (!clif_decl.has_cpp_file()) {
return true;
}
std::string clif_cpp_file = clif_decl.cpp_file();
if (clif_cpp_file.empty()) {
return true;
}
std::string source_file = ast_->GetSourceFile(named_decl);
// Examples: .../name.h, .../python/name.h, .../python/name_clif_aux.h
if (llvm::StringRef(source_file).ends_with(clif_cpp_file.c_str())) {
return true;
}
std::string decl_expected_in = clif_cpp_file;
// Testing for kClifAux
std::size_t dot_pos = clif_cpp_file.rfind('.');
if (dot_pos != std::string::npos &&
dot_pos > kClifAuxLen // Intentionally NOT >= (implies len(name) > 0)
&& llvm::StringRef(clif_cpp_file.c_str() + (dot_pos - kClifAuxLen))
.starts_with(kClifAux)) {
// Example: .../python/name.h
std::string clif_cpp_file_no_aux =
clif_cpp_file.substr(0, dot_pos - kClifAuxLen) +
clif_cpp_file.substr(dot_pos, std::string::npos);
if (llvm::StringRef(source_file).ends_with(clif_cpp_file_no_aux.c_str())) {
return true;
}
decl_expected_in += ", " + clif_cpp_file_no_aux;
// Example: .../name.h (one directory level up)
// The name of the subdirectory is intentionally NOT checked HERE.
std::size_t sep_pos_r1 = clif_cpp_file_no_aux.rfind(kFilesystemPathSep);
if (sep_pos_r1 != std::string::npos && sep_pos_r1 > 0) {
std::size_t sep_pos_r2 = clif_cpp_file_no_aux.rfind(
kFilesystemPathSep, sep_pos_r1 - 1);
if (sep_pos_r2 != std::string::npos) {
std::string clif_cpp_file_no_aux_level_up =
clif_cpp_file_no_aux.substr(0, sep_pos_r2) +
clif_cpp_file_no_aux.substr(sep_pos_r1, std::string::npos);
if (llvm::StringRef(source_file)
.ends_with(clif_cpp_file_no_aux_level_up.c_str())) {
return true;
}
decl_expected_in += ", " + clif_cpp_file_no_aux_level_up;
}
}
decl_expected_in = "one of the files {" + decl_expected_in + "}";
} else { // not clif_aux
decl_expected_in = "the file " + decl_expected_in;
}
error->SetCode(kNotInImportFile);
std::string message;
StrAppend(&message,
"Clif expects it in ",
decl_expected_in,
" but found it at ",
ast_->GetClangDeclLocForError(named_decl));
error->AddMessage(message);
return false;
}
template<class ClangDeclType>
ClangDeclType* ClifMatcher::TypecheckLookupResult(
clang::NamedDecl* named_decl,
const std::string& clif_identifier,
const std::string& clif_type) const {
ClangDeclType* decl = CheckDeclType<ClangDeclType>(named_decl);
if (decl == nullptr) {
ReportTypecheckError<ClangDeclType>(named_decl, clif_identifier, clif_type);
}
return decl;
}
template<class ClangDeclType>
ClangDeclType* ClifMatcher::CheckDeclType(clang::NamedDecl* named_decl) const {
// Find the underlying type.
if (clang::isa<clang::TypedefNameDecl>(named_decl)) {
auto typedefname = static_cast<const clang::TypedefNameDecl*>(named_decl);
QualType type = typedefname->getUnderlyingType();
// We don't care if the type is incomplete, but this function also
// finds the named decl which was typedeffed from, which we do
// care about.
type.getTypePtr()->isIncompleteType(&named_decl);
}
if (!clang::isa<ClangDeclType>(named_decl)) {
return nullptr;
}
return static_cast<ClangDeclType*>(named_decl);
}
std::string ClifMatcher::ClifDeclName(
const clang::NamedDecl* named_decl) const {
if (clang::isa<clang::CXXRecordDecl>(named_decl)) {
return "C++ class";
}
if (clang::isa<clang::CXXConstructorDecl>(named_decl)) {
return "C++ constructor";
}
if (clang::isa<clang::CXXDestructorDecl>(named_decl)) {
return "C++ destructor";
}
if (clang::isa<clang::CXXConversionDecl>(named_decl)) {
return "C++ conversion function";
}
if (clang::isa<clang::CXXMethodDecl>(named_decl)) {
return "C++ method";
}
if (clang::isa<clang::FunctionDecl>(named_decl)) {
return "C++ function";
}
if (clang::isa<clang::FunctionTemplateDecl>(named_decl)) {
return "C++ template function";
}
if (clang::isa<clang::ClassTemplateDecl>(named_decl)) {
return "C++ template class";
}
if (clang::isa<clang::ConstructorUsingShadowDecl>(named_decl)) {
return "C++ constructor imported by \"using\" declaration";
}
if (clang::isa<clang::UsingShadowDecl>(named_decl)) {
return "\"using\" declaration";
}
if (clang::isa<clang::EnumDecl>(named_decl)) {
return "C++ enum";
}
if (clang::isa<clang::FieldDecl>(named_decl)) {
return "C++ field";
}
if (clang::isa<clang::VarDecl>(named_decl)) {
return "C++ varaible";
}
return named_decl->getDeclKindName();
}
template<class ClangDeclType>
void ClifMatcher::ReportTypecheckError(
clang::NamedDecl* named_decl,
const std::string& clif_identifier,
const std::string& clif_type) const {
std::string message;
StrAppend(&message, "Type mismatch: Clif declares ", clif_identifier, " as ",
clif_type, " but its name matched \"",
named_decl->getQualifiedNameAsString(), "\" which is a ",
ClifDeclName(named_decl), ".");
ClifError error(*this, kTypeMismatch, message);
error.AddClangDeclAndLocation(ast_.get(), named_decl);
error.Report(CurrentDecl());
}
namespace detail {
// Practical approch to enforcing matching CLIF types for widely used
// optional-like C++ types with implicit conversion to the held type(s).
// Example:
// C++ std::optional<int> ReturnOptionalInt();
// CLIF def ReturnOptionalInt() -> NoneOr<int> # OK
// CLIF def ReturnOptionalInt() -> int # No match b/o logic here.
bool CheckOptionalLikeTypes(
std::string from_clif_name,
std::string to_clif_name) {
const std::array<const std::string, 6> covered_types({
"::absl::optional<",
"::absl::StatusOr<",
"::absl::variant<",
"::std::optional<",
"::std::variant<",
});
for (const auto& covered_type : covered_types) {
if (from_clif_name.find(covered_type, 0) == 0) { // NOLINT abseil-string-find-startswith
continue; // Optional-like in .clif file.
// NOT checking here: Optional-like in .clif but not in C++.
// It fails elsewhere.
}
if (to_clif_name.find(covered_type, 0) != 0) { // NOLINT abseil-string-find-startswith
continue; // Optional-like not in .clif and not in C++.
}
// Optional-like not in .clif but in C++.
return false;
}
return true;
}
} // namespace detail
// Type-promotion often causes unexpected behavior on the
// source-language side, so clif forbid many kinds. Generally,
// promotion within a category is OK (short int to long int). We
// don't want to use the Sema functions (isXXX[Promotion|Conversion])
// here because we are evaluating the promotions as if the from_type
// was a clif type, rather than an allowable C++ standard promotion.
bool ClifMatcher::IsValidClifTypePromotion(
QualType from_type,
QualType to_type) const {
// Can't use "!to_type->isXXXXType()" here because record types such
// as StatusOr may have appropriate conversions.
// Forbid pointer type promotion. (With the caveat that arrays work
// like pointers for the purposes of this calculation.)
if (from_type->isPointerType() &&
!to_type->isPointerType() && !to_type->isArrayType()) {
return false;
}
if (from_type->isReferenceType()) {
from_type = from_type.getNonReferenceType();
}
if (to_type->isReferenceType()) {
to_type = to_type.getNonReferenceType();
}
// Forbid boolean conversions of any sort. Fun fact: C++ considers
// bool an integer type. Allow RecordTypes because implicit
// conversions via constructors are OK, and a user can forbid such
// conversions by using the "explicit" keyword, if one a conversion
// causes them a problem.
if ((from_type->isBooleanType() &&
!to_type->isBooleanType() &&
!to_type->isRecordType()) ||
(to_type->isBooleanType() &&
!from_type->isBooleanType() &&
!from_type->isRecordType())) {
return false;
}
// Char to integer is OK.
// Forbid integer conversions.
if ((from_type->isIntegerType() && (to_type->isFloatingType() ||
to_type->isComplexType())) ||
(to_type->isIntegerType() && (from_type->isFloatingType() ||
from_type->isComplexType()))) {
return false;
}
// Forbid float conversions.
if ((from_type->isFloatingType() && to_type->isComplexType()) ||
(to_type->isFloatingType() && from_type->isComplexType())) {
return false;
}
if (!detail::CheckOptionalLikeTypes(GetQualTypeClifName(from_type),
GetQualTypeClifName(to_type))) {
return false;
}
// Everything else will be caught by AreAssignableTypes.
return true;
}
bool ClifMatcher::AreAssignableTypes(const QualType from_type,
const clang::SourceLocation& loc,
const QualType to_type) const {
assert((from_type.getTypePtrOrNull() != nullptr) && "Invalid type from Clif");
assert((to_type.getTypePtrOrNull() != nullptr) && "Invalid type from C++");
if (!IsValidClifTypePromotion(from_type, to_type)) {
return false;
}
// An erroneous declaration can leave the Sema in an inconsistent
// state, so push a context that says that no code will be generated
// from this expression. This just makes it safer, not completely
// safe. Also, carefully call functions that check if something is
// possible, rather than actually generating the ast which does
// it. These are typically the "CanXXXX" version of a function
// instead of the "XXXX" version.
// The clif type may be assignable to the C++ type via a converting
// constructor. If that converting constructor is part of a template,
// AreAssignableTypes may need to instantiate it. But by the time matching
// takes place, Sema has deleted the Parser and the associated scopes. It is
// something of a wart in clang that instantiating some template declarations
// in this situation need Scopes instead of DeclContexts. Fake a scope for
// those that need it.
//
// Usually this template instantiation happens via a similar construct
// somewhere else in the original source, but if one doesn't exist, there may
// have been no need to instantiate the template before this.
//
// Logically, matching takes place just before the end of the TU, so the TU
// should never have been closed, but buildASTFromCodeWithArgs doesn't allow
// that level of control. It would be more correct to switch to a hand-built
// CompilerInstance which doesn't tear down the parser until after
// matching--the lldb expression parser does this.
ast_->PushFakeTUScope();
// Object's destructor exits the context.
clang::EnterExpressionEvaluationContext context(ast_->GetSema(),
clang::Sema::ExpressionEvaluationContext::Unevaluated);
InitializedEntity entity = InitializedEntity::InitializeResult(loc, to_type
#if PYCLIF_LLVM_VERSION_MAJOR < 14
, false
#endif
);
clang::OpaqueValueExpr init_expr(loc, from_type.getNonReferenceType(),
clang::ExprValueKind::VK_LValue);
bool assignable = ast_->GetSema().CanPerformCopyInitialization(
entity, &init_expr);
// Sema is very sensitive, so don't leave this fake scope in place any longer
// than is absolutely necessary.
ast_->PopFakeTUScope();
return assignable;
}
bool ClifMatcher::AreEqualTypes(QualType from_type, QualType to_type) const {
auto from_canonical_type = from_type.getCanonicalType().getTypePtr();
auto to_canonical_type = to_type.getCanonicalType().getTypePtr();
return (from_canonical_type == to_canonical_type);
}
bool ClifMatcher::SelectTypeWithTypeSelector(
clang::QualType clang_type, ClifRetryType try_type, Type* clif_type,
clang::QualType* type_selected) const {
QualType possible_clif_type;
auto type_map = clif_to_clang_type_map_.find(clif_type->lang_type());
if (type_map == clif_to_clang_type_map_.end()) {
return false;
}
std::vector<std::string> possible_clif_type_names = type_map->second;
QualType first_assignable_clif_type;
int assignable_clif_type_count = 0;
QualType equal_clif_type;
int equal_clif_type_count = 0;
// Iterates through all of the possible CLIF cpp types. Finds the equal type
// to clang type if exists. Otherwise, CLIF chooses the first assignable CLIF
// cpp type to clang type.
for (const std::string& clif_type_name : possible_clif_type_names) {
auto clif_type_iter = clif_qual_types_.find(clif_type_name);
assert(clif_type_iter != clif_qual_types_.end());
possible_clif_type = clif_type_iter->second.qual_type;
if (clif_type->cpp_raw_pointer() && !possible_clif_type->isPointerType()) {
possible_clif_type =
ast_->GetASTContext().getPointerType(possible_clif_type);
}
switch (try_type) {
// Tries the pointer version of the possible CLIF cpp types.
case ClifRetryType::kPointer: {
possible_clif_type = ast_->GetSema().BuildPointerType(
possible_clif_type, clif_type_iter->second.loc, DeclarationName());
break;
}
// Tries the nonconst and nonref version of the possible CLIF cpp types.
case ClifRetryType::kNonconstNonref: {
possible_clif_type =
possible_clif_type.getNonReferenceType().getUnqualifiedType();
break;
}
default:
break;
}
if (AreEqualTypes(possible_clif_type, clang_type)) {
if (equal_clif_type_count == 0) {
equal_clif_type = possible_clif_type;
}
equal_clif_type_count++;
} else if ((try_type != ClifRetryType::kArray &&
AreAssignableTypes(possible_clif_type,
clif_type_iter->second.loc, clang_type)) ||
(try_type == ClifRetryType::kArray &&
AreAssignableTypes(clang_type, clif_type_iter->second.loc,
possible_clif_type))) {
if (assignable_clif_type_count == 0) {
first_assignable_clif_type = possible_clif_type;
}
assignable_clif_type_count++;
}
}
// Chooses the equal candidate type to clang type if there exists.
if (equal_clif_type_count != 0) {
*type_selected = equal_clif_type;
return true;
}
// Otherwise, chooses the first assignable candidate type.
if (assignable_clif_type_count != 0) {
*type_selected = first_assignable_clif_type;
return true;
}
// Otherwise, there is no available clif cpp type.
return false;
}
// Selects the appropriate CLIF cpp type either with/without type selector.
bool ClifMatcher::SelectType(const clang::QualType& clang_type,
ClifRetryType try_type, bool enable_type_selector,
const ClifQualTypeDecl* clif_cpp_decl,
Type* clif_type,
clang::QualType* type_selected) const {
if (enable_type_selector) {
return SelectTypeWithTypeSelector(clang_type, try_type, clif_type,
type_selected);
}
// When users specify the cpp_type on purpose, CLIF will disable the type
// selector and use the user specified CLIF cpp type.
// Desugars to use what the user wrote, rather than clif_type_0.
*type_selected = clif_cpp_decl->qual_type.getSingleStepDesugaredType(
ast_->GetASTContext());
if (clif_type->cpp_raw_pointer() && !(*type_selected)->isPointerType()) {
*type_selected = ast_->GetASTContext().getPointerType(*type_selected);
}
switch (try_type) {
case ClifRetryType::kPointer: {
*type_selected = ast_->GetSema().BuildPointerType(
*type_selected, clif_cpp_decl->loc, DeclarationName());
break;
}
case ClifRetryType::kArray: {
return AreAssignableTypes(clang_type, clif_cpp_decl->loc, *type_selected);
}
case ClifRetryType::kNonconstNonref: {
*type_selected =
type_selected->getNonReferenceType().getUnqualifiedType();
break;
}
default:
break;
}
return AreAssignableTypes(*type_selected, clif_cpp_decl->loc, clang_type);
}
bool ClifMatcher::MatchAndSetClassName(ForwardDecl* forward_decl) const {
auto clif_qual_type = clif_qual_types_.find(forward_decl->name().cpp_name());
assert(clif_qual_type != clif_qual_types_.end());
forward_decl->mutable_name()->set_cpp_name(
clang::TypeName::getFullyQualifiedName(
clif_qual_type->second.qual_type, ast_->GetASTContext(),
ast_->GetASTContext().getPrintingPolicy(),
true /* Include "::" prefix */));
// We always set these to true for classes and capsules.
ast_->AddPtrConversionType(clif_qual_type->second.qual_type);
ast_->AddUniquePtrConversionType(clif_qual_type->second.qual_type);
return true;
}
// Calculate if a base type should be added to the clif declaration. Return
// false if non-virtual diamond inheritance happens.
bool ClifMatcher::CalculateBaseClassesHelper(
ClassDecl* clif_decl, BaseSpecifierQueue* base_queue,
QualTypeMap* public_bases,
ClassTempSpecializedDeclMap* public_template_specialized_bases) const {
auto base = base_queue->front();
base_queue->pop();
// Bypass private and protected base classes.
if (base.getAccessSpecifier() == clang::AS_public) {
bool is_virtual = base.isVirtual();
QualType base_type = base.getType();
CXXRecordDecl* base_clang_decl = base_type->getAsCXXRecordDecl();
if (public_bases->find(base_type) == public_bases->end()) {
// Template specialized base classes are differently represented from
// regular base classes. Consider the following diamond inheritance
// example:
// template <class T>
// class base {};
//
// template <class T>
// class derive1: virtual public base<T> {};
//
// template <class T>
// class derive2: virtual public base<T> {};
//
// template <class T>
// class derive3: virtual public derive1<T>, virtual public derive2<T> {};
//
// While processing derive3's base classes, we will encounter "base<int>"
// twice, one(named "b1") is the base of "derive1" and another(names "b2")
// is the base of "derive2". "b1" and "b2" have different QualTypes
// because class "base" is specialized separately for them, but the same
// ClassTemplateSpecializationDecl. To avoid the duplication of
// recording base classes in diamond inheritance, we also need to keep a
// set of ClassTemplateSpecializationDecl for specialized template base
// classes.
auto template_specialized_decl =
llvm::dyn_cast<ClassTemplateSpecializationDecl>(base_clang_decl);
if (template_specialized_decl) {
auto decl_iter =
public_template_specialized_bases->find(template_specialized_decl);
if (decl_iter != public_template_specialized_bases->end()) {
// Non-virtual diamond inheritance for template classes.
if (decl_iter->second != true || !is_virtual) {
return false;
}
return true;
}
public_template_specialized_bases->insert(
{template_specialized_decl, is_virtual});
}
const std::string base_type_name = GetQualTypeClifName(base_type);
// The proto fields "bases" and "cpp_bases" are separate for
// historical reasons.
auto* mutable_base = clif_decl->add_bases();
mutable_base->set_cpp_name(base_type_name);
mutable_base->set_cpp_canonical_type(GetCanonicalType(base_type));
ClassDecl::Base* cpp_base = clif_decl->add_cpp_bases();
cpp_base->set_name(base_type_name);
cpp_base->set_filename(ast_->GetSourceFile(*base_clang_decl));
if (auto* context = base_clang_decl->getEnclosingNamespaceContext()) {
if (auto* namespace_decl = llvm::dyn_cast<NamespaceDecl>(context)) {
cpp_base->set_namespace_(namespace_decl->getNameAsString());
}
}
for (auto child_base : base_clang_decl->bases()) {
base_queue->push(child_base);
}
public_bases->insert({base_type, is_virtual});
} else if ((*public_bases)[base_type] != true || !is_virtual) {
// Non-virtual diamond inheritance for regular classes.
return false;
}
}
return true;
}
// Collect public base classes of |clang_decl| and save them in |clif_decl|.
bool ClifMatcher::CalculateBaseClasses(const CXXRecordDecl* clang_decl,
ClassDecl* clif_decl) const {
if (clang_decl->hasDefinition()) {
clang_decl = clang_decl->getDefinition();
} else {
if (llvm::isa<ClassTemplateSpecializationDecl>(clang_decl)) {
return true;
}
ClifError error(*this, kNoDefinitionAvailable);
error.Report(CurrentDecl());
return false;
}
// Traverse all of the base classes of the current ClassDecl and update
// clif_decl. Base classes for private/protected inheritances are skipped.
// "base_queue" stores the base classes waiting to be processed.
BaseSpecifierQueue base_queue;
// public_bases keeps already processed bases to avoid duplicate reporting.
QualTypeMap public_bases;