xref: /freebsd-src/contrib/llvm-project/clang/lib/Lex/DependencyDirectivesScanner.cpp (revision 81ad626541db97eb356e2c1d4a20eb2a26a766ab)
1*81ad6265SDimitry Andric //===- DependencyDirectivesScanner.cpp ------------------------------------===//
2*81ad6265SDimitry Andric //
3*81ad6265SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*81ad6265SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5*81ad6265SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6*81ad6265SDimitry Andric //
7*81ad6265SDimitry Andric //===----------------------------------------------------------------------===//
8*81ad6265SDimitry Andric ///
9*81ad6265SDimitry Andric /// \file
10*81ad6265SDimitry Andric /// This is the interface for scanning header and source files to get the
11*81ad6265SDimitry Andric /// minimum necessary preprocessor directives for evaluating includes. It
12*81ad6265SDimitry Andric /// reduces the source down to #define, #include, #import, @import, and any
13*81ad6265SDimitry Andric /// conditional preprocessor logic that contains one of those.
14*81ad6265SDimitry Andric ///
15*81ad6265SDimitry Andric //===----------------------------------------------------------------------===//
16*81ad6265SDimitry Andric 
17*81ad6265SDimitry Andric #include "clang/Lex/DependencyDirectivesScanner.h"
18*81ad6265SDimitry Andric #include "clang/Basic/CharInfo.h"
19*81ad6265SDimitry Andric #include "clang/Basic/Diagnostic.h"
20*81ad6265SDimitry Andric #include "clang/Lex/LexDiagnostic.h"
21*81ad6265SDimitry Andric #include "clang/Lex/Lexer.h"
22*81ad6265SDimitry Andric #include "llvm/ADT/ScopeExit.h"
23*81ad6265SDimitry Andric #include "llvm/ADT/SmallString.h"
24*81ad6265SDimitry Andric #include "llvm/ADT/StringMap.h"
25*81ad6265SDimitry Andric #include "llvm/ADT/StringSwitch.h"
26*81ad6265SDimitry Andric 
27*81ad6265SDimitry Andric using namespace clang;
28*81ad6265SDimitry Andric using namespace clang::dependency_directives_scan;
29*81ad6265SDimitry Andric using namespace llvm;
30*81ad6265SDimitry Andric 
31*81ad6265SDimitry Andric namespace {
32*81ad6265SDimitry Andric 
33*81ad6265SDimitry Andric struct DirectiveWithTokens {
34*81ad6265SDimitry Andric   DirectiveKind Kind;
35*81ad6265SDimitry Andric   unsigned NumTokens;
36*81ad6265SDimitry Andric 
37*81ad6265SDimitry Andric   DirectiveWithTokens(DirectiveKind Kind, unsigned NumTokens)
38*81ad6265SDimitry Andric       : Kind(Kind), NumTokens(NumTokens) {}
39*81ad6265SDimitry Andric };
40*81ad6265SDimitry Andric 
41*81ad6265SDimitry Andric /// Does an efficient "scan" of the sources to detect the presence of
42*81ad6265SDimitry Andric /// preprocessor (or module import) directives and collects the raw lexed tokens
43*81ad6265SDimitry Andric /// for those directives so that the \p Lexer can "replay" them when the file is
44*81ad6265SDimitry Andric /// included.
45*81ad6265SDimitry Andric ///
46*81ad6265SDimitry Andric /// Note that the behavior of the raw lexer is affected by the language mode,
47*81ad6265SDimitry Andric /// while at this point we want to do a scan and collect tokens once,
48*81ad6265SDimitry Andric /// irrespective of the language mode that the file will get included in. To
49*81ad6265SDimitry Andric /// compensate for that the \p Lexer, while "replaying", will adjust a token
50*81ad6265SDimitry Andric /// where appropriate, when it could affect the preprocessor's state.
51*81ad6265SDimitry Andric /// For example in a directive like
52*81ad6265SDimitry Andric ///
53*81ad6265SDimitry Andric /// \code
54*81ad6265SDimitry Andric ///   #if __has_cpp_attribute(clang::fallthrough)
55*81ad6265SDimitry Andric /// \endcode
56*81ad6265SDimitry Andric ///
57*81ad6265SDimitry Andric /// The preprocessor needs to see '::' as 'tok::coloncolon' instead of 2
58*81ad6265SDimitry Andric /// 'tok::colon'. The \p Lexer will adjust if it sees consecutive 'tok::colon'
59*81ad6265SDimitry Andric /// while in C++ mode.
60*81ad6265SDimitry Andric struct Scanner {
61*81ad6265SDimitry Andric   Scanner(StringRef Input,
62*81ad6265SDimitry Andric           SmallVectorImpl<dependency_directives_scan::Token> &Tokens,
63*81ad6265SDimitry Andric           DiagnosticsEngine *Diags, SourceLocation InputSourceLoc)
64*81ad6265SDimitry Andric       : Input(Input), Tokens(Tokens), Diags(Diags),
65*81ad6265SDimitry Andric         InputSourceLoc(InputSourceLoc), LangOpts(getLangOptsForDepScanning()),
66*81ad6265SDimitry Andric         TheLexer(InputSourceLoc, LangOpts, Input.begin(), Input.begin(),
67*81ad6265SDimitry Andric                  Input.end()) {}
68*81ad6265SDimitry Andric 
69*81ad6265SDimitry Andric   static LangOptions getLangOptsForDepScanning() {
70*81ad6265SDimitry Andric     LangOptions LangOpts;
71*81ad6265SDimitry Andric     // Set the lexer to use 'tok::at' for '@', instead of 'tok::unknown'.
72*81ad6265SDimitry Andric     LangOpts.ObjC = true;
73*81ad6265SDimitry Andric     LangOpts.LineComment = true;
74*81ad6265SDimitry Andric     return LangOpts;
75*81ad6265SDimitry Andric   }
76*81ad6265SDimitry Andric 
77*81ad6265SDimitry Andric   /// Lex the provided source and emit the directive tokens.
78*81ad6265SDimitry Andric   ///
79*81ad6265SDimitry Andric   /// \returns True on error.
80*81ad6265SDimitry Andric   bool scan(SmallVectorImpl<Directive> &Directives);
81*81ad6265SDimitry Andric 
82*81ad6265SDimitry Andric private:
83*81ad6265SDimitry Andric   /// Lexes next token and advances \p First and the \p Lexer.
84*81ad6265SDimitry Andric   LLVM_NODISCARD dependency_directives_scan::Token &
85*81ad6265SDimitry Andric   lexToken(const char *&First, const char *const End);
86*81ad6265SDimitry Andric 
87*81ad6265SDimitry Andric   dependency_directives_scan::Token &lexIncludeFilename(const char *&First,
88*81ad6265SDimitry Andric                                                         const char *const End);
89*81ad6265SDimitry Andric 
90*81ad6265SDimitry Andric   /// Lexes next token and if it is identifier returns its string, otherwise
91*81ad6265SDimitry Andric   /// it skips the current line and returns \p None.
92*81ad6265SDimitry Andric   ///
93*81ad6265SDimitry Andric   /// In any case (whatever the token kind) \p First and the \p Lexer will
94*81ad6265SDimitry Andric   /// advance beyond the token.
95*81ad6265SDimitry Andric   LLVM_NODISCARD Optional<StringRef>
96*81ad6265SDimitry Andric   tryLexIdentifierOrSkipLine(const char *&First, const char *const End);
97*81ad6265SDimitry Andric 
98*81ad6265SDimitry Andric   /// Used when it is certain that next token is an identifier.
99*81ad6265SDimitry Andric   LLVM_NODISCARD StringRef lexIdentifier(const char *&First,
100*81ad6265SDimitry Andric                                          const char *const End);
101*81ad6265SDimitry Andric 
102*81ad6265SDimitry Andric   /// Lexes next token and returns true iff it is an identifier that matches \p
103*81ad6265SDimitry Andric   /// Id, otherwise it skips the current line and returns false.
104*81ad6265SDimitry Andric   ///
105*81ad6265SDimitry Andric   /// In any case (whatever the token kind) \p First and the \p Lexer will
106*81ad6265SDimitry Andric   /// advance beyond the token.
107*81ad6265SDimitry Andric   LLVM_NODISCARD bool isNextIdentifierOrSkipLine(StringRef Id,
108*81ad6265SDimitry Andric                                                  const char *&First,
109*81ad6265SDimitry Andric                                                  const char *const End);
110*81ad6265SDimitry Andric 
111*81ad6265SDimitry Andric   LLVM_NODISCARD bool scanImpl(const char *First, const char *const End);
112*81ad6265SDimitry Andric   LLVM_NODISCARD bool lexPPLine(const char *&First, const char *const End);
113*81ad6265SDimitry Andric   LLVM_NODISCARD bool lexAt(const char *&First, const char *const End);
114*81ad6265SDimitry Andric   LLVM_NODISCARD bool lexModule(const char *&First, const char *const End);
115*81ad6265SDimitry Andric   LLVM_NODISCARD bool lexDefine(const char *HashLoc, const char *&First,
116*81ad6265SDimitry Andric                                 const char *const End);
117*81ad6265SDimitry Andric   LLVM_NODISCARD bool lexPragma(const char *&First, const char *const End);
118*81ad6265SDimitry Andric   LLVM_NODISCARD bool lexEndif(const char *&First, const char *const End);
119*81ad6265SDimitry Andric   LLVM_NODISCARD bool lexDefault(DirectiveKind Kind, const char *&First,
120*81ad6265SDimitry Andric                                  const char *const End);
121*81ad6265SDimitry Andric   LLVM_NODISCARD bool lexModuleDirectiveBody(DirectiveKind Kind,
122*81ad6265SDimitry Andric                                              const char *&First,
123*81ad6265SDimitry Andric                                              const char *const End);
124*81ad6265SDimitry Andric   void lexPPDirectiveBody(const char *&First, const char *const End);
125*81ad6265SDimitry Andric 
126*81ad6265SDimitry Andric   DirectiveWithTokens &pushDirective(DirectiveKind Kind) {
127*81ad6265SDimitry Andric     Tokens.append(CurDirToks);
128*81ad6265SDimitry Andric     DirsWithToks.emplace_back(Kind, CurDirToks.size());
129*81ad6265SDimitry Andric     CurDirToks.clear();
130*81ad6265SDimitry Andric     return DirsWithToks.back();
131*81ad6265SDimitry Andric   }
132*81ad6265SDimitry Andric   void popDirective() {
133*81ad6265SDimitry Andric     Tokens.pop_back_n(DirsWithToks.pop_back_val().NumTokens);
134*81ad6265SDimitry Andric   }
135*81ad6265SDimitry Andric   DirectiveKind topDirective() const {
136*81ad6265SDimitry Andric     return DirsWithToks.empty() ? pp_none : DirsWithToks.back().Kind;
137*81ad6265SDimitry Andric   }
138*81ad6265SDimitry Andric 
139*81ad6265SDimitry Andric   unsigned getOffsetAt(const char *CurPtr) const {
140*81ad6265SDimitry Andric     return CurPtr - Input.data();
141*81ad6265SDimitry Andric   }
142*81ad6265SDimitry Andric 
143*81ad6265SDimitry Andric   /// Reports a diagnostic if the diagnostic engine is provided. Always returns
144*81ad6265SDimitry Andric   /// true at the end.
145*81ad6265SDimitry Andric   bool reportError(const char *CurPtr, unsigned Err);
146*81ad6265SDimitry Andric 
147*81ad6265SDimitry Andric   StringMap<char> SplitIds;
148*81ad6265SDimitry Andric   StringRef Input;
149*81ad6265SDimitry Andric   SmallVectorImpl<dependency_directives_scan::Token> &Tokens;
150*81ad6265SDimitry Andric   DiagnosticsEngine *Diags;
151*81ad6265SDimitry Andric   SourceLocation InputSourceLoc;
152*81ad6265SDimitry Andric 
153*81ad6265SDimitry Andric   /// Keeps track of the tokens for the currently lexed directive. Once a
154*81ad6265SDimitry Andric   /// directive is fully lexed and "committed" then the tokens get appended to
155*81ad6265SDimitry Andric   /// \p Tokens and \p CurDirToks is cleared for the next directive.
156*81ad6265SDimitry Andric   SmallVector<dependency_directives_scan::Token, 32> CurDirToks;
157*81ad6265SDimitry Andric   /// The directives that were lexed along with the number of tokens that each
158*81ad6265SDimitry Andric   /// directive contains. The tokens of all the directives are kept in \p Tokens
159*81ad6265SDimitry Andric   /// vector, in the same order as the directives order in \p DirsWithToks.
160*81ad6265SDimitry Andric   SmallVector<DirectiveWithTokens, 64> DirsWithToks;
161*81ad6265SDimitry Andric   LangOptions LangOpts;
162*81ad6265SDimitry Andric   Lexer TheLexer;
163*81ad6265SDimitry Andric };
164*81ad6265SDimitry Andric 
165*81ad6265SDimitry Andric } // end anonymous namespace
166*81ad6265SDimitry Andric 
167*81ad6265SDimitry Andric bool Scanner::reportError(const char *CurPtr, unsigned Err) {
168*81ad6265SDimitry Andric   if (!Diags)
169*81ad6265SDimitry Andric     return true;
170*81ad6265SDimitry Andric   assert(CurPtr >= Input.data() && "invalid buffer ptr");
171*81ad6265SDimitry Andric   Diags->Report(InputSourceLoc.getLocWithOffset(getOffsetAt(CurPtr)), Err);
172*81ad6265SDimitry Andric   return true;
173*81ad6265SDimitry Andric }
174*81ad6265SDimitry Andric 
175*81ad6265SDimitry Andric static void skipOverSpaces(const char *&First, const char *const End) {
176*81ad6265SDimitry Andric   while (First != End && isHorizontalWhitespace(*First))
177*81ad6265SDimitry Andric     ++First;
178*81ad6265SDimitry Andric }
179*81ad6265SDimitry Andric 
180*81ad6265SDimitry Andric LLVM_NODISCARD static bool isRawStringLiteral(const char *First,
181*81ad6265SDimitry Andric                                               const char *Current) {
182*81ad6265SDimitry Andric   assert(First <= Current);
183*81ad6265SDimitry Andric 
184*81ad6265SDimitry Andric   // Check if we can even back up.
185*81ad6265SDimitry Andric   if (*Current != '"' || First == Current)
186*81ad6265SDimitry Andric     return false;
187*81ad6265SDimitry Andric 
188*81ad6265SDimitry Andric   // Check for an "R".
189*81ad6265SDimitry Andric   --Current;
190*81ad6265SDimitry Andric   if (*Current != 'R')
191*81ad6265SDimitry Andric     return false;
192*81ad6265SDimitry Andric   if (First == Current || !isAsciiIdentifierContinue(*--Current))
193*81ad6265SDimitry Andric     return true;
194*81ad6265SDimitry Andric 
195*81ad6265SDimitry Andric   // Check for a prefix of "u", "U", or "L".
196*81ad6265SDimitry Andric   if (*Current == 'u' || *Current == 'U' || *Current == 'L')
197*81ad6265SDimitry Andric     return First == Current || !isAsciiIdentifierContinue(*--Current);
198*81ad6265SDimitry Andric 
199*81ad6265SDimitry Andric   // Check for a prefix of "u8".
200*81ad6265SDimitry Andric   if (*Current != '8' || First == Current || *Current-- != 'u')
201*81ad6265SDimitry Andric     return false;
202*81ad6265SDimitry Andric   return First == Current || !isAsciiIdentifierContinue(*--Current);
203*81ad6265SDimitry Andric }
204*81ad6265SDimitry Andric 
205*81ad6265SDimitry Andric static void skipRawString(const char *&First, const char *const End) {
206*81ad6265SDimitry Andric   assert(First[0] == '"');
207*81ad6265SDimitry Andric   assert(First[-1] == 'R');
208*81ad6265SDimitry Andric 
209*81ad6265SDimitry Andric   const char *Last = ++First;
210*81ad6265SDimitry Andric   while (Last != End && *Last != '(')
211*81ad6265SDimitry Andric     ++Last;
212*81ad6265SDimitry Andric   if (Last == End) {
213*81ad6265SDimitry Andric     First = Last; // Hit the end... just give up.
214*81ad6265SDimitry Andric     return;
215*81ad6265SDimitry Andric   }
216*81ad6265SDimitry Andric 
217*81ad6265SDimitry Andric   StringRef Terminator(First, Last - First);
218*81ad6265SDimitry Andric   for (;;) {
219*81ad6265SDimitry Andric     // Move First to just past the next ")".
220*81ad6265SDimitry Andric     First = Last;
221*81ad6265SDimitry Andric     while (First != End && *First != ')')
222*81ad6265SDimitry Andric       ++First;
223*81ad6265SDimitry Andric     if (First == End)
224*81ad6265SDimitry Andric       return;
225*81ad6265SDimitry Andric     ++First;
226*81ad6265SDimitry Andric 
227*81ad6265SDimitry Andric     // Look ahead for the terminator sequence.
228*81ad6265SDimitry Andric     Last = First;
229*81ad6265SDimitry Andric     while (Last != End && size_t(Last - First) < Terminator.size() &&
230*81ad6265SDimitry Andric            Terminator[Last - First] == *Last)
231*81ad6265SDimitry Andric       ++Last;
232*81ad6265SDimitry Andric 
233*81ad6265SDimitry Andric     // Check if we hit it (or the end of the file).
234*81ad6265SDimitry Andric     if (Last == End) {
235*81ad6265SDimitry Andric       First = Last;
236*81ad6265SDimitry Andric       return;
237*81ad6265SDimitry Andric     }
238*81ad6265SDimitry Andric     if (size_t(Last - First) < Terminator.size())
239*81ad6265SDimitry Andric       continue;
240*81ad6265SDimitry Andric     if (*Last != '"')
241*81ad6265SDimitry Andric       continue;
242*81ad6265SDimitry Andric     First = Last + 1;
243*81ad6265SDimitry Andric     return;
244*81ad6265SDimitry Andric   }
245*81ad6265SDimitry Andric }
246*81ad6265SDimitry Andric 
247*81ad6265SDimitry Andric // Returns the length of EOL, either 0 (no end-of-line), 1 (\n) or 2 (\r\n)
248*81ad6265SDimitry Andric static unsigned isEOL(const char *First, const char *const End) {
249*81ad6265SDimitry Andric   if (First == End)
250*81ad6265SDimitry Andric     return 0;
251*81ad6265SDimitry Andric   if (End - First > 1 && isVerticalWhitespace(First[0]) &&
252*81ad6265SDimitry Andric       isVerticalWhitespace(First[1]) && First[0] != First[1])
253*81ad6265SDimitry Andric     return 2;
254*81ad6265SDimitry Andric   return !!isVerticalWhitespace(First[0]);
255*81ad6265SDimitry Andric }
256*81ad6265SDimitry Andric 
257*81ad6265SDimitry Andric static void skipString(const char *&First, const char *const End) {
258*81ad6265SDimitry Andric   assert(*First == '\'' || *First == '"' || *First == '<');
259*81ad6265SDimitry Andric   const char Terminator = *First == '<' ? '>' : *First;
260*81ad6265SDimitry Andric   for (++First; First != End && *First != Terminator; ++First) {
261*81ad6265SDimitry Andric     // String and character literals don't extend past the end of the line.
262*81ad6265SDimitry Andric     if (isVerticalWhitespace(*First))
263*81ad6265SDimitry Andric       return;
264*81ad6265SDimitry Andric     if (*First != '\\')
265*81ad6265SDimitry Andric       continue;
266*81ad6265SDimitry Andric     // Skip past backslash to the next character. This ensures that the
267*81ad6265SDimitry Andric     // character right after it is skipped as well, which matters if it's
268*81ad6265SDimitry Andric     // the terminator.
269*81ad6265SDimitry Andric     if (++First == End)
270*81ad6265SDimitry Andric       return;
271*81ad6265SDimitry Andric     if (!isWhitespace(*First))
272*81ad6265SDimitry Andric       continue;
273*81ad6265SDimitry Andric     // Whitespace after the backslash might indicate a line continuation.
274*81ad6265SDimitry Andric     const char *FirstAfterBackslashPastSpace = First;
275*81ad6265SDimitry Andric     skipOverSpaces(FirstAfterBackslashPastSpace, End);
276*81ad6265SDimitry Andric     if (unsigned NLSize = isEOL(FirstAfterBackslashPastSpace, End)) {
277*81ad6265SDimitry Andric       // Advance the character pointer to the next line for the next
278*81ad6265SDimitry Andric       // iteration.
279*81ad6265SDimitry Andric       First = FirstAfterBackslashPastSpace + NLSize - 1;
280*81ad6265SDimitry Andric     }
281*81ad6265SDimitry Andric   }
282*81ad6265SDimitry Andric   if (First != End)
283*81ad6265SDimitry Andric     ++First; // Finish off the string.
284*81ad6265SDimitry Andric }
285*81ad6265SDimitry Andric 
286*81ad6265SDimitry Andric // Returns the length of the skipped newline
287*81ad6265SDimitry Andric static unsigned skipNewline(const char *&First, const char *End) {
288*81ad6265SDimitry Andric   if (First == End)
289*81ad6265SDimitry Andric     return 0;
290*81ad6265SDimitry Andric   assert(isVerticalWhitespace(*First));
291*81ad6265SDimitry Andric   unsigned Len = isEOL(First, End);
292*81ad6265SDimitry Andric   assert(Len && "expected newline");
293*81ad6265SDimitry Andric   First += Len;
294*81ad6265SDimitry Andric   return Len;
295*81ad6265SDimitry Andric }
296*81ad6265SDimitry Andric 
297*81ad6265SDimitry Andric static bool wasLineContinuation(const char *First, unsigned EOLLen) {
298*81ad6265SDimitry Andric   return *(First - (int)EOLLen - 1) == '\\';
299*81ad6265SDimitry Andric }
300*81ad6265SDimitry Andric 
301*81ad6265SDimitry Andric static void skipToNewlineRaw(const char *&First, const char *const End) {
302*81ad6265SDimitry Andric   for (;;) {
303*81ad6265SDimitry Andric     if (First == End)
304*81ad6265SDimitry Andric       return;
305*81ad6265SDimitry Andric 
306*81ad6265SDimitry Andric     unsigned Len = isEOL(First, End);
307*81ad6265SDimitry Andric     if (Len)
308*81ad6265SDimitry Andric       return;
309*81ad6265SDimitry Andric 
310*81ad6265SDimitry Andric     do {
311*81ad6265SDimitry Andric       if (++First == End)
312*81ad6265SDimitry Andric         return;
313*81ad6265SDimitry Andric       Len = isEOL(First, End);
314*81ad6265SDimitry Andric     } while (!Len);
315*81ad6265SDimitry Andric 
316*81ad6265SDimitry Andric     if (First[-1] != '\\')
317*81ad6265SDimitry Andric       return;
318*81ad6265SDimitry Andric 
319*81ad6265SDimitry Andric     First += Len;
320*81ad6265SDimitry Andric     // Keep skipping lines...
321*81ad6265SDimitry Andric   }
322*81ad6265SDimitry Andric }
323*81ad6265SDimitry Andric 
324*81ad6265SDimitry Andric static void skipLineComment(const char *&First, const char *const End) {
325*81ad6265SDimitry Andric   assert(First[0] == '/' && First[1] == '/');
326*81ad6265SDimitry Andric   First += 2;
327*81ad6265SDimitry Andric   skipToNewlineRaw(First, End);
328*81ad6265SDimitry Andric }
329*81ad6265SDimitry Andric 
330*81ad6265SDimitry Andric static void skipBlockComment(const char *&First, const char *const End) {
331*81ad6265SDimitry Andric   assert(First[0] == '/' && First[1] == '*');
332*81ad6265SDimitry Andric   if (End - First < 4) {
333*81ad6265SDimitry Andric     First = End;
334*81ad6265SDimitry Andric     return;
335*81ad6265SDimitry Andric   }
336*81ad6265SDimitry Andric   for (First += 3; First != End; ++First)
337*81ad6265SDimitry Andric     if (First[-1] == '*' && First[0] == '/') {
338*81ad6265SDimitry Andric       ++First;
339*81ad6265SDimitry Andric       return;
340*81ad6265SDimitry Andric     }
341*81ad6265SDimitry Andric }
342*81ad6265SDimitry Andric 
343*81ad6265SDimitry Andric /// \returns True if the current single quotation mark character is a C++ 14
344*81ad6265SDimitry Andric /// digit separator.
345*81ad6265SDimitry Andric static bool isQuoteCppDigitSeparator(const char *const Start,
346*81ad6265SDimitry Andric                                      const char *const Cur,
347*81ad6265SDimitry Andric                                      const char *const End) {
348*81ad6265SDimitry Andric   assert(*Cur == '\'' && "expected quotation character");
349*81ad6265SDimitry Andric   // skipLine called in places where we don't expect a valid number
350*81ad6265SDimitry Andric   // body before `start` on the same line, so always return false at the start.
351*81ad6265SDimitry Andric   if (Start == Cur)
352*81ad6265SDimitry Andric     return false;
353*81ad6265SDimitry Andric   // The previous character must be a valid PP number character.
354*81ad6265SDimitry Andric   // Make sure that the L, u, U, u8 prefixes don't get marked as a
355*81ad6265SDimitry Andric   // separator though.
356*81ad6265SDimitry Andric   char Prev = *(Cur - 1);
357*81ad6265SDimitry Andric   if (Prev == 'L' || Prev == 'U' || Prev == 'u')
358*81ad6265SDimitry Andric     return false;
359*81ad6265SDimitry Andric   if (Prev == '8' && (Cur - 1 != Start) && *(Cur - 2) == 'u')
360*81ad6265SDimitry Andric     return false;
361*81ad6265SDimitry Andric   if (!isPreprocessingNumberBody(Prev))
362*81ad6265SDimitry Andric     return false;
363*81ad6265SDimitry Andric   // The next character should be a valid identifier body character.
364*81ad6265SDimitry Andric   return (Cur + 1) < End && isAsciiIdentifierContinue(*(Cur + 1));
365*81ad6265SDimitry Andric }
366*81ad6265SDimitry Andric 
367*81ad6265SDimitry Andric static void skipLine(const char *&First, const char *const End) {
368*81ad6265SDimitry Andric   for (;;) {
369*81ad6265SDimitry Andric     assert(First <= End);
370*81ad6265SDimitry Andric     if (First == End)
371*81ad6265SDimitry Andric       return;
372*81ad6265SDimitry Andric 
373*81ad6265SDimitry Andric     if (isVerticalWhitespace(*First)) {
374*81ad6265SDimitry Andric       skipNewline(First, End);
375*81ad6265SDimitry Andric       return;
376*81ad6265SDimitry Andric     }
377*81ad6265SDimitry Andric     const char *Start = First;
378*81ad6265SDimitry Andric     while (First != End && !isVerticalWhitespace(*First)) {
379*81ad6265SDimitry Andric       // Iterate over strings correctly to avoid comments and newlines.
380*81ad6265SDimitry Andric       if (*First == '"' ||
381*81ad6265SDimitry Andric           (*First == '\'' && !isQuoteCppDigitSeparator(Start, First, End))) {
382*81ad6265SDimitry Andric         if (isRawStringLiteral(Start, First))
383*81ad6265SDimitry Andric           skipRawString(First, End);
384*81ad6265SDimitry Andric         else
385*81ad6265SDimitry Andric           skipString(First, End);
386*81ad6265SDimitry Andric         continue;
387*81ad6265SDimitry Andric       }
388*81ad6265SDimitry Andric 
389*81ad6265SDimitry Andric       // Iterate over comments correctly.
390*81ad6265SDimitry Andric       if (*First != '/' || End - First < 2) {
391*81ad6265SDimitry Andric         ++First;
392*81ad6265SDimitry Andric         continue;
393*81ad6265SDimitry Andric       }
394*81ad6265SDimitry Andric 
395*81ad6265SDimitry Andric       if (First[1] == '/') {
396*81ad6265SDimitry Andric         // "//...".
397*81ad6265SDimitry Andric         skipLineComment(First, End);
398*81ad6265SDimitry Andric         continue;
399*81ad6265SDimitry Andric       }
400*81ad6265SDimitry Andric 
401*81ad6265SDimitry Andric       if (First[1] != '*') {
402*81ad6265SDimitry Andric         ++First;
403*81ad6265SDimitry Andric         continue;
404*81ad6265SDimitry Andric       }
405*81ad6265SDimitry Andric 
406*81ad6265SDimitry Andric       // "/*...*/".
407*81ad6265SDimitry Andric       skipBlockComment(First, End);
408*81ad6265SDimitry Andric     }
409*81ad6265SDimitry Andric     if (First == End)
410*81ad6265SDimitry Andric       return;
411*81ad6265SDimitry Andric 
412*81ad6265SDimitry Andric     // Skip over the newline.
413*81ad6265SDimitry Andric     unsigned Len = skipNewline(First, End);
414*81ad6265SDimitry Andric     if (!wasLineContinuation(First, Len)) // Continue past line-continuations.
415*81ad6265SDimitry Andric       break;
416*81ad6265SDimitry Andric   }
417*81ad6265SDimitry Andric }
418*81ad6265SDimitry Andric 
419*81ad6265SDimitry Andric static void skipDirective(StringRef Name, const char *&First,
420*81ad6265SDimitry Andric                           const char *const End) {
421*81ad6265SDimitry Andric   if (llvm::StringSwitch<bool>(Name)
422*81ad6265SDimitry Andric           .Case("warning", true)
423*81ad6265SDimitry Andric           .Case("error", true)
424*81ad6265SDimitry Andric           .Default(false))
425*81ad6265SDimitry Andric     // Do not process quotes or comments.
426*81ad6265SDimitry Andric     skipToNewlineRaw(First, End);
427*81ad6265SDimitry Andric   else
428*81ad6265SDimitry Andric     skipLine(First, End);
429*81ad6265SDimitry Andric }
430*81ad6265SDimitry Andric 
431*81ad6265SDimitry Andric static void skipWhitespace(const char *&First, const char *const End) {
432*81ad6265SDimitry Andric   for (;;) {
433*81ad6265SDimitry Andric     assert(First <= End);
434*81ad6265SDimitry Andric     skipOverSpaces(First, End);
435*81ad6265SDimitry Andric 
436*81ad6265SDimitry Andric     if (End - First < 2)
437*81ad6265SDimitry Andric       return;
438*81ad6265SDimitry Andric 
439*81ad6265SDimitry Andric     if (First[0] == '\\' && isVerticalWhitespace(First[1])) {
440*81ad6265SDimitry Andric       skipNewline(++First, End);
441*81ad6265SDimitry Andric       continue;
442*81ad6265SDimitry Andric     }
443*81ad6265SDimitry Andric 
444*81ad6265SDimitry Andric     // Check for a non-comment character.
445*81ad6265SDimitry Andric     if (First[0] != '/')
446*81ad6265SDimitry Andric       return;
447*81ad6265SDimitry Andric 
448*81ad6265SDimitry Andric     // "// ...".
449*81ad6265SDimitry Andric     if (First[1] == '/') {
450*81ad6265SDimitry Andric       skipLineComment(First, End);
451*81ad6265SDimitry Andric       return;
452*81ad6265SDimitry Andric     }
453*81ad6265SDimitry Andric 
454*81ad6265SDimitry Andric     // Cannot be a comment.
455*81ad6265SDimitry Andric     if (First[1] != '*')
456*81ad6265SDimitry Andric       return;
457*81ad6265SDimitry Andric 
458*81ad6265SDimitry Andric     // "/*...*/".
459*81ad6265SDimitry Andric     skipBlockComment(First, End);
460*81ad6265SDimitry Andric   }
461*81ad6265SDimitry Andric }
462*81ad6265SDimitry Andric 
463*81ad6265SDimitry Andric bool Scanner::lexModuleDirectiveBody(DirectiveKind Kind, const char *&First,
464*81ad6265SDimitry Andric                                      const char *const End) {
465*81ad6265SDimitry Andric   const char *DirectiveLoc = Input.data() + CurDirToks.front().Offset;
466*81ad6265SDimitry Andric   for (;;) {
467*81ad6265SDimitry Andric     const dependency_directives_scan::Token &Tok = lexToken(First, End);
468*81ad6265SDimitry Andric     if (Tok.is(tok::eof))
469*81ad6265SDimitry Andric       return reportError(
470*81ad6265SDimitry Andric           DirectiveLoc,
471*81ad6265SDimitry Andric           diag::err_dep_source_scanner_missing_semi_after_at_import);
472*81ad6265SDimitry Andric     if (Tok.is(tok::semi))
473*81ad6265SDimitry Andric       break;
474*81ad6265SDimitry Andric   }
475*81ad6265SDimitry Andric   pushDirective(Kind);
476*81ad6265SDimitry Andric   skipWhitespace(First, End);
477*81ad6265SDimitry Andric   if (First == End)
478*81ad6265SDimitry Andric     return false;
479*81ad6265SDimitry Andric   if (!isVerticalWhitespace(*First))
480*81ad6265SDimitry Andric     return reportError(
481*81ad6265SDimitry Andric         DirectiveLoc, diag::err_dep_source_scanner_unexpected_tokens_at_import);
482*81ad6265SDimitry Andric   skipNewline(First, End);
483*81ad6265SDimitry Andric   return false;
484*81ad6265SDimitry Andric }
485*81ad6265SDimitry Andric 
486*81ad6265SDimitry Andric dependency_directives_scan::Token &Scanner::lexToken(const char *&First,
487*81ad6265SDimitry Andric                                                      const char *const End) {
488*81ad6265SDimitry Andric   clang::Token Tok;
489*81ad6265SDimitry Andric   TheLexer.LexFromRawLexer(Tok);
490*81ad6265SDimitry Andric   First = Input.data() + TheLexer.getCurrentBufferOffset();
491*81ad6265SDimitry Andric   assert(First <= End);
492*81ad6265SDimitry Andric 
493*81ad6265SDimitry Andric   unsigned Offset = TheLexer.getCurrentBufferOffset() - Tok.getLength();
494*81ad6265SDimitry Andric   CurDirToks.emplace_back(Offset, Tok.getLength(), Tok.getKind(),
495*81ad6265SDimitry Andric                           Tok.getFlags());
496*81ad6265SDimitry Andric   return CurDirToks.back();
497*81ad6265SDimitry Andric }
498*81ad6265SDimitry Andric 
499*81ad6265SDimitry Andric dependency_directives_scan::Token &
500*81ad6265SDimitry Andric Scanner::lexIncludeFilename(const char *&First, const char *const End) {
501*81ad6265SDimitry Andric   clang::Token Tok;
502*81ad6265SDimitry Andric   TheLexer.LexIncludeFilename(Tok);
503*81ad6265SDimitry Andric   First = Input.data() + TheLexer.getCurrentBufferOffset();
504*81ad6265SDimitry Andric   assert(First <= End);
505*81ad6265SDimitry Andric 
506*81ad6265SDimitry Andric   unsigned Offset = TheLexer.getCurrentBufferOffset() - Tok.getLength();
507*81ad6265SDimitry Andric   CurDirToks.emplace_back(Offset, Tok.getLength(), Tok.getKind(),
508*81ad6265SDimitry Andric                           Tok.getFlags());
509*81ad6265SDimitry Andric   return CurDirToks.back();
510*81ad6265SDimitry Andric }
511*81ad6265SDimitry Andric 
512*81ad6265SDimitry Andric void Scanner::lexPPDirectiveBody(const char *&First, const char *const End) {
513*81ad6265SDimitry Andric   while (true) {
514*81ad6265SDimitry Andric     const dependency_directives_scan::Token &Tok = lexToken(First, End);
515*81ad6265SDimitry Andric     if (Tok.is(tok::eod))
516*81ad6265SDimitry Andric       break;
517*81ad6265SDimitry Andric   }
518*81ad6265SDimitry Andric }
519*81ad6265SDimitry Andric 
520*81ad6265SDimitry Andric LLVM_NODISCARD Optional<StringRef>
521*81ad6265SDimitry Andric Scanner::tryLexIdentifierOrSkipLine(const char *&First, const char *const End) {
522*81ad6265SDimitry Andric   const dependency_directives_scan::Token &Tok = lexToken(First, End);
523*81ad6265SDimitry Andric   if (Tok.isNot(tok::raw_identifier)) {
524*81ad6265SDimitry Andric     if (!Tok.is(tok::eod))
525*81ad6265SDimitry Andric       skipLine(First, End);
526*81ad6265SDimitry Andric     return None;
527*81ad6265SDimitry Andric   }
528*81ad6265SDimitry Andric 
529*81ad6265SDimitry Andric   bool NeedsCleaning = Tok.Flags & clang::Token::NeedsCleaning;
530*81ad6265SDimitry Andric   if (LLVM_LIKELY(!NeedsCleaning))
531*81ad6265SDimitry Andric     return Input.slice(Tok.Offset, Tok.getEnd());
532*81ad6265SDimitry Andric 
533*81ad6265SDimitry Andric   SmallString<64> Spelling;
534*81ad6265SDimitry Andric   Spelling.resize(Tok.Length);
535*81ad6265SDimitry Andric 
536*81ad6265SDimitry Andric   unsigned SpellingLength = 0;
537*81ad6265SDimitry Andric   const char *BufPtr = Input.begin() + Tok.Offset;
538*81ad6265SDimitry Andric   const char *AfterIdent = Input.begin() + Tok.getEnd();
539*81ad6265SDimitry Andric   while (BufPtr < AfterIdent) {
540*81ad6265SDimitry Andric     unsigned Size;
541*81ad6265SDimitry Andric     Spelling[SpellingLength++] =
542*81ad6265SDimitry Andric         Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts);
543*81ad6265SDimitry Andric     BufPtr += Size;
544*81ad6265SDimitry Andric   }
545*81ad6265SDimitry Andric 
546*81ad6265SDimitry Andric   return SplitIds.try_emplace(StringRef(Spelling.begin(), SpellingLength), 0)
547*81ad6265SDimitry Andric       .first->first();
548*81ad6265SDimitry Andric }
549*81ad6265SDimitry Andric 
550*81ad6265SDimitry Andric StringRef Scanner::lexIdentifier(const char *&First, const char *const End) {
551*81ad6265SDimitry Andric   Optional<StringRef> Id = tryLexIdentifierOrSkipLine(First, End);
552*81ad6265SDimitry Andric   assert(Id && "expected identifier token");
553*81ad6265SDimitry Andric   return Id.getValue();
554*81ad6265SDimitry Andric }
555*81ad6265SDimitry Andric 
556*81ad6265SDimitry Andric bool Scanner::isNextIdentifierOrSkipLine(StringRef Id, const char *&First,
557*81ad6265SDimitry Andric                                          const char *const End) {
558*81ad6265SDimitry Andric   if (Optional<StringRef> FoundId = tryLexIdentifierOrSkipLine(First, End)) {
559*81ad6265SDimitry Andric     if (*FoundId == Id)
560*81ad6265SDimitry Andric       return true;
561*81ad6265SDimitry Andric     skipLine(First, End);
562*81ad6265SDimitry Andric   }
563*81ad6265SDimitry Andric   return false;
564*81ad6265SDimitry Andric }
565*81ad6265SDimitry Andric 
566*81ad6265SDimitry Andric bool Scanner::lexAt(const char *&First, const char *const End) {
567*81ad6265SDimitry Andric   // Handle "@import".
568*81ad6265SDimitry Andric 
569*81ad6265SDimitry Andric   // Lex '@'.
570*81ad6265SDimitry Andric   const dependency_directives_scan::Token &AtTok = lexToken(First, End);
571*81ad6265SDimitry Andric   assert(AtTok.is(tok::at));
572*81ad6265SDimitry Andric   (void)AtTok;
573*81ad6265SDimitry Andric 
574*81ad6265SDimitry Andric   if (!isNextIdentifierOrSkipLine("import", First, End))
575*81ad6265SDimitry Andric     return false;
576*81ad6265SDimitry Andric   return lexModuleDirectiveBody(decl_at_import, First, End);
577*81ad6265SDimitry Andric }
578*81ad6265SDimitry Andric 
579*81ad6265SDimitry Andric bool Scanner::lexModule(const char *&First, const char *const End) {
580*81ad6265SDimitry Andric   StringRef Id = lexIdentifier(First, End);
581*81ad6265SDimitry Andric   bool Export = false;
582*81ad6265SDimitry Andric   if (Id == "export") {
583*81ad6265SDimitry Andric     Export = true;
584*81ad6265SDimitry Andric     Optional<StringRef> NextId = tryLexIdentifierOrSkipLine(First, End);
585*81ad6265SDimitry Andric     if (!NextId)
586*81ad6265SDimitry Andric       return false;
587*81ad6265SDimitry Andric     Id = *NextId;
588*81ad6265SDimitry Andric   }
589*81ad6265SDimitry Andric 
590*81ad6265SDimitry Andric   if (Id != "module" && Id != "import") {
591*81ad6265SDimitry Andric     skipLine(First, End);
592*81ad6265SDimitry Andric     return false;
593*81ad6265SDimitry Andric   }
594*81ad6265SDimitry Andric 
595*81ad6265SDimitry Andric   skipWhitespace(First, End);
596*81ad6265SDimitry Andric 
597*81ad6265SDimitry Andric   // Ignore this as a module directive if the next character can't be part of
598*81ad6265SDimitry Andric   // an import.
599*81ad6265SDimitry Andric 
600*81ad6265SDimitry Andric   switch (*First) {
601*81ad6265SDimitry Andric   case ':':
602*81ad6265SDimitry Andric   case '<':
603*81ad6265SDimitry Andric   case '"':
604*81ad6265SDimitry Andric     break;
605*81ad6265SDimitry Andric   default:
606*81ad6265SDimitry Andric     if (!isAsciiIdentifierContinue(*First)) {
607*81ad6265SDimitry Andric       skipLine(First, End);
608*81ad6265SDimitry Andric       return false;
609*81ad6265SDimitry Andric     }
610*81ad6265SDimitry Andric   }
611*81ad6265SDimitry Andric 
612*81ad6265SDimitry Andric   TheLexer.seek(getOffsetAt(First), /*IsAtStartOfLine*/ false);
613*81ad6265SDimitry Andric 
614*81ad6265SDimitry Andric   DirectiveKind Kind;
615*81ad6265SDimitry Andric   if (Id == "module")
616*81ad6265SDimitry Andric     Kind = Export ? cxx_export_module_decl : cxx_module_decl;
617*81ad6265SDimitry Andric   else
618*81ad6265SDimitry Andric     Kind = Export ? cxx_export_import_decl : cxx_import_decl;
619*81ad6265SDimitry Andric 
620*81ad6265SDimitry Andric   return lexModuleDirectiveBody(Kind, First, End);
621*81ad6265SDimitry Andric }
622*81ad6265SDimitry Andric 
623*81ad6265SDimitry Andric bool Scanner::lexPragma(const char *&First, const char *const End) {
624*81ad6265SDimitry Andric   Optional<StringRef> FoundId = tryLexIdentifierOrSkipLine(First, End);
625*81ad6265SDimitry Andric   if (!FoundId)
626*81ad6265SDimitry Andric     return false;
627*81ad6265SDimitry Andric 
628*81ad6265SDimitry Andric   StringRef Id = *FoundId;
629*81ad6265SDimitry Andric   auto Kind = llvm::StringSwitch<DirectiveKind>(Id)
630*81ad6265SDimitry Andric                   .Case("once", pp_pragma_once)
631*81ad6265SDimitry Andric                   .Case("push_macro", pp_pragma_push_macro)
632*81ad6265SDimitry Andric                   .Case("pop_macro", pp_pragma_pop_macro)
633*81ad6265SDimitry Andric                   .Case("include_alias", pp_pragma_include_alias)
634*81ad6265SDimitry Andric                   .Default(pp_none);
635*81ad6265SDimitry Andric   if (Kind != pp_none) {
636*81ad6265SDimitry Andric     lexPPDirectiveBody(First, End);
637*81ad6265SDimitry Andric     pushDirective(Kind);
638*81ad6265SDimitry Andric     return false;
639*81ad6265SDimitry Andric   }
640*81ad6265SDimitry Andric 
641*81ad6265SDimitry Andric   if (Id != "clang") {
642*81ad6265SDimitry Andric     skipLine(First, End);
643*81ad6265SDimitry Andric     return false;
644*81ad6265SDimitry Andric   }
645*81ad6265SDimitry Andric 
646*81ad6265SDimitry Andric   // #pragma clang.
647*81ad6265SDimitry Andric   if (!isNextIdentifierOrSkipLine("module", First, End))
648*81ad6265SDimitry Andric     return false;
649*81ad6265SDimitry Andric 
650*81ad6265SDimitry Andric   // #pragma clang module.
651*81ad6265SDimitry Andric   if (!isNextIdentifierOrSkipLine("import", First, End))
652*81ad6265SDimitry Andric     return false;
653*81ad6265SDimitry Andric 
654*81ad6265SDimitry Andric   // #pragma clang module import.
655*81ad6265SDimitry Andric   lexPPDirectiveBody(First, End);
656*81ad6265SDimitry Andric   pushDirective(pp_pragma_import);
657*81ad6265SDimitry Andric   return false;
658*81ad6265SDimitry Andric }
659*81ad6265SDimitry Andric 
660*81ad6265SDimitry Andric bool Scanner::lexEndif(const char *&First, const char *const End) {
661*81ad6265SDimitry Andric   // Strip out "#else" if it's empty.
662*81ad6265SDimitry Andric   if (topDirective() == pp_else)
663*81ad6265SDimitry Andric     popDirective();
664*81ad6265SDimitry Andric 
665*81ad6265SDimitry Andric   // If "#ifdef" is empty, strip it and skip the "#endif".
666*81ad6265SDimitry Andric   //
667*81ad6265SDimitry Andric   // FIXME: Once/if Clang starts disallowing __has_include in macro expansions,
668*81ad6265SDimitry Andric   // we can skip empty `#if` and `#elif` blocks as well after scanning for a
669*81ad6265SDimitry Andric   // literal __has_include in the condition.  Even without that rule we could
670*81ad6265SDimitry Andric   // drop the tokens if we scan for identifiers in the condition and find none.
671*81ad6265SDimitry Andric   if (topDirective() == pp_ifdef || topDirective() == pp_ifndef) {
672*81ad6265SDimitry Andric     popDirective();
673*81ad6265SDimitry Andric     skipLine(First, End);
674*81ad6265SDimitry Andric     return false;
675*81ad6265SDimitry Andric   }
676*81ad6265SDimitry Andric 
677*81ad6265SDimitry Andric   return lexDefault(pp_endif, First, End);
678*81ad6265SDimitry Andric }
679*81ad6265SDimitry Andric 
680*81ad6265SDimitry Andric bool Scanner::lexDefault(DirectiveKind Kind, const char *&First,
681*81ad6265SDimitry Andric                          const char *const End) {
682*81ad6265SDimitry Andric   lexPPDirectiveBody(First, End);
683*81ad6265SDimitry Andric   pushDirective(Kind);
684*81ad6265SDimitry Andric   return false;
685*81ad6265SDimitry Andric }
686*81ad6265SDimitry Andric 
687*81ad6265SDimitry Andric static bool isStartOfRelevantLine(char First) {
688*81ad6265SDimitry Andric   switch (First) {
689*81ad6265SDimitry Andric   case '#':
690*81ad6265SDimitry Andric   case '@':
691*81ad6265SDimitry Andric   case 'i':
692*81ad6265SDimitry Andric   case 'e':
693*81ad6265SDimitry Andric   case 'm':
694*81ad6265SDimitry Andric     return true;
695*81ad6265SDimitry Andric   }
696*81ad6265SDimitry Andric   return false;
697*81ad6265SDimitry Andric }
698*81ad6265SDimitry Andric 
699*81ad6265SDimitry Andric bool Scanner::lexPPLine(const char *&First, const char *const End) {
700*81ad6265SDimitry Andric   assert(First != End);
701*81ad6265SDimitry Andric 
702*81ad6265SDimitry Andric   skipWhitespace(First, End);
703*81ad6265SDimitry Andric   assert(First <= End);
704*81ad6265SDimitry Andric   if (First == End)
705*81ad6265SDimitry Andric     return false;
706*81ad6265SDimitry Andric 
707*81ad6265SDimitry Andric   if (!isStartOfRelevantLine(*First)) {
708*81ad6265SDimitry Andric     skipLine(First, End);
709*81ad6265SDimitry Andric     assert(First <= End);
710*81ad6265SDimitry Andric     return false;
711*81ad6265SDimitry Andric   }
712*81ad6265SDimitry Andric 
713*81ad6265SDimitry Andric   TheLexer.seek(getOffsetAt(First), /*IsAtStartOfLine*/ true);
714*81ad6265SDimitry Andric 
715*81ad6265SDimitry Andric   auto ScEx1 = make_scope_exit([&]() {
716*81ad6265SDimitry Andric     /// Clear Scanner's CurDirToks before returning, in case we didn't push a
717*81ad6265SDimitry Andric     /// new directive.
718*81ad6265SDimitry Andric     CurDirToks.clear();
719*81ad6265SDimitry Andric   });
720*81ad6265SDimitry Andric 
721*81ad6265SDimitry Andric   // Handle "@import".
722*81ad6265SDimitry Andric   if (*First == '@')
723*81ad6265SDimitry Andric     return lexAt(First, End);
724*81ad6265SDimitry Andric 
725*81ad6265SDimitry Andric   if (*First == 'i' || *First == 'e' || *First == 'm')
726*81ad6265SDimitry Andric     return lexModule(First, End);
727*81ad6265SDimitry Andric 
728*81ad6265SDimitry Andric   // Handle preprocessing directives.
729*81ad6265SDimitry Andric 
730*81ad6265SDimitry Andric   TheLexer.setParsingPreprocessorDirective(true);
731*81ad6265SDimitry Andric   auto ScEx2 = make_scope_exit(
732*81ad6265SDimitry Andric       [&]() { TheLexer.setParsingPreprocessorDirective(false); });
733*81ad6265SDimitry Andric 
734*81ad6265SDimitry Andric   // Lex '#'.
735*81ad6265SDimitry Andric   const dependency_directives_scan::Token &HashTok = lexToken(First, End);
736*81ad6265SDimitry Andric   assert(HashTok.is(tok::hash));
737*81ad6265SDimitry Andric   (void)HashTok;
738*81ad6265SDimitry Andric 
739*81ad6265SDimitry Andric   Optional<StringRef> FoundId = tryLexIdentifierOrSkipLine(First, End);
740*81ad6265SDimitry Andric   if (!FoundId)
741*81ad6265SDimitry Andric     return false;
742*81ad6265SDimitry Andric 
743*81ad6265SDimitry Andric   StringRef Id = *FoundId;
744*81ad6265SDimitry Andric 
745*81ad6265SDimitry Andric   if (Id == "pragma")
746*81ad6265SDimitry Andric     return lexPragma(First, End);
747*81ad6265SDimitry Andric 
748*81ad6265SDimitry Andric   auto Kind = llvm::StringSwitch<DirectiveKind>(Id)
749*81ad6265SDimitry Andric                   .Case("include", pp_include)
750*81ad6265SDimitry Andric                   .Case("__include_macros", pp___include_macros)
751*81ad6265SDimitry Andric                   .Case("define", pp_define)
752*81ad6265SDimitry Andric                   .Case("undef", pp_undef)
753*81ad6265SDimitry Andric                   .Case("import", pp_import)
754*81ad6265SDimitry Andric                   .Case("include_next", pp_include_next)
755*81ad6265SDimitry Andric                   .Case("if", pp_if)
756*81ad6265SDimitry Andric                   .Case("ifdef", pp_ifdef)
757*81ad6265SDimitry Andric                   .Case("ifndef", pp_ifndef)
758*81ad6265SDimitry Andric                   .Case("elif", pp_elif)
759*81ad6265SDimitry Andric                   .Case("elifdef", pp_elifdef)
760*81ad6265SDimitry Andric                   .Case("elifndef", pp_elifndef)
761*81ad6265SDimitry Andric                   .Case("else", pp_else)
762*81ad6265SDimitry Andric                   .Case("endif", pp_endif)
763*81ad6265SDimitry Andric                   .Default(pp_none);
764*81ad6265SDimitry Andric   if (Kind == pp_none) {
765*81ad6265SDimitry Andric     skipDirective(Id, First, End);
766*81ad6265SDimitry Andric     return false;
767*81ad6265SDimitry Andric   }
768*81ad6265SDimitry Andric 
769*81ad6265SDimitry Andric   if (Kind == pp_endif)
770*81ad6265SDimitry Andric     return lexEndif(First, End);
771*81ad6265SDimitry Andric 
772*81ad6265SDimitry Andric   switch (Kind) {
773*81ad6265SDimitry Andric   case pp_include:
774*81ad6265SDimitry Andric   case pp___include_macros:
775*81ad6265SDimitry Andric   case pp_include_next:
776*81ad6265SDimitry Andric   case pp_import:
777*81ad6265SDimitry Andric     lexIncludeFilename(First, End);
778*81ad6265SDimitry Andric     break;
779*81ad6265SDimitry Andric   default:
780*81ad6265SDimitry Andric     break;
781*81ad6265SDimitry Andric   }
782*81ad6265SDimitry Andric 
783*81ad6265SDimitry Andric   // Everything else.
784*81ad6265SDimitry Andric   return lexDefault(Kind, First, End);
785*81ad6265SDimitry Andric }
786*81ad6265SDimitry Andric 
787*81ad6265SDimitry Andric static void skipUTF8ByteOrderMark(const char *&First, const char *const End) {
788*81ad6265SDimitry Andric   if ((End - First) >= 3 && First[0] == '\xef' && First[1] == '\xbb' &&
789*81ad6265SDimitry Andric       First[2] == '\xbf')
790*81ad6265SDimitry Andric     First += 3;
791*81ad6265SDimitry Andric }
792*81ad6265SDimitry Andric 
793*81ad6265SDimitry Andric bool Scanner::scanImpl(const char *First, const char *const End) {
794*81ad6265SDimitry Andric   skipUTF8ByteOrderMark(First, End);
795*81ad6265SDimitry Andric   while (First != End)
796*81ad6265SDimitry Andric     if (lexPPLine(First, End))
797*81ad6265SDimitry Andric       return true;
798*81ad6265SDimitry Andric   return false;
799*81ad6265SDimitry Andric }
800*81ad6265SDimitry Andric 
801*81ad6265SDimitry Andric bool Scanner::scan(SmallVectorImpl<Directive> &Directives) {
802*81ad6265SDimitry Andric   bool Error = scanImpl(Input.begin(), Input.end());
803*81ad6265SDimitry Andric 
804*81ad6265SDimitry Andric   if (!Error) {
805*81ad6265SDimitry Andric     // Add an EOF on success.
806*81ad6265SDimitry Andric     pushDirective(pp_eof);
807*81ad6265SDimitry Andric   }
808*81ad6265SDimitry Andric 
809*81ad6265SDimitry Andric   ArrayRef<dependency_directives_scan::Token> RemainingTokens = Tokens;
810*81ad6265SDimitry Andric   for (const DirectiveWithTokens &DirWithToks : DirsWithToks) {
811*81ad6265SDimitry Andric     assert(RemainingTokens.size() >= DirWithToks.NumTokens);
812*81ad6265SDimitry Andric     Directives.emplace_back(DirWithToks.Kind,
813*81ad6265SDimitry Andric                             RemainingTokens.take_front(DirWithToks.NumTokens));
814*81ad6265SDimitry Andric     RemainingTokens = RemainingTokens.drop_front(DirWithToks.NumTokens);
815*81ad6265SDimitry Andric   }
816*81ad6265SDimitry Andric   assert(RemainingTokens.empty());
817*81ad6265SDimitry Andric 
818*81ad6265SDimitry Andric   return Error;
819*81ad6265SDimitry Andric }
820*81ad6265SDimitry Andric 
821*81ad6265SDimitry Andric bool clang::scanSourceForDependencyDirectives(
822*81ad6265SDimitry Andric     StringRef Input, SmallVectorImpl<dependency_directives_scan::Token> &Tokens,
823*81ad6265SDimitry Andric     SmallVectorImpl<Directive> &Directives, DiagnosticsEngine *Diags,
824*81ad6265SDimitry Andric     SourceLocation InputSourceLoc) {
825*81ad6265SDimitry Andric   return Scanner(Input, Tokens, Diags, InputSourceLoc).scan(Directives);
826*81ad6265SDimitry Andric }
827*81ad6265SDimitry Andric 
828*81ad6265SDimitry Andric void clang::printDependencyDirectivesAsSource(
829*81ad6265SDimitry Andric     StringRef Source,
830*81ad6265SDimitry Andric     ArrayRef<dependency_directives_scan::Directive> Directives,
831*81ad6265SDimitry Andric     llvm::raw_ostream &OS) {
832*81ad6265SDimitry Andric   // Add a space separator where it is convenient for testing purposes.
833*81ad6265SDimitry Andric   auto needsSpaceSeparator =
834*81ad6265SDimitry Andric       [](tok::TokenKind Prev,
835*81ad6265SDimitry Andric          const dependency_directives_scan::Token &Tok) -> bool {
836*81ad6265SDimitry Andric     if (Prev == Tok.Kind)
837*81ad6265SDimitry Andric       return !Tok.isOneOf(tok::l_paren, tok::r_paren, tok::l_square,
838*81ad6265SDimitry Andric                           tok::r_square);
839*81ad6265SDimitry Andric     if (Prev == tok::raw_identifier &&
840*81ad6265SDimitry Andric         Tok.isOneOf(tok::hash, tok::numeric_constant, tok::string_literal,
841*81ad6265SDimitry Andric                     tok::char_constant, tok::header_name))
842*81ad6265SDimitry Andric       return true;
843*81ad6265SDimitry Andric     if (Prev == tok::r_paren &&
844*81ad6265SDimitry Andric         Tok.isOneOf(tok::raw_identifier, tok::hash, tok::string_literal,
845*81ad6265SDimitry Andric                     tok::char_constant, tok::unknown))
846*81ad6265SDimitry Andric       return true;
847*81ad6265SDimitry Andric     if (Prev == tok::comma &&
848*81ad6265SDimitry Andric         Tok.isOneOf(tok::l_paren, tok::string_literal, tok::less))
849*81ad6265SDimitry Andric       return true;
850*81ad6265SDimitry Andric     return false;
851*81ad6265SDimitry Andric   };
852*81ad6265SDimitry Andric 
853*81ad6265SDimitry Andric   for (const dependency_directives_scan::Directive &Directive : Directives) {
854*81ad6265SDimitry Andric     Optional<tok::TokenKind> PrevTokenKind;
855*81ad6265SDimitry Andric     for (const dependency_directives_scan::Token &Tok : Directive.Tokens) {
856*81ad6265SDimitry Andric       if (PrevTokenKind && needsSpaceSeparator(*PrevTokenKind, Tok))
857*81ad6265SDimitry Andric         OS << ' ';
858*81ad6265SDimitry Andric       PrevTokenKind = Tok.Kind;
859*81ad6265SDimitry Andric       OS << Source.slice(Tok.Offset, Tok.getEnd());
860*81ad6265SDimitry Andric     }
861*81ad6265SDimitry Andric   }
862*81ad6265SDimitry Andric }
863