clang-tools 24.0.0git
LexerUtils.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
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 "LexerUtils.h"
10#include "clang/Basic/SourceManager.h"
11#include <optional>
12#include <utility>
13#include <vector>
14
16
17StringRef getTokenName(const Token &Tok) {
18 if (Tok.is(tok::raw_identifier))
19 return Tok.getRawIdentifier();
20 if (const IdentifierInfo *Info = Tok.getIdentifierInfo())
21 return Info->getName();
22 return {};
23}
24
25std::vector<Token> getRawTokens(CharSourceRange Range, const SourceManager &SM,
26 const LangOptions &LangOpts) {
27 if (Range.isInvalid())
28 return {};
29
30 const CharSourceRange FileRange =
31 Lexer::makeFileCharRange(Range, SM, LangOpts);
32 if (FileRange.isInvalid())
33 return {};
34
35 bool Invalid = false;
36 const StringRef Text =
37 Lexer::getSourceText(FileRange, SM, LangOpts, &Invalid);
38 if (Invalid || Text.empty())
39 return {};
40
41 const auto [File, BeginOffset] = SM.getDecomposedLoc(FileRange.getBegin());
42 const StringRef Buffer = SM.getBufferData(File, &Invalid);
43 if (Invalid || BeginOffset + Text.size() > Buffer.size())
44 return {};
45
46 Lexer RawLexer(SM.getLocForStartOfFile(File), LangOpts, Buffer.begin(),
47 Buffer.begin() + BeginOffset, Buffer.end());
48 const size_t EndOffset = BeginOffset + Text.size();
49 std::vector<Token> Tokens;
50 Token Tok;
51 while (!RawLexer.LexFromRawLexer(Tok) && Tok.isNot(tok::eof) &&
52 SM.getFileOffset(Tok.getLocation()) < EndOffset)
53 Tokens.push_back(Tok);
54 return Tokens;
55}
56
57std::pair<std::optional<Token>, SourceLocation>
58getPreviousTokenAndStart(SourceLocation Location, const SourceManager &SM,
59 const LangOptions &LangOpts, bool SkipComments) {
60 const std::optional<Token> Tok =
61 Lexer::findPreviousToken(Location, SM, LangOpts, !SkipComments);
62
63 if (Tok.has_value())
64 return {*Tok, Lexer::GetBeginningOfToken(Tok->getLocation(), SM, LangOpts)};
65
66 return {std::nullopt, SourceLocation()};
67}
68
69std::optional<Token> getPreviousToken(SourceLocation Location,
70 const SourceManager &SM,
71 const LangOptions &LangOpts,
72 bool SkipComments) {
73 auto [Token, Start] =
74 getPreviousTokenAndStart(Location, SM, LangOpts, SkipComments);
75 return Token;
76}
77
78SourceLocation findPreviousTokenStart(SourceLocation Start,
79 const SourceManager &SM,
80 const LangOptions &LangOpts) {
81 if (Start.isInvalid() || Start.isMacroID())
82 return {};
83
84 const SourceLocation BeforeStart = Start.getLocWithOffset(-1);
85 if (BeforeStart.isInvalid() || BeforeStart.isMacroID())
86 return {};
87
88 return Lexer::GetBeginningOfToken(BeforeStart, SM, LangOpts);
89}
90
91SourceLocation findPreviousTokenKind(SourceLocation Start,
92 const SourceManager &SM,
93 const LangOptions &LangOpts,
94 tok::TokenKind TK) {
95 if (Start.isInvalid() || Start.isMacroID())
96 return {};
97
98 while (true) {
99 const SourceLocation L = findPreviousTokenStart(Start, SM, LangOpts);
100 if (L.isInvalid() || L.isMacroID())
101 return {};
102
103 Token T;
104 if (Lexer::getRawToken(L, T, SM, LangOpts, /*IgnoreWhiteSpace=*/true))
105 return {};
106
107 if (T.is(TK))
108 return T.getLocation();
109
110 Start = L;
111 }
112}
113
114SourceLocation findNextTerminator(SourceLocation Start, const SourceManager &SM,
115 const LangOptions &LangOpts) {
116 return findNextAnyTokenKind(Start, SM, LangOpts, tok::comma, tok::semi);
117}
118
120 const SourceManager &SM,
121 const LangOptions &LangOpts) {
122 assert(Range.isValid() && "Invalid Range for relexing provided");
123 SourceLocation Loc = Range.getBegin();
124
125 while (Loc <= Range.getEnd()) {
126 if (Loc.isMacroID())
127 return true;
128
129 std::optional<Token> Tok = findNextTokenSkippingComments(Loc, SM, LangOpts);
130
131 if (!Tok)
132 return true;
133
134 if (Tok->is(tok::hash))
135 return true;
136
137 Loc = Tok->getLocation();
138 }
139
140 return false;
141}
142
143namespace {
144enum class CommentCollectionMode { AllComments, TrailingComments };
145} // namespace
146
147static std::vector<CommentToken>
148collectCommentsInRange(CharSourceRange Range, const SourceManager &SM,
149 const LangOptions &LangOpts,
150 CommentCollectionMode Mode) {
151 std::vector<CommentToken> Comments;
152 if (Range.isInvalid())
153 return Comments;
154
155 const CharSourceRange FileRange =
156 Lexer::makeFileCharRange(Range, SM, LangOpts);
157 if (FileRange.isInvalid())
158 return Comments;
159
160 const std::pair<FileID, unsigned> BeginLoc =
161 SM.getDecomposedLoc(FileRange.getBegin());
162 const std::pair<FileID, unsigned> EndLoc =
163 SM.getDecomposedLoc(FileRange.getEnd());
164
165 if (BeginLoc.first != EndLoc.first)
166 return Comments;
167
168 bool Invalid = false;
169 const StringRef Buffer = SM.getBufferData(BeginLoc.first, &Invalid);
170 if (Invalid)
171 return Comments;
172
173 const char *StrData = Buffer.data() + BeginLoc.second;
174
175 Lexer TheLexer(SM.getLocForStartOfFile(BeginLoc.first), LangOpts,
176 Buffer.begin(), StrData, Buffer.end());
177 // Use raw lexing with comment retention so we can see comment tokens without
178 // preprocessing or macro expansion effects.
179 TheLexer.SetCommentRetentionState(true);
180
181 while (true) {
182 Token Tok;
183 if (TheLexer.LexFromRawLexer(Tok))
184 break;
185 if (Tok.is(tok::eof) || Tok.getLocation() == FileRange.getEnd() ||
186 SM.isBeforeInTranslationUnit(FileRange.getEnd(), Tok.getLocation()))
187 break;
188
189 if (Tok.is(tok::comment)) {
190 const std::pair<FileID, unsigned> CommentLoc =
191 SM.getDecomposedLoc(Tok.getLocation());
192 assert(CommentLoc.first == BeginLoc.first);
193 Comments.emplace_back(CommentToken{
194 Tok.getLocation(),
195 StringRef(Buffer.begin() + CommentLoc.second, Tok.getLength()),
196 });
197 } else if (Mode == CommentCollectionMode::TrailingComments) {
198 // Clear comments found before the different token, e.g. comma. Callers
199 // use this to retrieve only the contiguous comment block that directly
200 // precedes a token of interest.
201 Comments.clear();
202 }
203 }
204
205 return Comments;
206}
207
208std::vector<CommentToken> getCommentsInRange(CharSourceRange Range,
209 const SourceManager &SM,
210 const LangOptions &LangOpts) {
211 return collectCommentsInRange(Range, SM, LangOpts,
212 CommentCollectionMode::AllComments);
213}
214
215std::vector<CommentToken>
216getTrailingCommentsInRange(CharSourceRange Range, const SourceManager &SM,
217 const LangOptions &LangOpts) {
218 return collectCommentsInRange(Range, SM, LangOpts,
219 CommentCollectionMode::TrailingComments);
220}
221
222CharSourceRange
223findTokenTextInRange(CharSourceRange Range, const SourceManager &SM,
224 const LangOptions &LangOpts,
225 llvm::function_ref<bool(const Token &)> Pred) {
226 if (Range.isInvalid())
227 return {};
228
229 // Normalize to a file-based char range so raw lexing can operate on one
230 // contiguous buffer and reject unmappable (e.g. macro) ranges.
231 const CharSourceRange FileRange =
232 Lexer::makeFileCharRange(Range, SM, LangOpts);
233 if (FileRange.isInvalid())
234 return {};
235
236 const auto [BeginFID, BeginOffset] =
237 SM.getDecomposedLoc(FileRange.getBegin());
238 const auto [EndFID, EndOffset] = SM.getDecomposedLoc(FileRange.getEnd());
239 if (BeginFID != EndFID || BeginOffset > EndOffset)
240 return {};
241
242 bool Invalid = false;
243 const StringRef Buffer = SM.getBufferData(BeginFID, &Invalid);
244 if (Invalid)
245 return {};
246
247 const char *LexStart = Buffer.data() + BeginOffset;
248 // Re-lex raw tokens in the bounded file buffer while preserving comments so
249 // callers can match tokens regardless of interleaved comments.
250 Lexer TheLexer(SM.getLocForStartOfFile(BeginFID), LangOpts, Buffer.begin(),
251 LexStart, Buffer.end());
252 TheLexer.SetCommentRetentionState(true);
253
254 while (true) {
255 Token Tok;
256 if (TheLexer.LexFromRawLexer(Tok))
257 return {};
258
259 if (Tok.is(tok::eof) || Tok.getLocation() == FileRange.getEnd() ||
260 SM.isBeforeInTranslationUnit(FileRange.getEnd(), Tok.getLocation()))
261 return {};
262
263 if (!Pred(Tok))
264 continue;
265
266 Token NextTok;
267 if (TheLexer.LexFromRawLexer(NextTok))
268 return {};
269 // Return a char range ending at the next token start so trailing trivia of
270 // the matched token is included (useful for fix-it removals).
271 return CharSourceRange::getCharRange(Tok.getLocation(),
272 NextTok.getLocation());
273 }
274}
275
276std::optional<Token> getQualifyingToken(tok::TokenKind TK,
277 CharSourceRange Range,
278 const ASTContext &Context,
279 const SourceManager &SM) {
280 assert((TK == tok::kw_const || TK == tok::kw_volatile ||
281 TK == tok::kw_restrict) &&
282 "TK is not a qualifier keyword");
283 const std::pair<FileID, unsigned> LocInfo =
284 SM.getDecomposedLoc(Range.getBegin());
285 const StringRef File = SM.getBufferData(LocInfo.first);
286 Lexer RawLexer(SM.getLocForStartOfFile(LocInfo.first), Context.getLangOpts(),
287 File.begin(), File.data() + LocInfo.second, File.end());
288 std::optional<Token> LastMatchBeforeTemplate;
289 std::optional<Token> LastMatchAfterTemplate;
290 bool SawTemplate = false;
291 Token Tok;
292 while (!RawLexer.LexFromRawLexer(Tok) &&
293 Range.getEnd() != Tok.getLocation() &&
294 !SM.isBeforeInTranslationUnit(Range.getEnd(), Tok.getLocation())) {
295 if (Tok.is(tok::raw_identifier)) {
296 IdentifierInfo &Info = Context.Idents.get(
297 StringRef(SM.getCharacterData(Tok.getLocation()), Tok.getLength()));
298 Tok.setIdentifierInfo(&Info);
299 Tok.setKind(Info.getTokenID());
300 }
301 if (Tok.is(tok::less)) {
302 SawTemplate = true;
303 } else if (Tok.isOneOf(tok::greater, tok::greatergreater)) {
304 LastMatchAfterTemplate = std::nullopt;
305 } else if (Tok.is(TK)) {
306 if (SawTemplate)
307 LastMatchAfterTemplate = Tok;
308 else
309 LastMatchBeforeTemplate = Tok;
310 }
311 }
312 return LastMatchAfterTemplate != std::nullopt ? LastMatchAfterTemplate
313 : LastMatchBeforeTemplate;
314}
315
316static bool breakAndReturnEnd(const Stmt &S) {
317 return isa<CompoundStmt, DeclStmt, NullStmt>(S);
318}
319
320static bool breakAndReturnEndPlus1Token(const Stmt &S) {
321 return isa<Expr, DoStmt, ReturnStmt, BreakStmt, ContinueStmt, GotoStmt,
322 SEHLeaveStmt>(S);
323}
324
325// Given a Stmt which does not include it's semicolon this method returns the
326// SourceLocation of the semicolon.
327static SourceLocation getSemicolonAfterStmtEndLoc(const SourceLocation &EndLoc,
328 const SourceManager &SM,
329 const LangOptions &LangOpts) {
330 if (EndLoc.isMacroID()) {
331 // Assuming EndLoc points to a function call foo within macro F.
332 // This method is supposed to return location of the semicolon within
333 // those macro arguments:
334 // F ( foo() ; )
335 // ^ EndLoc ^ SpellingLoc ^ next token of SpellingLoc
336 const SourceLocation SpellingLoc = SM.getSpellingLoc(EndLoc);
337 std::optional<Token> NextTok =
338 findNextTokenSkippingComments(SpellingLoc, SM, LangOpts);
339
340 // Was the next token found successfully?
341 // All macro issues are simply resolved by ensuring it's a semicolon.
342 if (NextTok && NextTok->is(tok::TokenKind::semi)) {
343 // Ideally this would return `F` with spelling location `;` (NextTok)
344 // following the example above. For now simply return NextTok location.
345 return NextTok->getLocation();
346 }
347
348 // Fallthrough to 'normal handling'.
349 // F ( foo() ) ;
350 // ^ EndLoc ^ SpellingLoc ) ^ next token of EndLoc
351 }
352
353 std::optional<Token> NextTok =
354 findNextTokenSkippingComments(EndLoc, SM, LangOpts);
355
356 // Testing for semicolon again avoids some issues with macros.
357 if (NextTok && NextTok->is(tok::TokenKind::semi))
358 return NextTok->getLocation();
359
360 return {};
361}
362
363SourceLocation getUnifiedEndLoc(const Stmt &S, const SourceManager &SM,
364 const LangOptions &LangOpts) {
365 const Stmt *LastChild = &S;
366 while (!LastChild->children().empty() && !breakAndReturnEnd(*LastChild) &&
367 !breakAndReturnEndPlus1Token(*LastChild)) {
368 for (const Stmt *Child : LastChild->children())
369 LastChild = Child;
370 }
371
372 if (!breakAndReturnEnd(*LastChild) && breakAndReturnEndPlus1Token(*LastChild))
373 return getSemicolonAfterStmtEndLoc(S.getEndLoc(), SM, LangOpts);
374
375 return S.getEndLoc();
376}
377
378SourceLocation getLocationForNoexceptSpecifier(const FunctionDecl *FuncDecl,
379 const SourceManager &SM) {
380 if (!FuncDecl)
381 return {};
382
383 const LangOptions &LangOpts = FuncDecl->getLangOpts();
384
385 if (FuncDecl->getNumParams() == 0) {
386 // Start at the beginning of the function declaration, and find the closing
387 // parenthesis after which we would place the noexcept specifier.
388 Token CurrentToken;
389 SourceLocation CurrentLocation = FuncDecl->getBeginLoc();
390 while (!Lexer::getRawToken(CurrentLocation, CurrentToken, SM, LangOpts,
391 true)) {
392 if (CurrentToken.is(tok::r_paren))
393 return CurrentLocation.getLocWithOffset(1);
394
395 CurrentLocation = CurrentToken.getEndLoc();
396 }
397
398 // Failed to find the closing parenthesis, so just return an invalid
399 // SourceLocation.
400 return {};
401 }
402
403 // FunctionDecl with parameters
404 const SourceLocation NoexceptLoc =
405 FuncDecl->getParamDecl(FuncDecl->getNumParams() - 1)->getEndLoc();
406 if (NoexceptLoc.isValid())
407 return Lexer::findLocationAfterToken(
408 NoexceptLoc, tok::r_paren, SM, LangOpts,
409 /*SkipTrailingWhitespaceAndNewLine=*/true);
410
411 return {};
412}
413
414} // namespace clang::tidy::utils::lexer
std::pair< std::optional< Token >, SourceLocation > getPreviousTokenAndStart(SourceLocation Location, const SourceManager &SM, const LangOptions &LangOpts, bool SkipComments)
SourceLocation getLocationForNoexceptSpecifier(const FunctionDecl *FuncDecl, const SourceManager &SM)
For a given FunctionDecl returns the location where you would need to place the noexcept specifier.
SourceLocation getUnifiedEndLoc(const Stmt &S, const SourceManager &SM, const LangOptions &LangOpts)
Stmt->getEndLoc does not always behave the same way depending on Token type.
bool rangeContainsExpansionsOrDirectives(SourceRange Range, const SourceManager &SM, const LangOptions &LangOpts)
Re-lex the provide Range and return false if either a macro spans multiple tokens,...
std::vector< Token > getRawTokens(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts)
Returns the raw tokens in Range.
SourceLocation findNextTerminator(SourceLocation Start, const SourceManager &SM, const LangOptions &LangOpts)
StringRef getTokenName(const Token &Tok)
Returns the spelling of an identifier token.
std::optional< Token > getPreviousToken(SourceLocation Location, const SourceManager &SM, const LangOptions &LangOpts, bool SkipComments)
Returns previous token or std::nullopt if not found.
std::vector< CommentToken > getTrailingCommentsInRange(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts)
Returns comment tokens found in the given range. If a non-comment token is encountered,...
SourceLocation findNextAnyTokenKind(SourceLocation Start, const SourceManager &SM, const LangOptions &LangOpts, TokenKind TK, TokenKinds... TKs)
Definition LexerUtils.h:81
std::optional< Token > findNextTokenSkippingComments(SourceLocation Start, const SourceManager &SM, const LangOptions &LangOpts)
Definition LexerUtils.h:114
SourceLocation findPreviousTokenStart(SourceLocation Start, const SourceManager &SM, const LangOptions &LangOpts)
static SourceLocation getSemicolonAfterStmtEndLoc(const SourceLocation &EndLoc, const SourceManager &SM, const LangOptions &LangOpts)
CharSourceRange findTokenTextInRange(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts, llvm::function_ref< bool(const Token &)> Pred)
Returns source range of the first token in Range matching Pred. The returned char range starts at the...
static bool breakAndReturnEndPlus1Token(const Stmt &S)
static bool breakAndReturnEnd(const Stmt &S)
std::vector< CommentToken > getCommentsInRange(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts)
Returns all comment tokens found in the given range.
static std::vector< CommentToken > collectCommentsInRange(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts, CommentCollectionMode Mode)
SourceLocation findPreviousTokenKind(SourceLocation Start, const SourceManager &SM, const LangOptions &LangOpts, tok::TokenKind TK)
std::optional< Token > getQualifyingToken(tok::TokenKind TK, CharSourceRange Range, const ASTContext &Context, const SourceManager &SM)
Assuming that Range spans a CVR-qualified type, returns the token in Range that is responsible for th...
static constexpr const char FuncDecl[]