1 //===--- IntegerTypesCheck.cpp - clang-tidy -------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "IntegerTypesCheck.h"
10 #include "clang/AST/ASTContext.h"
11 #include "clang/ASTMatchers/ASTMatchFinder.h"
12 #include "clang/ASTMatchers/ASTMatchers.h"
13 #include "clang/Basic/AttrKinds.h"
14 #include "clang/Basic/CharInfo.h"
15 #include "clang/Basic/IdentifierTable.h"
16 #include "clang/Basic/TargetInfo.h"
17 #include "clang/Lex/Lexer.h"
18 
19 namespace clang {
20 
21 using namespace ast_matchers;
22 
23 static Token getTokenAtLoc(SourceLocation Loc,
24                            const MatchFinder::MatchResult &MatchResult,
25                            IdentifierTable &IdentTable) {
26   Token Tok;
27   if (Lexer::getRawToken(Loc, Tok, *MatchResult.SourceManager,
28                          MatchResult.Context->getLangOpts(), false))
29     return Tok;
30 
31   if (Tok.is(tok::raw_identifier)) {
32     IdentifierInfo &Info = IdentTable.get(Tok.getRawIdentifier());
33     Tok.setIdentifierInfo(&Info);
34     Tok.setKind(Info.getTokenID());
35   }
36   return Tok;
37 }
38 
39 namespace tidy {
40 namespace google {
41 namespace runtime {
42 
43 IntegerTypesCheck::IntegerTypesCheck(StringRef Name, ClangTidyContext *Context)
44     : ClangTidyCheck(Name, Context),
45       UnsignedTypePrefix(Options.get("UnsignedTypePrefix", "uint")),
46       SignedTypePrefix(Options.get("SignedTypePrefix", "int")),
47       TypeSuffix(Options.get("TypeSuffix", "")) {}
48 
49 void IntegerTypesCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
50   Options.store(Opts, "UnsignedTypePrefix", UnsignedTypePrefix);
51   Options.store(Opts, "SignedTypePrefix", SignedTypePrefix);
52   Options.store(Opts, "TypeSuffix", TypeSuffix);
53 }
54 
55 void IntegerTypesCheck::registerMatchers(MatchFinder *Finder) {
56   // Find all TypeLocs. The relevant Style Guide rule only applies to C++.
57   // This check is also not applied in Objective-C++ sources as Objective-C
58   // often uses built-in integer types other than `int`.
59   if (!getLangOpts().CPlusPlus || getLangOpts().ObjC)
60     return;
61   // Match any integer types, unless they are passed to a printf-based API:
62   //
63   // http://google.github.io/styleguide/cppguide.html#64-bit_Portability
64   // "Where possible, avoid passing arguments of types specified by
65   // bitwidth typedefs to printf-based APIs."
66   Finder->addMatcher(typeLoc(loc(isInteger()),
67                              unless(hasAncestor(callExpr(
68                                  callee(functionDecl(hasAttr(attr::Format)))))))
69                          .bind("tl"),
70                      this);
71   IdentTable = std::make_unique<IdentifierTable>(getLangOpts());
72 }
73 
74 void IntegerTypesCheck::check(const MatchFinder::MatchResult &Result) {
75   auto TL = *Result.Nodes.getNodeAs<TypeLoc>("tl");
76   SourceLocation Loc = TL.getBeginLoc();
77 
78   if (Loc.isInvalid() || Loc.isMacroID())
79     return;
80 
81   // Look through qualification.
82   if (auto QualLoc = TL.getAs<QualifiedTypeLoc>())
83     TL = QualLoc.getUnqualifiedLoc();
84 
85   auto BuiltinLoc = TL.getAs<BuiltinTypeLoc>();
86   if (!BuiltinLoc)
87     return;
88 
89   Token Tok = getTokenAtLoc(Loc, Result, *IdentTable);
90   // Ensure the location actually points to one of the builting integral type
91   // names we're interested in. Otherwise, we might be getting this match from
92   // implicit code (e.g. an implicit assignment operator of a class containing
93   // an array of non-POD types).
94   if (!Tok.isOneOf(tok::kw_short, tok::kw_long, tok::kw_unsigned,
95                    tok::kw_signed))
96     return;
97 
98   bool IsSigned;
99   unsigned Width;
100   const TargetInfo &TargetInfo = Result.Context->getTargetInfo();
101 
102   // Look for uses of short, long, long long and their unsigned versions.
103   switch (BuiltinLoc.getTypePtr()->getKind()) {
104   case BuiltinType::Short:
105     Width = TargetInfo.getShortWidth();
106     IsSigned = true;
107     break;
108   case BuiltinType::Long:
109     Width = TargetInfo.getLongWidth();
110     IsSigned = true;
111     break;
112   case BuiltinType::LongLong:
113     Width = TargetInfo.getLongLongWidth();
114     IsSigned = true;
115     break;
116   case BuiltinType::UShort:
117     Width = TargetInfo.getShortWidth();
118     IsSigned = false;
119     break;
120   case BuiltinType::ULong:
121     Width = TargetInfo.getLongWidth();
122     IsSigned = false;
123     break;
124   case BuiltinType::ULongLong:
125     Width = TargetInfo.getLongLongWidth();
126     IsSigned = false;
127     break;
128   default:
129     return;
130   }
131 
132   // We allow "unsigned short port" as that's reasonably common and required by
133   // the sockets API.
134   const StringRef Port = "unsigned short port";
135   const char *Data = Result.SourceManager->getCharacterData(Loc);
136   if (!std::strncmp(Data, Port.data(), Port.size()) &&
137       !isIdentifierBody(Data[Port.size()]))
138     return;
139 
140   std::string Replacement =
141       ((IsSigned ? SignedTypePrefix : UnsignedTypePrefix) + Twine(Width) +
142        TypeSuffix)
143           .str();
144 
145   // We don't add a fix-it as changing the type can easily break code,
146   // e.g. when a function requires a 'long' argument on all platforms.
147   // QualTypes are printed with implicit quotes.
148   diag(Loc, "consider replacing %0 with '%1'") << BuiltinLoc.getType()
149                                                << Replacement;
150 }
151 
152 } // namespace runtime
153 } // namespace google
154 } // namespace tidy
155 } // namespace clang
156