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