clang 24.0.0git
DependencyDirectivesScanner.cpp
Go to the documentation of this file.
1//===- DependencyDirectivesScanner.cpp ------------------------------------===//
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/// \file
10/// This is the interface for scanning header and source files to get the
11/// minimum necessary preprocessor directives for evaluating includes. It
12/// reduces the source down to #define, #include, #import, @import, and any
13/// conditional preprocessor logic that contains one of those.
14///
15//===----------------------------------------------------------------------===//
16
21#include "clang/Lex/Lexer.h"
22#include "clang/Lex/Pragma.h"
23#include "llvm/ADT/ScopeExit.h"
24#include "llvm/ADT/SmallString.h"
25#include "llvm/ADT/StringMap.h"
26#include "llvm/ADT/StringSwitch.h"
27#include <optional>
28
29using namespace clang;
31using namespace llvm;
32
33namespace {
34
35struct DirectiveWithTokens {
36 DirectiveKind Kind;
37 unsigned NumTokens;
38
39 DirectiveWithTokens(DirectiveKind Kind, unsigned NumTokens)
40 : Kind(Kind), NumTokens(NumTokens) {}
41};
42
43enum class CXX20ModuleDirectiveKind {
44 None,
45 GlobalModuleFragment,
46 NamedModuleDeclaration,
47 ImportDeclaration,
48};
49
50static CXX20ModuleDirectiveKind scanFirstCXX20ModuleDirective(StringRef Source);
51
52/// Does an efficient "scan" of the sources to detect the presence of
53/// preprocessor (or module import) directives and collects the raw lexed tokens
54/// for those directives so that the \p Lexer can "replay" them when the file is
55/// included.
56///
57/// Note that the behavior of the raw lexer is affected by the language mode,
58/// while at this point we want to do a scan and collect tokens once,
59/// irrespective of the language mode that the file will get included in. To
60/// compensate for that the \p Lexer, while "replaying", will adjust a token
61/// where appropriate, when it could affect the preprocessor's state.
62/// For example in a directive like
63///
64/// \code
65/// #if __has_cpp_attribute(clang::fallthrough)
66/// \endcode
67///
68/// The preprocessor needs to see '::' as 'tok::coloncolon' instead of 2
69/// 'tok::colon'. The \p Lexer will adjust if it sees consecutive 'tok::colon'
70/// while in C++ mode.
71struct Scanner {
72 Scanner(StringRef Input,
73 SmallVectorImpl<dependency_directives_scan::Token> &Tokens,
74 DiagnosticsEngine *Diags, SourceLocation InputSourceLoc)
75 : Input(Input), Tokens(Tokens), Diags(Diags),
76 InputSourceLoc(InputSourceLoc), LangOpts(getLangOptsForDepScanning()),
77 TheLexer(InputSourceLoc, LangOpts, Input.begin(), Input.begin(),
78 Input.end()) {}
79
80 static LangOptions getLangOptsForDepScanning() {
81 LangOptions LangOpts;
82 // Set the lexer to use 'tok::at' for '@', instead of 'tok::unknown'.
83 LangOpts.ObjC = true;
84 LangOpts.LineComment = true;
85 LangOpts.RawStringLiterals = true;
86 LangOpts.AllowLiteralDigitSeparator = true;
87 // FIXME: we do not enable C11 or C++11, so we are missing u/u8/U"".
88 return LangOpts;
89 }
90
91 /// Lex the provided source and emit the directive tokens.
92 ///
93 /// \returns True on error.
94 bool scan(SmallVectorImpl<Directive> &Directives);
95
96 friend CXX20ModuleDirectiveKind
97 scanFirstCXX20ModuleDirective(StringRef Source);
98 friend bool clang::isPreprocessedModuleFile(StringRef Source);
99
100private:
101 /// Lexes next token and advances \p First and the \p Lexer.
102 [[nodiscard]] dependency_directives_scan::Token &
103 lexToken(const char *&First, const char *const End);
104
105 [[nodiscard]] dependency_directives_scan::Token &
106 lexIncludeFilename(const char *&First, const char *const End);
107
108 void skipLine(const char *&First, const char *const End);
109 void skipDirective(StringRef Name, const char *&First, const char *const End);
110
111 /// Returns the spelling of a string literal or identifier after performing
112 /// any processing needed to handle \c clang::Token::NeedsCleaning.
113 StringRef cleanStringIfNeeded(const dependency_directives_scan::Token &Tok);
114
115 /// Lexes next token and if it is identifier returns its string, otherwise
116 /// it skips the current line and returns \p std::nullopt.
117 ///
118 /// In any case (whatever the token kind) \p First and the \p Lexer will
119 /// advance beyond the token.
120 [[nodiscard]] std::optional<StringRef>
121 tryLexIdentifierOrSkipLine(const char *&First, const char *const End);
122
123 /// Used when it is certain that next token is an identifier.
124 [[nodiscard]] StringRef lexIdentifier(const char *&First,
125 const char *const End);
126
127 /// Lexes next token and returns true iff it is an identifier that matches \p
128 /// Id, otherwise it skips the current line and returns false.
129 ///
130 /// In any case (whatever the token kind) \p First and the \p Lexer will
131 /// advance beyond the token.
132 [[nodiscard]] bool isNextIdentifierOrSkipLine(StringRef Id,
133 const char *&First,
134 const char *const End);
135
136 /// Lexes next token and returns true iff it matches the kind \p K.
137 /// Otherwise it skips the current line and returns false.
138 ///
139 /// In any case (whatever the token kind) \p First and the \p Lexer will
140 /// advance beyond the token.
141 [[nodiscard]] bool isNextTokenOrSkipLine(tok::TokenKind K, const char *&First,
142 const char *const End);
143
144 /// Lexes next token and if it is string literal, returns its string.
145 /// Otherwise, it skips the current line and returns \p std::nullopt.
146 ///
147 /// In any case (whatever the token kind) \p First and the \p Lexer will
148 /// advance beyond the token.
149 [[nodiscard]] std::optional<StringRef>
150 tryLexStringLiteralOrSkipLine(const char *&First, const char *const End);
151
152 [[nodiscard]] bool scanImpl(const char *First, const char *const End);
153 [[nodiscard]] bool lexPPLine(const char *&First, const char *const End);
154 [[nodiscard]] bool lexAt(const char *&First, const char *const End);
155 [[nodiscard]] bool lexModule(const char *&First, const char *const End);
156 [[nodiscard]] bool lexPragma(const char *&First, const char *const End);
157 [[nodiscard]] bool lex_Pragma(const char *&First, const char *const End);
158 [[nodiscard]] bool lexEndif(const char *&First, const char *const End);
159 [[nodiscard]] bool lexDefault(DirectiveKind Kind, const char *&First,
160 const char *const End);
161 [[nodiscard]] bool lexModuleDirectiveBody(DirectiveKind Kind,
162 const char *&First,
163 const char *const End);
164 void lexPPDirectiveBody(const char *&First, const char *const End);
165
166 DirectiveWithTokens &pushDirective(DirectiveKind Kind) {
167 Tokens.append(CurDirToks);
168 DirsWithToks.emplace_back(Kind, CurDirToks.size());
169 CurDirToks.clear();
170 return DirsWithToks.back();
171 }
172 void popDirective() {
173 Tokens.pop_back_n(DirsWithToks.pop_back_val().NumTokens);
174 }
175 DirectiveKind topDirective() const {
176 return DirsWithToks.empty() ? pp_none : DirsWithToks.back().Kind;
177 }
178
179 unsigned getOffsetAt(const char *CurPtr) const {
180 return CurPtr - Input.data();
181 }
182
183 /// Reports a diagnostic if the diagnostic engine is provided. Always returns
184 /// true at the end.
185 bool reportError(const char *CurPtr, unsigned Err);
186
187 bool ScanningPreprocessedModuleFile = false;
188 StringMap<char> SplitIds;
189 StringRef Input;
190 SmallVectorImpl<dependency_directives_scan::Token> &Tokens;
191 DiagnosticsEngine *Diags;
192 SourceLocation InputSourceLoc;
193
194 const char *LastTokenPtr = nullptr;
195 /// Keeps track of the tokens for the currently lexed directive. Once a
196 /// directive is fully lexed and "committed" then the tokens get appended to
197 /// \p Tokens and \p CurDirToks is cleared for the next directive.
198 SmallVector<dependency_directives_scan::Token, 32> CurDirToks;
199 /// The directives that were lexed along with the number of tokens that each
200 /// directive contains. The tokens of all the directives are kept in \p Tokens
201 /// vector, in the same order as the directives order in \p DirsWithToks.
202 SmallVector<DirectiveWithTokens, 64> DirsWithToks;
203 LangOptions LangOpts;
204 Lexer TheLexer;
205};
206
207} // end anonymous namespace
208
209bool Scanner::reportError(const char *CurPtr, unsigned Err) {
210 if (!Diags)
211 return true;
212 assert(CurPtr >= Input.data() && "invalid buffer ptr");
213 Diags->Report(InputSourceLoc.getLocWithOffset(getOffsetAt(CurPtr)), Err);
214 return true;
215}
216
217static void skipOverSpaces(const char *&First, const char *const End) {
218 while (First != End && isHorizontalWhitespace(*First))
219 ++First;
220}
221
222// Move back by one character, skipping escaped newlines (backslash + \n)
223static char previousChar(const char *First, const char *&Current) {
224 assert(Current > First);
225 --Current;
226 while (Current > First && isVerticalWhitespace(*Current)) {
227 // Check if the previous character is a backslash
228 if (Current > First && *(Current - 1) == '\\') {
229 // Use Lexer's getEscapedNewLineSize to get the size of the escaped
230 // newline
231 unsigned EscapeSize = Lexer::getEscapedNewLineSize(Current);
232 if (EscapeSize > 0) {
233 // Skip back over the entire escaped newline sequence (backslash +
234 // newline)
235 Current -= (1 + EscapeSize);
236 } else {
237 break;
238 }
239 } else {
240 break;
241 }
242 }
243 return *Current;
244}
245
246[[nodiscard]] static bool isRawStringLiteral(const char *First,
247 const char *Current) {
248 assert(First <= Current);
249
250 // Check if we can even back up.
251 if (*Current != '"' || First == Current)
252 return false;
253
254 // Check for an "R".
255 if (previousChar(First, Current) != 'R')
256 return false;
257 if (First == Current ||
259 return true;
260
261 // Check for a prefix of "u", "U", or "L".
262 if (*Current == 'u' || *Current == 'U' || *Current == 'L')
263 return First == Current ||
265
266 // Check for a prefix of "u8".
267 if (*Current != '8' || First == Current ||
268 previousChar(First, Current) != 'u')
269 return false;
270 return First == Current ||
272}
273
274static void skipRawString(const char *&First, const char *const End) {
275 assert(First[0] == '"');
276
277 const char *Last = ++First;
278 while (Last != End && *Last != '(')
279 ++Last;
280 if (Last == End) {
281 First = Last; // Hit the end... just give up.
282 return;
283 }
284
285 StringRef Terminator(First, Last - First);
286 for (;;) {
287 // Move First to just past the next ")".
288 First = Last;
289 while (First != End && *First != ')')
290 ++First;
291 if (First == End)
292 return;
293 ++First;
294
295 // Look ahead for the terminator sequence.
296 Last = First;
297 while (Last != End && size_t(Last - First) < Terminator.size() &&
298 Terminator[Last - First] == *Last)
299 ++Last;
300
301 // Check if we hit it (or the end of the file).
302 if (Last == End) {
303 First = Last;
304 return;
305 }
306 if (size_t(Last - First) < Terminator.size())
307 continue;
308 if (*Last != '"')
309 continue;
310 First = Last + 1;
311 return;
312 }
313}
314
315// Returns the length of EOL, either 0 (no end-of-line), 1 (\n) or 2 (\r\n)
316static unsigned isEOL(const char *First, const char *const End) {
317 if (First == End)
318 return 0;
319 if (End - First > 1 && isVerticalWhitespace(First[0]) &&
320 isVerticalWhitespace(First[1]) && First[0] != First[1])
321 return 2;
322 return !!isVerticalWhitespace(First[0]);
323}
324
325static void skipString(const char *&First, const char *const End) {
326 assert(*First == '\'' || *First == '"' || *First == '<');
327 const char Terminator = *First == '<' ? '>' : *First;
328 for (++First; First != End && *First != Terminator; ++First) {
329 // String and character literals don't extend past the end of the line.
331 return;
332 if (*First != '\\')
333 continue;
334 // Skip past backslash to the next character. This ensures that the
335 // character right after it is skipped as well, which matters if it's
336 // the terminator.
337 if (++First == End)
338 return;
339 if (!isWhitespace(*First))
340 continue;
341 // Whitespace after the backslash might indicate a line continuation.
342 const char *FirstAfterBackslashPastSpace = First;
343 skipOverSpaces(FirstAfterBackslashPastSpace, End);
344 if (unsigned NLSize = isEOL(FirstAfterBackslashPastSpace, End)) {
345 // Advance the character pointer to the next line for the next
346 // iteration.
347 First = FirstAfterBackslashPastSpace + NLSize - 1;
348 }
349 }
350 if (First != End)
351 ++First; // Finish off the string.
352}
353
354// Returns the length of the skipped newline
355static unsigned skipNewline(const char *&First, const char *End) {
356 if (First == End)
357 return 0;
358 assert(isVerticalWhitespace(*First));
359 unsigned Len = isEOL(First, End);
360 assert(Len && "expected newline");
361 First += Len;
362 return Len;
363}
364
365static void skipToNewlineRaw(const char *&First, const char *const End) {
366 for (;;) {
367 if (First == End)
368 return;
369
370 unsigned Len = isEOL(First, End);
371 if (Len)
372 return;
373
374 char LastNonWhitespace = ' ';
375 do {
377 LastNonWhitespace = *First;
378 if (++First == End)
379 return;
380 Len = isEOL(First, End);
381 } while (!Len);
382
383 if (LastNonWhitespace != '\\')
384 return;
385
386 First += Len;
387 // Keep skipping lines...
388 }
389}
390
391static void skipLineComment(const char *&First, const char *const End) {
392 assert(First[0] == '/' && First[1] == '/');
393 First += 2;
395}
396
397static void skipBlockComment(const char *&First, const char *const End) {
398 assert(First[0] == '/' && First[1] == '*');
399 if (End - First < 4) {
400 First = End;
401 return;
402 }
403 for (First += 3; First != End; ++First)
404 if (First[-1] == '*' && First[0] == '/') {
405 ++First;
406 return;
407 }
408}
409
410/// \returns True if the current single quotation mark character is a C++14
411/// digit separator.
412static bool isQuoteCppDigitSeparator(const char *const Start,
413 const char *const Cur,
414 const char *const End) {
415 assert(*Cur == '\'' && "expected quotation character");
416 // skipLine called in places where we don't expect a valid number
417 // body before `start` on the same line, so always return false at the start.
418 if (Start == Cur)
419 return false;
420 // The previous character must be a valid PP number character.
421 // Make sure that the L, u, U, u8 prefixes don't get marked as a
422 // separator though.
423 char Prev = *(Cur - 1);
424 if (Prev == 'L' || Prev == 'U' || Prev == 'u')
425 return false;
426 if (Prev == '8' && (Cur - 1 != Start) && *(Cur - 2) == 'u')
427 return false;
428 if (!isPreprocessingNumberBody(Prev))
429 return false;
430 // The next character should be a valid identifier body character.
431 return (Cur + 1) < End && isAsciiIdentifierContinue(*(Cur + 1));
432}
433
434void Scanner::skipLine(const char *&First, const char *const End) {
435 for (;;) {
436 assert(First <= End);
437 if (First == End)
438 return;
439
441 skipNewline(First, End);
442 return;
443 }
444 const char *Start = First;
445 // Use `LastNonWhitespace`to track if a line-continuation has ever been seen
446 // before a new-line character:
447 char LastNonWhitespace = ' ';
448 while (First != End && !isVerticalWhitespace(*First)) {
449 // Iterate over strings correctly to avoid comments and newlines.
450 if (*First == '"' ||
451 (*First == '\'' && !isQuoteCppDigitSeparator(Start, First, End))) {
452 LastTokenPtr = First;
453 if (isRawStringLiteral(Start, First))
454 skipRawString(First, End);
455 else
456 skipString(First, End);
457 continue;
458 }
459
460 // Continue on the same line if an EOL is preceded with backslash
461 if (First + 1 < End && *First == '\\') {
462 if (unsigned Len = isEOL(First + 1, End)) {
463 First += 1 + Len;
464 continue;
465 }
466 }
467
468 // Iterate over comments correctly.
469 if (*First != '/' || End - First < 2) {
470 LastTokenPtr = First;
471 if (!isWhitespace(*First))
472 LastNonWhitespace = *First;
473 ++First;
474 continue;
475 }
476
477 if (First[1] == '/') {
478 // "//...".
480 continue;
481 }
482
483 if (First[1] != '*') {
484 LastTokenPtr = First;
485 if (!isWhitespace(*First))
486 LastNonWhitespace = *First;
487 ++First;
488 continue;
489 }
490
491 // "/*...*/".
493 }
494 if (First == End)
495 return;
496
497 // Skip over the newline.
498 skipNewline(First, End);
499
500 if (LastNonWhitespace != '\\')
501 break;
502 }
503}
504
505void Scanner::skipDirective(StringRef Name, const char *&First,
506 const char *const End) {
507 if (llvm::StringSwitch<bool>(Name)
508 .Case("warning", true)
509 .Case("error", true)
510 .Default(false))
511 // Do not process quotes or comments.
513 else
514 skipLine(First, End);
515}
516
517static void skipWhitespace(const char *&First, const char *const End) {
518 for (;;) {
519 assert(First <= End);
520 skipOverSpaces(First, End);
521
522 if (End - First < 2)
523 return;
524
525 if (*First == '\\') {
526 const char *Ptr = First + 1;
527 while (Ptr < End && isHorizontalWhitespace(*Ptr))
528 ++Ptr;
529 if (Ptr != End && isVerticalWhitespace(*Ptr)) {
530 skipNewline(Ptr, End);
531 First = Ptr;
532 continue;
533 }
534 return;
535 }
536
537 // Check for a non-comment character.
538 if (First[0] != '/')
539 return;
540
541 // "// ...".
542 if (First[1] == '/') {
544 return;
545 }
546
547 // Cannot be a comment.
548 if (First[1] != '*')
549 return;
550
551 // "/*...*/".
553 }
554}
555
556bool Scanner::lexModuleDirectiveBody(DirectiveKind Kind, const char *&First,
557 const char *const End) {
558 assert(Kind == DirectiveKind::cxx_export_import_decl ||
559 Kind == DirectiveKind::cxx_export_module_decl ||
560 Kind == DirectiveKind::cxx_import_decl ||
561 Kind == DirectiveKind::cxx_module_decl ||
562 Kind == DirectiveKind::decl_at_import);
563
564 const char *DirectiveLoc = Input.data() + CurDirToks.front().Offset;
565 for (;;) {
566 // Keep a copy of the First char incase it needs to be reset.
567 const char *Previous = First;
568 const dependency_directives_scan::Token &Tok = lexToken(First, End);
569 if ((Tok.is(tok::hash) || Tok.is(tok::at)) &&
571 CurDirToks.pop_back();
572 First = Previous;
573 return false;
574 }
575 if (Tok.isOneOf(tok::eof, tok::eod))
576 return reportError(
577 DirectiveLoc,
578 diag::err_dep_source_scanner_missing_semi_after_at_import);
579 if (Tok.is(tok::semi))
580 break;
581 }
582
583 bool IsCXXModules = Kind == DirectiveKind::cxx_export_import_decl ||
584 Kind == DirectiveKind::cxx_export_module_decl ||
585 Kind == DirectiveKind::cxx_import_decl ||
586 Kind == DirectiveKind::cxx_module_decl;
587 if (IsCXXModules) {
588 lexPPDirectiveBody(First, End);
589 pushDirective(Kind);
590 return false;
591 }
592
593 const auto &Tok = lexToken(First, End);
594 pushDirective(Kind);
595 if (Tok.is(tok::eof) || Tok.is(tok::eod))
596 return false;
597 return reportError(DirectiveLoc,
598 diag::err_dep_source_scanner_unexpected_tokens_at_import);
599}
600
601dependency_directives_scan::Token &Scanner::lexToken(const char *&First,
602 const char *const End) {
603 clang::Token Tok;
604 TheLexer.LexFromRawLexer(Tok);
605 First = Input.data() + TheLexer.getCurrentBufferOffset();
606 assert(First <= End);
607
608 unsigned Offset = TheLexer.getCurrentBufferOffset() - Tok.getLength();
609 CurDirToks.emplace_back(Offset, Tok.getLength(), Tok.getKind(),
610 Tok.getFlags());
611 return CurDirToks.back();
612}
613
614dependency_directives_scan::Token &
615Scanner::lexIncludeFilename(const char *&First, const char *const End) {
616 clang::Token Tok;
617 TheLexer.LexIncludeFilename(Tok);
618 First = Input.data() + TheLexer.getCurrentBufferOffset();
619 assert(First <= End);
620
621 unsigned Offset = TheLexer.getCurrentBufferOffset() - Tok.getLength();
622 CurDirToks.emplace_back(Offset, Tok.getLength(), Tok.getKind(),
623 Tok.getFlags());
624 return CurDirToks.back();
625}
626
627void Scanner::lexPPDirectiveBody(const char *&First, const char *const End) {
628 while (true) {
629 const dependency_directives_scan::Token &Tok = lexToken(First, End);
630 if (Tok.is(tok::eod) || Tok.is(tok::eof))
631 break;
632 }
633}
634
635StringRef
636Scanner::cleanStringIfNeeded(const dependency_directives_scan::Token &Tok) {
637 bool NeedsCleaning = Tok.Flags & clang::Token::NeedsCleaning;
638 if (LLVM_LIKELY(!NeedsCleaning))
639 return Input.slice(Tok.Offset, Tok.getEnd());
640
641 SmallString<64> Spelling;
642 Spelling.resize(Tok.Length);
643
644 // FIXME: C++11 raw string literals need special handling (see getSpellingSlow
645 // in the Lexer). Currently we cannot see them due to our LangOpts.
646
647 unsigned SpellingLength = 0;
648 const char *BufPtr = Input.begin() + Tok.Offset;
649 const char *AfterIdent = Input.begin() + Tok.getEnd();
650 while (BufPtr < AfterIdent) {
651 auto [Char, Size] = Lexer::getCharAndSizeNoWarn(BufPtr, LangOpts);
652 Spelling[SpellingLength++] = Char;
653 BufPtr += Size;
654 }
655
656 return SplitIds.try_emplace(StringRef(Spelling.begin(), SpellingLength), 0)
657 .first->first();
658}
659
660std::optional<StringRef>
661Scanner::tryLexIdentifierOrSkipLine(const char *&First, const char *const End) {
662 const dependency_directives_scan::Token &Tok = lexToken(First, End);
663 if (Tok.isNot(tok::raw_identifier)) {
664 if (!Tok.is(tok::eod))
665 skipLine(First, End);
666 return std::nullopt;
667 }
668
669 return cleanStringIfNeeded(Tok);
670}
671
672StringRef Scanner::lexIdentifier(const char *&First, const char *const End) {
673 std::optional<StringRef> Id = tryLexIdentifierOrSkipLine(First, End);
674 assert(Id && "expected identifier token");
675 return *Id;
676}
677
678bool Scanner::isNextIdentifierOrSkipLine(StringRef Id, const char *&First,
679 const char *const End) {
680 if (std::optional<StringRef> FoundId =
681 tryLexIdentifierOrSkipLine(First, End)) {
682 if (*FoundId == Id)
683 return true;
684 skipLine(First, End);
685 }
686 return false;
687}
688
689bool Scanner::isNextTokenOrSkipLine(tok::TokenKind K, const char *&First,
690 const char *const End) {
691 const dependency_directives_scan::Token &Tok = lexToken(First, End);
692 if (Tok.is(K))
693 return true;
694 skipLine(First, End);
695 return false;
696}
697
698std::optional<StringRef>
699Scanner::tryLexStringLiteralOrSkipLine(const char *&First,
700 const char *const End) {
701 const dependency_directives_scan::Token &Tok = lexToken(First, End);
703 if (!Tok.is(tok::eod))
704 skipLine(First, End);
705 return std::nullopt;
706 }
707
708 return cleanStringIfNeeded(Tok);
709}
710
711bool Scanner::lexAt(const char *&First, const char *const End) {
712 // Handle "@import".
713
714 // Lex '@'.
715 const dependency_directives_scan::Token &AtTok = lexToken(First, End);
716 assert(AtTok.is(tok::at));
717 (void)AtTok;
718
719 if (!isNextIdentifierOrSkipLine("import", First, End))
720 return false;
721 return lexModuleDirectiveBody(decl_at_import, First, End);
722}
723
724bool Scanner::lexModule(const char *&First, const char *const End) {
725 StringRef Id = lexIdentifier(First, End);
726 bool Export = false;
727 if (Id == "export") {
728 Export = true;
729 std::optional<StringRef> NextId = tryLexIdentifierOrSkipLine(First, End);
730 if (!NextId)
731 return false;
732 Id = *NextId;
733 }
734
735 StringRef Module =
736 ScanningPreprocessedModuleFile ? "__preprocessed_module" : "module";
737 StringRef Import =
738 ScanningPreprocessedModuleFile ? "__preprocessed_import" : "import";
739
740 if (Id != Module && Id != Import) {
741 skipLine(First, End);
742 return false;
743 }
744
745 skipWhitespace(First, End);
746
747 // Ignore this as a module directive if the next character can't be part of
748 // an import.
749
750 switch (*First) {
751 case ':': {
752 // `module :` is never the start of a valid module declaration.
753 if (Id == Module) {
754 skipLine(First, End);
755 return false;
756 }
757 // A module partition starts with exactly one ':'. If we have '::', this is
758 // a scope resolution instead and shouldn't be recognized as a directive
759 // per P1857R3.
760 if (First + 1 != End && First[1] == ':') {
761 skipLine(First, End);
762 return false;
763 }
764 // `import:(type)name` is a valid ObjC method decl, so check one more token.
765 (void)lexToken(First, End);
766 if (!tryLexIdentifierOrSkipLine(First, End))
767 return false;
768 break;
769 }
770 case ';': {
771 // Handle the global module fragment `module;`.
772 if (Id == Module && !Export)
773 break;
774 skipLine(First, End);
775 return false;
776 }
777 case '<':
778 case '"':
779 break;
780 default:
782 skipLine(First, End);
783 return false;
784 }
785 }
786
787 TheLexer.seek(getOffsetAt(First), /*IsAtStartOfLine*/ false);
788
790 if (Id == Module)
792 else
794
795 return lexModuleDirectiveBody(Kind, First, End);
796}
797
798bool Scanner::lex_Pragma(const char *&First, const char *const End) {
799 if (!isNextTokenOrSkipLine(tok::l_paren, First, End))
800 return false;
801
802 std::optional<StringRef> Str = tryLexStringLiteralOrSkipLine(First, End);
803
804 if (!Str || !isNextTokenOrSkipLine(tok::r_paren, First, End))
805 return false;
806
807 SmallString<64> Buffer(*Str);
808 prepare_PragmaString(Buffer);
809
810 // Use a new scanner instance since the tokens will be inside the allocated
811 // string. We should already have captured all the relevant tokens in the
812 // current scanner.
813 SmallVector<dependency_directives_scan::Token> DiscardTokens;
814 const char *Begin = Buffer.c_str();
815 Scanner PragmaScanner{StringRef(Begin, Buffer.size()), DiscardTokens, Diags,
816 InputSourceLoc};
817
818 PragmaScanner.TheLexer.setParsingPreprocessorDirective(true);
819 if (PragmaScanner.lexPragma(Begin, Buffer.end()))
820 return true;
821
822 DirectiveKind K = PragmaScanner.topDirective();
823 if (K == pp_none) {
824 skipLine(First, End);
825 return false;
826 }
827
828 assert(Begin == Buffer.end());
829 pushDirective(K);
830 return false;
831}
832
833bool Scanner::lexPragma(const char *&First, const char *const End) {
834 std::optional<StringRef> FoundId = tryLexIdentifierOrSkipLine(First, End);
835 if (!FoundId)
836 return false;
837
838 StringRef Id = *FoundId;
839 auto Kind = llvm::StringSwitch<DirectiveKind>(Id)
840 .Case("once", pp_pragma_once)
841 .Case("push_macro", pp_pragma_push_macro)
842 .Case("pop_macro", pp_pragma_pop_macro)
843 .Case("include_alias", pp_pragma_include_alias)
844 .Default(pp_none);
845 if (Kind != pp_none) {
846 lexPPDirectiveBody(First, End);
847 pushDirective(Kind);
848 return false;
849 }
850
851 if (Id != "clang") {
852 skipLine(First, End);
853 return false;
854 }
855
856 FoundId = tryLexIdentifierOrSkipLine(First, End);
857 if (!FoundId)
858 return false;
859 Id = *FoundId;
860
861 // #pragma clang system_header
862 if (Id == "system_header") {
863 lexPPDirectiveBody(First, End);
864 pushDirective(pp_pragma_system_header);
865 return false;
866 }
867
868 if (Id != "module") {
869 skipLine(First, End);
870 return false;
871 }
872
873 // #pragma clang module.
874 if (!isNextIdentifierOrSkipLine("import", First, End))
875 return false;
876
877 // #pragma clang module import.
878 lexPPDirectiveBody(First, End);
879 pushDirective(pp_pragma_import);
880 return false;
881}
882
883bool Scanner::lexEndif(const char *&First, const char *const End) {
884 // Strip out "#else" if it's empty.
885 if (topDirective() == pp_else)
886 popDirective();
887
888 // If "#ifdef" is empty, strip it and skip the "#endif".
889 //
890 // FIXME: Once/if Clang starts disallowing __has_include in macro expansions,
891 // we can skip empty `#if` and `#elif` blocks as well after scanning for a
892 // literal __has_include in the condition. Even without that rule we could
893 // drop the tokens if we scan for identifiers in the condition and find none.
894 if (topDirective() == pp_ifdef || topDirective() == pp_ifndef) {
895 popDirective();
896 skipLine(First, End);
897 return false;
898 }
899
900 return lexDefault(pp_endif, First, End);
901}
902
903bool Scanner::lexDefault(DirectiveKind Kind, const char *&First,
904 const char *const End) {
905 lexPPDirectiveBody(First, End);
906 pushDirective(Kind);
907 return false;
908}
909
910static bool isStartOfRelevantLine(char First) {
911 switch (First) {
912 case '#':
913 case '@':
914 case 'i':
915 case 'e':
916 case 'm':
917 case '_':
918 return true;
919 }
920 return false;
921}
922
923static inline bool isStartWithPreprocessedModuleDirective(const char *First,
924 const char *End) {
925 assert(First <= End);
926 if (*First == '_') {
927 StringRef Str(First, End - First);
928 return Str.starts_with(
929 tok::getPPKeywordSpelling(tok::pp___preprocessed_module)) ||
930 Str.starts_with(
931 tok::getPPKeywordSpelling(tok::pp___preprocessed_import));
932 }
933 return false;
934}
935
936bool Scanner::lexPPLine(const char *&First, const char *const End) {
937 assert(First != End);
938
939 skipWhitespace(First, End);
940 assert(First <= End);
941 if (First == End)
942 return false;
943
945 skipLine(First, End);
946 assert(First <= End);
947 return false;
948 }
949
950 LastTokenPtr = First;
951
952 TheLexer.seek(getOffsetAt(First), /*IsAtStartOfLine*/ true);
953
954 llvm::scope_exit ScEx1([&]() {
955 /// Clear Scanner's CurDirToks before returning, in case we didn't push a
956 /// new directive.
957 CurDirToks.clear();
958 });
959
960 bool IsPreprocessedModule =
962 if (*First == '_' && !IsPreprocessedModule) {
963 if (isNextIdentifierOrSkipLine("_Pragma", First, End))
964 return lex_Pragma(First, End);
965 return false;
966 }
967
968 // Handle preprocessing directives.
969
970 TheLexer.setParsingPreprocessorDirective(true);
971 llvm::scope_exit ScEx2(
972 [&]() { TheLexer.setParsingPreprocessorDirective(false); });
973
974 if (*First == '@')
975 return lexAt(First, End);
976
977 // Handle module directives for C++20 modules.
978 if (*First == 'i' || *First == 'e' || *First == 'm' || IsPreprocessedModule)
979 return lexModule(First, End);
980
981 // Lex '#'.
982 const dependency_directives_scan::Token &HashTok = lexToken(First, End);
983 if (HashTok.is(tok::hashhash)) {
984 // A \p tok::hashhash at this location is passed by the preprocessor to the
985 // parser to interpret, like any other token. So for dependency scanning
986 // skip it like a normal token not affecting the preprocessor.
987 skipLine(First, End);
988 assert(First <= End);
989 return false;
990 }
991 assert(HashTok.is(tok::hash));
992 (void)HashTok;
993
994 std::optional<StringRef> FoundId = tryLexIdentifierOrSkipLine(First, End);
995 if (!FoundId)
996 return false;
997
998 StringRef Id = *FoundId;
999
1000 if (Id == "pragma")
1001 return lexPragma(First, End);
1002
1003 auto Kind = llvm::StringSwitch<DirectiveKind>(Id)
1004 .Case("include", pp_include)
1005 .Case("__include_macros", pp___include_macros)
1006 .Case("define", pp_define)
1007 .Case("undef", pp_undef)
1008 .Case("import", pp_import)
1009 .Case("include_next", pp_include_next)
1010 .Case("if", pp_if)
1011 .Case("ifdef", pp_ifdef)
1012 .Case("ifndef", pp_ifndef)
1013 .Case("elif", pp_elif)
1014 .Case("elifdef", pp_elifdef)
1015 .Case("elifndef", pp_elifndef)
1016 .Case("else", pp_else)
1017 .Case("endif", pp_endif)
1018 .Default(pp_none);
1019 if (Kind == pp_none) {
1020 skipDirective(Id, First, End);
1021 return false;
1022 }
1023
1024 if (Kind == pp_endif)
1025 return lexEndif(First, End);
1026
1027 switch (Kind) {
1028 case pp_include:
1030 case pp_include_next:
1031 case pp_import:
1032 // Ignore missing filenames in include or import directives.
1033 if (lexIncludeFilename(First, End).is(tok::eod)) {
1034 return false;
1035 }
1036 break;
1037 default:
1038 break;
1039 }
1040
1041 // Everything else.
1042 return lexDefault(Kind, First, End);
1043}
1044
1045static void skipUTF8ByteOrderMark(const char *&First, const char *const End) {
1046 if ((End - First) >= 3 && First[0] == '\xef' && First[1] == '\xbb' &&
1047 First[2] == '\xbf')
1048 First += 3;
1049}
1050
1051bool Scanner::scanImpl(const char *First, const char *const End) {
1053 while (First != End)
1054 if (lexPPLine(First, End))
1055 return true;
1056 return false;
1057}
1058
1059bool Scanner::scan(SmallVectorImpl<Directive> &Directives) {
1060 ScanningPreprocessedModuleFile = clang::isPreprocessedModuleFile(Input);
1061 bool Error = scanImpl(Input.begin(), Input.end());
1062
1063 if (!Error) {
1064 // Add an EOF on success.
1065 if (LastTokenPtr &&
1066 (Tokens.empty() || LastTokenPtr > Input.begin() + Tokens.back().Offset))
1067 pushDirective(tokens_present_before_eof);
1068 pushDirective(pp_eof);
1069 }
1070
1071 ArrayRef<dependency_directives_scan::Token> RemainingTokens = Tokens;
1072 for (const DirectiveWithTokens &DirWithToks : DirsWithToks) {
1073 assert(RemainingTokens.size() >= DirWithToks.NumTokens);
1074 Directives.emplace_back(DirWithToks.Kind,
1075 RemainingTokens.take_front(DirWithToks.NumTokens));
1076 RemainingTokens = RemainingTokens.drop_front(DirWithToks.NumTokens);
1077 }
1078 assert(RemainingTokens.empty());
1079
1080 return Error;
1081}
1082
1086 SourceLocation InputSourceLoc) {
1087 return Scanner(Input, Tokens, Diags, InputSourceLoc).scan(Directives);
1088}
1089
1091 StringRef Source,
1093 llvm::raw_ostream &OS) {
1094 // Add a space separator where it is convenient for testing purposes.
1095 auto needsSpaceSeparator = [](const dependency_directives_scan::Token &Prev,
1097 DirectiveKind Kind, unsigned TokIdx) -> bool {
1098 if (Prev.Kind == Tok.Kind)
1099 return !Tok.isOneOf(tok::l_paren, tok::r_paren, tok::l_square,
1100 tok::r_square);
1101 if (Prev.Kind == tok::raw_identifier &&
1102 Tok.isOneOf(tok::hash, tok::numeric_constant, tok::string_literal,
1103 tok::char_constant, tok::header_name))
1104 return true;
1105 if (Prev.Kind == tok::r_paren &&
1106 Tok.isOneOf(tok::raw_identifier, tok::hash, tok::string_literal,
1107 tok::char_constant, tok::unknown))
1108 return true;
1109 if (Prev.Kind == tok::comma &&
1110 Tok.isOneOf(tok::l_paren, tok::string_literal, tok::less))
1111 return true;
1112 // For object-like macros that begin with an lparen, preserve a space
1113 // between the name and the body to avoid it being converted to a
1114 // function-like macro.
1115 constexpr unsigned FirstBodyIdx = 3; // `#`, `define`, <NAME>, <BODY...>
1116 return Kind == pp_define && TokIdx == FirstBodyIdx &&
1117 Prev.is(tok::raw_identifier) && Tok.is(tok::l_paren) &&
1118 Tok.Offset > Prev.getEnd();
1119 };
1120
1121 for (const dependency_directives_scan::Directive &Directive : Directives) {
1123 // The specific token we use is arbitrary, so we use ; for simplicity. The
1124 // comment is only for readability.
1125 OS << ";/*TokBeforeEOF*/";
1126 const dependency_directives_scan::Token *PrevTok = nullptr;
1127 unsigned TokIdx = 0;
1129 if (PrevTok && needsSpaceSeparator(*PrevTok, Tok, Directive.Kind, TokIdx))
1130 OS << ' ';
1131 PrevTok = &Tok;
1132 ++TokIdx;
1133 OS << Source.slice(Tok.Offset, Tok.getEnd());
1134 }
1135 }
1136}
1137
1139 const char *const End) {
1140 assert(First <= End);
1141 while (First != End) {
1142 if (*First == '#') {
1143 ++First;
1144 skipToNewlineRaw(First, End);
1145 }
1146 skipWhitespace(First, End);
1147 if (const auto Len = isEOL(First, End)) {
1148 First += Len;
1149 continue;
1150 }
1151 break;
1152 }
1153}
1154
1155namespace {
1156
1157static CXX20ModuleDirectiveKind
1158scanFirstCXX20ModuleDirective(StringRef Source) {
1159 const char *First = Source.begin();
1160 const char *const End = Source.end();
1162 if (First == End)
1163 return CXX20ModuleDirectiveKind::None;
1164
1165 // Check if the next token can even be a module directive before creating a
1166 // full lexer.
1167 if (!(*First == 'i' || *First == 'e' || *First == 'm'))
1168 return CXX20ModuleDirectiveKind::None;
1169
1170 llvm::SmallVector<dependency_directives_scan::Token> Tokens;
1171 Scanner S(StringRef(First, End - First), Tokens, nullptr, SourceLocation());
1172 S.TheLexer.setParsingPreprocessorDirective(true);
1173 if (S.lexModule(First, End) || S.DirsWithToks.empty())
1174 return CXX20ModuleDirectiveKind::None;
1175
1176 assert(S.DirsWithToks.size() == 1);
1177 const DirectiveWithTokens &Directive = S.DirsWithToks.front();
1178 switch (Directive.Kind) {
1180 assert(Directive.NumTokens >= 2);
1181 return Tokens[1].is(tok::semi)
1182 ? CXX20ModuleDirectiveKind::GlobalModuleFragment
1183 : CXX20ModuleDirectiveKind::NamedModuleDeclaration;
1185 return CXX20ModuleDirectiveKind::NamedModuleDeclaration;
1188 return CXX20ModuleDirectiveKind::ImportDeclaration;
1189 default:
1190 llvm_unreachable("unexpected C++20 module directive kind");
1191 }
1192}
1193
1194} // namespace
1195
1197 return scanFirstCXX20ModuleDirective(Source) !=
1198 CXX20ModuleDirectiveKind::None;
1199}
1200
1202 switch (scanFirstCXX20ModuleDirective(Source)) {
1203 case CXX20ModuleDirectiveKind::GlobalModuleFragment:
1205 case CXX20ModuleDirectiveKind::NamedModuleDeclaration:
1207 case CXX20ModuleDirectiveKind::None:
1208 case CXX20ModuleDirectiveKind::ImportDeclaration:
1210 }
1211 llvm_unreachable("unexpected C++20 module directive kind");
1212}
1213
1214bool clang::isPreprocessedModuleFile(StringRef Source) {
1215 const char *First = Source.begin();
1216 const char *const End = Source.end();
1217
1219 if (First == End)
1220 return false;
1221
1223 Scanner S(StringRef(First, End - First), Tokens, nullptr, SourceLocation());
1224 while (First != End) {
1225 if (*First == '#') {
1226 ++First;
1227 skipToNewlineRaw(First, End);
1228 } else if (*First == 'e') {
1229 S.TheLexer.seek(S.getOffsetAt(First), /*IsAtStartOfLine=*/true);
1230 StringRef Id = S.lexIdentifier(First, End);
1231 if (Id == "export") {
1232 std::optional<StringRef> NextId =
1233 S.tryLexIdentifierOrSkipLine(First, End);
1234 if (!NextId)
1235 return false;
1236 Id = *NextId;
1237 }
1238 if (Id == "__preprocessed_module" || Id == "__preprocessed_import")
1239 return true;
1240 skipToNewlineRaw(First, End);
1242 return true;
1243 else
1244 skipToNewlineRaw(First, End);
1245
1246 skipWhitespace(First, End);
1247 if (const auto Len = isEOL(First, End)) {
1248 First += Len;
1249 continue;
1250 }
1251 break;
1252 }
1253 return false;
1254}
Defines the Diagnostic-related interfaces.
static void skipBlockComment(const char *&First, const char *const End)
static void skipRawString(const char *&First, const char *const End)
static void skipString(const char *&First, const char *const End)
static bool isStartOfRelevantLine(char First)
static bool isStartWithPreprocessedModuleDirective(const char *First, const char *End)
static bool isRawStringLiteral(const char *First, const char *Current)
static void skipUntilMaybeCXX20ModuleDirective(const char *&First, const char *const End)
static void skipOverSpaces(const char *&First, const char *const End)
static unsigned isEOL(const char *First, const char *const End)
static char previousChar(const char *First, const char *&Current)
static void skipToNewlineRaw(const char *&First, const char *const End)
static unsigned skipNewline(const char *&First, const char *End)
static void skipUTF8ByteOrderMark(const char *&First, const char *const End)
static void skipLineComment(const char *&First, const char *const End)
static bool isQuoteCppDigitSeparator(const char *const Start, const char *const Cur, const char *const End)
This is the interface for scanning header and source files to get the minimum necessary preprocessor ...
bool is(tok::TokenKind Kind) const
Token Tok
The Token.
FormatToken * Previous
The previous token in the unwrapped line.
static unsigned skipWhitespace(unsigned Idx, StringRef Str, unsigned Length)
Skip over whitespace in the string, starting at the given index.
VerifyDiagnosticConsumer::Directive Directive
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:241
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
bool LexFromRawLexer(Token &Result)
LexFromRawLexer - Lex a token from a designated raw lexer (one with no associated preprocessor object...
Definition Lexer.h:236
static unsigned getEscapedNewLineSize(const char *P)
getEscapedNewLineSize - Return the size of the specified escaped newline, or 0 if it is not an escape...
Definition Lexer.cpp:1336
void seek(unsigned Offset, bool IsAtStartOfLine)
Set the lexer's buffer pointer to Offset.
Definition Lexer.cpp:288
unsigned getCurrentBufferOffset()
Returns the current lexing offset.
Definition Lexer.h:313
static SizedChar getCharAndSizeNoWarn(const char *Ptr, const LangOptions &LangOpts)
getCharAndSizeNoWarn - Like the getCharAndSize method, but does not ever emit a warning.
Definition Lexer.h:614
void setParsingPreprocessorDirective(bool f)
Inform the lexer whether or not we are currently lexing a preprocessor directive.
void LexIncludeFilename(Token &FilenameTok)
Lex a token, producing a header-name token if possible.
Encodes a location in the source.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
@ StartOfLine
Definition Token.h:75
@ NeedsCleaning
Definition Token.h:80
DirectiveKind
Represents the kind of preprocessor directive or a module declaration that is tracked by the scanner ...
@ tokens_present_before_eof
Indicates that there are tokens present between the last scanned directive and eof.
bool isStringLiteral(TokenKind K)
Return true if this is a C or C++ string-literal (or C++11 user-defined-string-literal) token.
Definition TokenKinds.h:101
const char * getPPKeywordSpelling(PPKeywordKind Kind) LLVM_READNONE
Returns the spelling of preprocessor keywords, such as "else".
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition TokenKinds.h:33
Top level wrappers for InstallAPI frontend operations.
LLVM_READONLY bool isVerticalWhitespace(unsigned char c)
Returns true if this character is vertical ASCII whitespace: '\n', '\r'.
Definition CharInfo.h:99
LLVM_READONLY bool isAsciiIdentifierContinue(unsigned char c)
Definition CharInfo.h:61
void printDependencyDirectivesAsSource(StringRef Source, ArrayRef< dependency_directives_scan::Directive > Directives, llvm::raw_ostream &OS)
Print the previously scanned dependency directives as minimized source text.
bool scanInputForCXX20ModulesUsage(StringRef Source)
Scan an input source buffer for C++20 named module usage.
bool isPreprocessedModuleFile(StringRef Source)
Scan an input source buffer, and check whether the input source is a preprocessed output.
LLVM_READONLY bool isHorizontalWhitespace(unsigned char c)
Returns true if this character is horizontal ASCII whitespace: ' ', '\t', '\f', '\v'.
Definition CharInfo.h:91
bool scanSourceForDependencyDirectives(StringRef Input, SmallVectorImpl< dependency_directives_scan::Token > &Tokens, SmallVectorImpl< dependency_directives_scan::Directive > &Directives, DiagnosticsEngine *Diags=nullptr, SourceLocation InputSourceLoc=SourceLocation())
Scan the input for the preprocessor directives that might have an effect on the dependencies for a co...
@ Module
Module linkage, which indicates that the entity can be referred to from other translation units withi...
Definition Linkage.h:54
@ Default
Set to the current date and time.
ModuleUnitKind
Describes how a source input starts a C++20 module unit.
LLVM_READONLY bool isWhitespace(unsigned char c)
Return true if this character is horizontal or vertical ASCII whitespace: ' ', '\t',...
Definition CharInfo.h:108
LLVM_READONLY bool isPreprocessingNumberBody(unsigned char c)
Return true if this is the body character of a C preprocessing number, which is [a-zA-Z0-9_.
Definition CharInfo.h:168
void prepare_PragmaString(SmallVectorImpl< char > &StrVal)
Destringize a _Pragma("") string according to C11 6.10.9.1: "The string literal is destringized by de...
Definition Pragma.cpp:303
ModuleUnitKind scanInputForCXX20ModuleUnit(StringRef Source)
Scan an input source buffer to determine whether it starts a C++20 module unit, and whether that modu...
Diagnostic wrappers for TextAPI types for error reporting.
Definition Dominators.h:30
Represents a directive that's lexed as part of the dependency directives scanning.
Token lexed as part of dependency directive scanning.
unsigned Offset
Offset into the original source input.