1 //===--- SourceCode.cpp - Source code manipulation routines -----*- C++ -*-===//
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 //  This file provides functions that simplify extraction of source code.
10 //
11 //===----------------------------------------------------------------------===//
12 #include "clang/Tooling/Transformer/SourceCode.h"
13 #include "clang/AST/ASTContext.h"
14 #include "clang/AST/Attr.h"
15 #include "clang/AST/Comment.h"
16 #include "clang/AST/Decl.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclTemplate.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/Basic/SourceManager.h"
21 #include "clang/Lex/Lexer.h"
22 #include "llvm/Support/Errc.h"
23 #include "llvm/Support/Error.h"
24 #include <set>
25 
26 using namespace clang;
27 
28 using llvm::errc;
29 using llvm::StringError;
30 
31 StringRef clang::tooling::getText(CharSourceRange Range,
32                                   const ASTContext &Context) {
33   return Lexer::getSourceText(Range, Context.getSourceManager(),
34                               Context.getLangOpts());
35 }
36 
37 CharSourceRange clang::tooling::maybeExtendRange(CharSourceRange Range,
38                                                  tok::TokenKind Next,
39                                                  ASTContext &Context) {
40   Optional<Token> Tok = Lexer::findNextToken(
41       Range.getEnd(), Context.getSourceManager(), Context.getLangOpts());
42   if (!Tok || !Tok->is(Next))
43     return Range;
44   return CharSourceRange::getTokenRange(Range.getBegin(), Tok->getLocation());
45 }
46 
47 llvm::Error clang::tooling::validateEditRange(const CharSourceRange &Range,
48                                               const SourceManager &SM) {
49   if (Range.isInvalid())
50     return llvm::make_error<StringError>(errc::invalid_argument,
51                                          "Invalid range");
52 
53   if (Range.getBegin().isMacroID() || Range.getEnd().isMacroID())
54     return llvm::make_error<StringError>(
55         errc::invalid_argument, "Range starts or ends in a macro expansion");
56 
57   if (SM.isInSystemHeader(Range.getBegin()) ||
58       SM.isInSystemHeader(Range.getEnd()))
59     return llvm::make_error<StringError>(errc::invalid_argument,
60                                          "Range is in system header");
61 
62   std::pair<FileID, unsigned> BeginInfo = SM.getDecomposedLoc(Range.getBegin());
63   std::pair<FileID, unsigned> EndInfo = SM.getDecomposedLoc(Range.getEnd());
64   if (BeginInfo.first != EndInfo.first)
65     return llvm::make_error<StringError>(
66         errc::invalid_argument, "Range begins and ends in different files");
67 
68   if (BeginInfo.second > EndInfo.second)
69     return llvm::make_error<StringError>(
70         errc::invalid_argument, "Range's begin is past its end");
71 
72   return llvm::Error::success();
73 }
74 
75 llvm::Optional<CharSourceRange>
76 clang::tooling::getRangeForEdit(const CharSourceRange &EditRange,
77                                 const SourceManager &SM,
78                                 const LangOptions &LangOpts) {
79   // FIXME: makeFileCharRange() has the disadvantage of stripping off "identity"
80   // macros. For example, if we're looking to rewrite the int literal 3 to 6,
81   // and we have the following definition:
82   //    #define DO_NOTHING(x) x
83   // then
84   //    foo(DO_NOTHING(3))
85   // will be rewritten to
86   //    foo(6)
87   // rather than the arguably better
88   //    foo(DO_NOTHING(6))
89   // Decide whether the current behavior is desirable and modify if not.
90   CharSourceRange Range = Lexer::makeFileCharRange(EditRange, SM, LangOpts);
91   bool IsInvalid = llvm::errorToBool(validateEditRange(Range, SM));
92   if (IsInvalid)
93     return llvm::None;
94   return Range;
95 
96 }
97 
98 static bool startsWithNewline(const SourceManager &SM, const Token &Tok) {
99   return isVerticalWhitespace(SM.getCharacterData(Tok.getLocation())[0]);
100 }
101 
102 static bool contains(const std::set<tok::TokenKind> &Terminators,
103                      const Token &Tok) {
104   return Terminators.count(Tok.getKind()) > 0;
105 }
106 
107 // Returns the exclusive, *file* end location of the entity whose last token is
108 // at location 'EntityLast'. That is, it returns the location one past the last
109 // relevant character.
110 //
111 // Associated tokens include comments, horizontal whitespace and 'Terminators'
112 // -- optional tokens, which, if any are found, will be included; if
113 // 'Terminators' is empty, we will not include any extra tokens beyond comments
114 // and horizontal whitespace.
115 static SourceLocation
116 getEntityEndLoc(const SourceManager &SM, SourceLocation EntityLast,
117                 const std::set<tok::TokenKind> &Terminators,
118                 const LangOptions &LangOpts) {
119   assert(EntityLast.isValid() && "Invalid end location found.");
120 
121   // We remember the last location of a non-horizontal-whitespace token we have
122   // lexed; this is the location up to which we will want to delete.
123   // FIXME: Support using the spelling loc here for cases where we want to
124   // analyze the macro text.
125 
126   CharSourceRange ExpansionRange = SM.getExpansionRange(EntityLast);
127   // FIXME: Should check isTokenRange(), for the (rare) case that
128   // `ExpansionRange` is a character range.
129   std::unique_ptr<Lexer> Lexer = [&]() {
130     bool Invalid = false;
131     auto FileOffset = SM.getDecomposedLoc(ExpansionRange.getEnd());
132     llvm::StringRef File = SM.getBufferData(FileOffset.first, &Invalid);
133     assert(!Invalid && "Cannot get file/offset");
134     return std::make_unique<clang::Lexer>(
135         SM.getLocForStartOfFile(FileOffset.first), LangOpts, File.begin(),
136         File.data() + FileOffset.second, File.end());
137   }();
138 
139   // Tell Lexer to return whitespace as pseudo-tokens (kind is tok::unknown).
140   Lexer->SetKeepWhitespaceMode(true);
141 
142   // Generally, the code we want to include looks like this ([] are optional),
143   // If Terminators is empty:
144   //   [ <comment> ] [ <newline> ]
145   // Otherwise:
146   //   ... <terminator> [ <comment> ] [ <newline> ]
147 
148   Token Tok;
149   bool Terminated = false;
150 
151   // First, lex to the current token (which is the last token of the range that
152   // is definitely associated with the decl). Then, we process the first token
153   // separately from the rest based on conditions that hold specifically for
154   // that first token.
155   //
156   // We do not search for a terminator if none is required or we've already
157   // encountered it. Otherwise, if the original `EntityLast` location was in a
158   // macro expansion, we don't have visibility into the text, so we assume we've
159   // already terminated. However, we note this assumption with
160   // `TerminatedByMacro`, because we'll want to handle it somewhat differently
161   // for the terminators semicolon and comma. These terminators can be safely
162   // associated with the entity when they appear after the macro -- extra
163   // semicolons have no effect on the program and a well-formed program won't
164   // have multiple commas in a row, so we're guaranteed that there is only one.
165   //
166   // FIXME: This handling of macros is more conservative than necessary. When
167   // the end of the expansion coincides with the end of the node, we can still
168   // safely analyze the code. But, it is more complicated, because we need to
169   // start by lexing the spelling loc for the first token and then switch to the
170   // expansion loc.
171   bool TerminatedByMacro = false;
172   Lexer->LexFromRawLexer(Tok);
173   if (Terminators.empty() || contains(Terminators, Tok))
174     Terminated = true;
175   else if (EntityLast.isMacroID()) {
176     Terminated = true;
177     TerminatedByMacro = true;
178   }
179 
180   // We save the most recent candidate for the exclusive end location.
181   SourceLocation End = Tok.getEndLoc();
182 
183   while (!Terminated) {
184     // Lex the next token we want to possibly expand the range with.
185     Lexer->LexFromRawLexer(Tok);
186 
187     switch (Tok.getKind()) {
188     case tok::eof:
189     // Unexpected separators.
190     case tok::l_brace:
191     case tok::r_brace:
192     case tok::comma:
193       return End;
194     // Whitespace pseudo-tokens.
195     case tok::unknown:
196       if (startsWithNewline(SM, Tok))
197         // Include at least until the end of the line.
198         End = Tok.getEndLoc();
199       break;
200     default:
201       if (contains(Terminators, Tok))
202         Terminated = true;
203       End = Tok.getEndLoc();
204       break;
205     }
206   }
207 
208   do {
209     // Lex the next token we want to possibly expand the range with.
210     Lexer->LexFromRawLexer(Tok);
211 
212     switch (Tok.getKind()) {
213     case tok::unknown:
214       if (startsWithNewline(SM, Tok))
215         // We're done, but include this newline.
216         return Tok.getEndLoc();
217       break;
218     case tok::comment:
219       // Include any comments we find on the way.
220       End = Tok.getEndLoc();
221       break;
222     case tok::semi:
223     case tok::comma:
224       if (TerminatedByMacro && contains(Terminators, Tok)) {
225         End = Tok.getEndLoc();
226         // We've found a real terminator.
227         TerminatedByMacro = false;
228         break;
229       }
230       // Found an unrelated token; stop and don't include it.
231       return End;
232     default:
233       // Found an unrelated token; stop and don't include it.
234       return End;
235     }
236   } while (true);
237 }
238 
239 // Returns the expected terminator tokens for the given declaration.
240 //
241 // If we do not know the correct terminator token, returns an empty set.
242 //
243 // There are cases where we have more than one possible terminator (for example,
244 // we find either a comma or a semicolon after a VarDecl).
245 static std::set<tok::TokenKind> getTerminators(const Decl &D) {
246   if (llvm::isa<RecordDecl>(D) || llvm::isa<UsingDecl>(D))
247     return {tok::semi};
248 
249   if (llvm::isa<FunctionDecl>(D) || llvm::isa<LinkageSpecDecl>(D))
250     return {tok::r_brace, tok::semi};
251 
252   if (llvm::isa<VarDecl>(D) || llvm::isa<FieldDecl>(D))
253     return {tok::comma, tok::semi};
254 
255   return {};
256 }
257 
258 // Starting from `Loc`, skips whitespace up to, and including, a single
259 // newline. Returns the (exclusive) end of any skipped whitespace (that is, the
260 // location immediately after the whitespace).
261 static SourceLocation skipWhitespaceAndNewline(const SourceManager &SM,
262                                                SourceLocation Loc,
263                                                const LangOptions &LangOpts) {
264   const char *LocChars = SM.getCharacterData(Loc);
265   int i = 0;
266   while (isHorizontalWhitespace(LocChars[i]))
267     ++i;
268   if (isVerticalWhitespace(LocChars[i]))
269     ++i;
270   return Loc.getLocWithOffset(i);
271 }
272 
273 // Is `Loc` separated from any following decl by something meaningful (e.g. an
274 // empty line, a comment), ignoring horizontal whitespace?  Since this is a
275 // heuristic, we return false when in doubt.  `Loc` cannot be the first location
276 // in the file.
277 static bool atOrBeforeSeparation(const SourceManager &SM, SourceLocation Loc,
278                                  const LangOptions &LangOpts) {
279   // If the preceding character is a newline, we'll check for an empty line as a
280   // separator. However, we can't identify an empty line using tokens, so we
281   // analyse the characters. If we try to use tokens, we'll just end up with a
282   // whitespace token, whose characters we'd have to analyse anyhow.
283   bool Invalid = false;
284   const char *LocChars =
285       SM.getCharacterData(Loc.getLocWithOffset(-1), &Invalid);
286   assert(!Invalid &&
287          "Loc must be a valid character and not the first of the source file.");
288   if (isVerticalWhitespace(LocChars[0])) {
289     for (int i = 1; isWhitespace(LocChars[i]); ++i)
290       if (isVerticalWhitespace(LocChars[i]))
291         return true;
292   }
293   // We didn't find an empty line, so lex the next token, skipping past any
294   // whitespace we just scanned.
295   Token Tok;
296   bool Failed = Lexer::getRawToken(Loc, Tok, SM, LangOpts,
297                                    /*IgnoreWhiteSpace=*/true);
298   if (Failed)
299     // Any text that confuses the lexer seems fair to consider a separation.
300     return true;
301 
302   switch (Tok.getKind()) {
303   case tok::comment:
304   case tok::l_brace:
305   case tok::r_brace:
306   case tok::eof:
307     return true;
308   default:
309     return false;
310   }
311 }
312 
313 CharSourceRange tooling::getAssociatedRange(const Decl &Decl,
314                                             ASTContext &Context) {
315   const SourceManager &SM = Context.getSourceManager();
316   const LangOptions &LangOpts = Context.getLangOpts();
317   CharSourceRange Range = CharSourceRange::getTokenRange(Decl.getSourceRange());
318 
319   // First, expand to the start of the template<> declaration if necessary.
320   if (const auto *Record = llvm::dyn_cast<CXXRecordDecl>(&Decl)) {
321     if (const auto *T = Record->getDescribedClassTemplate())
322       if (SM.isBeforeInTranslationUnit(T->getBeginLoc(), Range.getBegin()))
323         Range.setBegin(T->getBeginLoc());
324   } else if (const auto *F = llvm::dyn_cast<FunctionDecl>(&Decl)) {
325     if (const auto *T = F->getDescribedFunctionTemplate())
326       if (SM.isBeforeInTranslationUnit(T->getBeginLoc(), Range.getBegin()))
327         Range.setBegin(T->getBeginLoc());
328   }
329 
330   // Next, expand the end location past trailing comments to include a potential
331   // newline at the end of the decl's line.
332   Range.setEnd(
333       getEntityEndLoc(SM, Decl.getEndLoc(), getTerminators(Decl), LangOpts));
334   Range.setTokenRange(false);
335 
336   // Expand to include preceeding associated comments. We ignore any comments
337   // that are not preceeding the decl, since we've already skipped trailing
338   // comments with getEntityEndLoc.
339   if (const RawComment *Comment =
340           Decl.getASTContext().getRawCommentForDeclNoCache(&Decl))
341     // Only include a preceding comment if:
342     // * it is *not* separate from the declaration (not including any newline
343     //   that immediately follows the comment),
344     // * the decl *is* separate from any following entity (so, there are no
345     //   other entities the comment could refer to), and
346     // * it is not a IfThisThenThat lint check.
347     if (SM.isBeforeInTranslationUnit(Comment->getBeginLoc(),
348                                      Range.getBegin()) &&
349         !atOrBeforeSeparation(
350             SM, skipWhitespaceAndNewline(SM, Comment->getEndLoc(), LangOpts),
351             LangOpts) &&
352         atOrBeforeSeparation(SM, Range.getEnd(), LangOpts)) {
353       const StringRef CommentText = Comment->getRawText(SM);
354       if (!CommentText.contains("LINT.IfChange") &&
355           !CommentText.contains("LINT.ThenChange"))
356         Range.setBegin(Comment->getBeginLoc());
357     }
358   // Add leading attributes.
359   for (auto *Attr : Decl.attrs()) {
360     if (Attr->getLocation().isInvalid() ||
361         !SM.isBeforeInTranslationUnit(Attr->getLocation(), Range.getBegin()))
362       continue;
363     Range.setBegin(Attr->getLocation());
364 
365     // Extend to the left '[[' or '__attribute((' if we saw the attribute,
366     // unless it is not a valid location.
367     bool Invalid;
368     StringRef Source =
369         SM.getBufferData(SM.getFileID(Range.getBegin()), &Invalid);
370     if (Invalid)
371       continue;
372     llvm::StringRef BeforeAttr =
373         Source.substr(0, SM.getFileOffset(Range.getBegin()));
374     llvm::StringRef BeforeAttrStripped = BeforeAttr.rtrim();
375 
376     for (llvm::StringRef Prefix : {"[[", "__attribute__(("}) {
377       // Handle whitespace between attribute prefix and attribute value.
378       if (BeforeAttrStripped.endswith(Prefix)) {
379         // Move start to start position of prefix, which is
380         // length(BeforeAttr) - length(BeforeAttrStripped) + length(Prefix)
381         // positions to the left.
382         Range.setBegin(Range.getBegin().getLocWithOffset(static_cast<int>(
383             -BeforeAttr.size() + BeforeAttrStripped.size() - Prefix.size())));
384         break;
385         // If we didn't see '[[' or '__attribute' it's probably coming from a
386         // macro expansion which is already handled by makeFileCharRange(),
387         // below.
388       }
389     }
390   }
391 
392   // Range.getEnd() is already fully un-expanded by getEntityEndLoc. But,
393   // Range.getBegin() may be inside an expansion.
394   return Lexer::makeFileCharRange(Range, SM, LangOpts);
395 }
396