clang  14.0.0git
Lexer.cpp
Go to the documentation of this file.
1 //===- Lexer.cpp - C Language Family Lexer --------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the Lexer and Token interfaces.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/Lex/Lexer.h"
14 #include "UnicodeCharSets.h"
15 #include "clang/Basic/CharInfo.h"
16 #include "clang/Basic/Diagnostic.h"
18 #include "clang/Basic/LLVM.h"
22 #include "clang/Basic/TokenKinds.h"
26 #include "clang/Lex/Preprocessor.h"
28 #include "clang/Lex/Token.h"
29 #include "llvm/ADT/None.h"
30 #include "llvm/ADT/Optional.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/ADT/StringExtras.h"
33 #include "llvm/ADT/StringRef.h"
34 #include "llvm/ADT/StringSwitch.h"
35 #include "llvm/Support/Compiler.h"
36 #include "llvm/Support/ConvertUTF.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/MemoryBufferRef.h"
39 #include "llvm/Support/NativeFormatting.h"
40 #include "llvm/Support/UnicodeCharRanges.h"
41 #include <algorithm>
42 #include <cassert>
43 #include <cstddef>
44 #include <cstdint>
45 #include <cstring>
46 #include <string>
47 #include <tuple>
48 #include <utility>
49 
50 using namespace clang;
51 
52 //===----------------------------------------------------------------------===//
53 // Token Class Implementation
54 //===----------------------------------------------------------------------===//
55 
56 /// isObjCAtKeyword - Return true if we have an ObjC keyword identifier.
58  if (isAnnotation())
59  return false;
61  return II->getObjCKeywordID() == objcKey;
62  return false;
63 }
64 
65 /// getObjCKeywordID - Return the ObjC keyword kind.
67  if (isAnnotation())
68  return tok::objc_not_keyword;
70  return specId ? specId->getObjCKeywordID() : tok::objc_not_keyword;
71 }
72 
73 //===----------------------------------------------------------------------===//
74 // Lexer Class Implementation
75 //===----------------------------------------------------------------------===//
76 
77 void Lexer::anchor() {}
78 
79 void Lexer::InitLexer(const char *BufStart, const char *BufPtr,
80  const char *BufEnd) {
81  BufferStart = BufStart;
82  BufferPtr = BufPtr;
83  BufferEnd = BufEnd;
84 
85  assert(BufEnd[0] == 0 &&
86  "We assume that the input buffer has a null character at the end"
87  " to simplify lexing!");
88 
89  // Check whether we have a BOM in the beginning of the buffer. If yes - act
90  // accordingly. Right now we support only UTF-8 with and without BOM, so, just
91  // skip the UTF-8 BOM if it's present.
92  if (BufferStart == BufferPtr) {
93  // Determine the size of the BOM.
94  StringRef Buf(BufferStart, BufferEnd - BufferStart);
95  size_t BOMLength = llvm::StringSwitch<size_t>(Buf)
96  .StartsWith("\xEF\xBB\xBF", 3) // UTF-8 BOM
97  .Default(0);
98 
99  // Skip the BOM.
100  BufferPtr += BOMLength;
101  }
102 
103  Is_PragmaLexer = false;
104  CurrentConflictMarkerState = CMK_None;
105 
106  // Start of the file is a start of line.
107  IsAtStartOfLine = true;
108  IsAtPhysicalStartOfLine = true;
109 
110  HasLeadingSpace = false;
111  HasLeadingEmptyMacro = false;
112 
113  // We are not after parsing a #.
115 
116  // We are not after parsing #include.
117  ParsingFilename = false;
118 
119  // We are not in raw mode. Raw mode disables diagnostics and interpretation
120  // of tokens (e.g. identifiers, thus disabling macro expansion). It is used
121  // to quickly lex the tokens of the buffer, e.g. when handling a "#if 0" block
122  // or otherwise skipping over tokens.
123  LexingRawMode = false;
124 
125  // Default to not keeping comments.
126  ExtendedTokenMode = 0;
127 
128  NewLinePtr = nullptr;
129 }
130 
131 /// Lexer constructor - Create a new lexer object for the specified buffer
132 /// with the specified preprocessor managing the lexing process. This lexer
133 /// assumes that the associated file buffer and Preprocessor objects will
134 /// outlive it, so it doesn't take ownership of either of them.
135 Lexer::Lexer(FileID FID, const llvm::MemoryBufferRef &InputFile,
136  Preprocessor &PP)
137  : PreprocessorLexer(&PP, FID),
138  FileLoc(PP.getSourceManager().getLocForStartOfFile(FID)),
139  LangOpts(PP.getLangOpts()) {
140  InitLexer(InputFile.getBufferStart(), InputFile.getBufferStart(),
141  InputFile.getBufferEnd());
142 
144 }
145 
146 /// Lexer constructor - Create a new raw lexer object. This object is only
147 /// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the text
148 /// range will outlive it, so it doesn't take ownership of it.
149 Lexer::Lexer(SourceLocation fileloc, const LangOptions &langOpts,
150  const char *BufStart, const char *BufPtr, const char *BufEnd)
151  : FileLoc(fileloc), LangOpts(langOpts) {
152  InitLexer(BufStart, BufPtr, BufEnd);
153 
154  // We *are* in raw mode.
155  LexingRawMode = true;
156 }
157 
158 /// Lexer constructor - Create a new raw lexer object. This object is only
159 /// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the text
160 /// range will outlive it, so it doesn't take ownership of it.
161 Lexer::Lexer(FileID FID, const llvm::MemoryBufferRef &FromFile,
162  const SourceManager &SM, const LangOptions &langOpts)
163  : Lexer(SM.getLocForStartOfFile(FID), langOpts, FromFile.getBufferStart(),
164  FromFile.getBufferStart(), FromFile.getBufferEnd()) {}
165 
167  assert(PP && "Cannot reset token mode without a preprocessor");
168  if (LangOpts.TraditionalCPP)
169  SetKeepWhitespaceMode(true);
170  else
172 }
173 
174 /// Create_PragmaLexer: Lexer constructor - Create a new lexer object for
175 /// _Pragma expansion. This has a variety of magic semantics that this method
176 /// sets up. It returns a new'd Lexer that must be delete'd when done.
177 ///
178 /// On entrance to this routine, TokStartLoc is a macro location which has a
179 /// spelling loc that indicates the bytes to be lexed for the token and an
180 /// expansion location that indicates where all lexed tokens should be
181 /// "expanded from".
182 ///
183 /// TODO: It would really be nice to make _Pragma just be a wrapper around a
184 /// normal lexer that remaps tokens as they fly by. This would require making
185 /// Preprocessor::Lex virtual. Given that, we could just dump in a magic lexer
186 /// interface that could handle this stuff. This would pull GetMappedTokenLoc
187 /// out of the critical path of the lexer!
188 ///
190  SourceLocation ExpansionLocStart,
191  SourceLocation ExpansionLocEnd,
192  unsigned TokLen, Preprocessor &PP) {
194 
195  // Create the lexer as if we were going to lex the file normally.
196  FileID SpellingFID = SM.getFileID(SpellingLoc);
197  llvm::MemoryBufferRef InputFile = SM.getBufferOrFake(SpellingFID);
198  Lexer *L = new Lexer(SpellingFID, InputFile, PP);
199 
200  // Now that the lexer is created, change the start/end locations so that we
201  // just lex the subsection of the file that we want. This is lexing from a
202  // scratch buffer.
203  const char *StrData = SM.getCharacterData(SpellingLoc);
204 
205  L->BufferPtr = StrData;
206  L->BufferEnd = StrData+TokLen;
207  assert(L->BufferEnd[0] == 0 && "Buffer is not nul terminated!");
208 
209  // Set the SourceLocation with the remapping information. This ensures that
210  // GetMappedTokenLoc will remap the tokens as they are lexed.
211  L->FileLoc = SM.createExpansionLoc(SM.getLocForStartOfFile(SpellingFID),
212  ExpansionLocStart,
213  ExpansionLocEnd, TokLen);
214 
215  // Ensure that the lexer thinks it is inside a directive, so that end \n will
216  // return an EOD token.
218 
219  // This lexer really is for _Pragma.
220  L->Is_PragmaLexer = true;
221  return L;
222 }
223 
224 bool Lexer::skipOver(unsigned NumBytes) {
225  IsAtPhysicalStartOfLine = true;
226  IsAtStartOfLine = true;
227  if ((BufferPtr + NumBytes) > BufferEnd)
228  return true;
229  BufferPtr += NumBytes;
230  return false;
231 }
232 
233 template <typename T> static void StringifyImpl(T &Str, char Quote) {
234  typename T::size_type i = 0, e = Str.size();
235  while (i < e) {
236  if (Str[i] == '\\' || Str[i] == Quote) {
237  Str.insert(Str.begin() + i, '\\');
238  i += 2;
239  ++e;
240  } else if (Str[i] == '\n' || Str[i] == '\r') {
241  // Replace '\r\n' and '\n\r' to '\\' followed by 'n'.
242  if ((i < e - 1) && (Str[i + 1] == '\n' || Str[i + 1] == '\r') &&
243  Str[i] != Str[i + 1]) {
244  Str[i] = '\\';
245  Str[i + 1] = 'n';
246  } else {
247  // Replace '\n' and '\r' to '\\' followed by 'n'.
248  Str[i] = '\\';
249  Str.insert(Str.begin() + i + 1, 'n');
250  ++e;
251  }
252  i += 2;
253  } else
254  ++i;
255  }
256 }
257 
258 std::string Lexer::Stringify(StringRef Str, bool Charify) {
259  std::string Result = std::string(Str);
260  char Quote = Charify ? '\'' : '"';
261  StringifyImpl(Result, Quote);
262  return Result;
263 }
264 
266 
267 //===----------------------------------------------------------------------===//
268 // Token Spelling
269 //===----------------------------------------------------------------------===//
270 
271 /// Slow case of getSpelling. Extract the characters comprising the
272 /// spelling of this token from the provided input buffer.
273 static size_t getSpellingSlow(const Token &Tok, const char *BufPtr,
274  const LangOptions &LangOpts, char *Spelling) {
275  assert(Tok.needsCleaning() && "getSpellingSlow called on simple token");
276 
277  size_t Length = 0;
278  const char *BufEnd = BufPtr + Tok.getLength();
279 
280  if (tok::isStringLiteral(Tok.getKind())) {
281  // Munch the encoding-prefix and opening double-quote.
282  while (BufPtr < BufEnd) {
283  unsigned Size;
284  Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts);
285  BufPtr += Size;
286 
287  if (Spelling[Length - 1] == '"')
288  break;
289  }
290 
291  // Raw string literals need special handling; trigraph expansion and line
292  // splicing do not occur within their d-char-sequence nor within their
293  // r-char-sequence.
294  if (Length >= 2 &&
295  Spelling[Length - 2] == 'R' && Spelling[Length - 1] == '"') {
296  // Search backwards from the end of the token to find the matching closing
297  // quote.
298  const char *RawEnd = BufEnd;
299  do --RawEnd; while (*RawEnd != '"');
300  size_t RawLength = RawEnd - BufPtr + 1;
301 
302  // Everything between the quotes is included verbatim in the spelling.
303  memcpy(Spelling + Length, BufPtr, RawLength);
304  Length += RawLength;
305  BufPtr += RawLength;
306 
307  // The rest of the token is lexed normally.
308  }
309  }
310 
311  while (BufPtr < BufEnd) {
312  unsigned Size;
313  Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts);
314  BufPtr += Size;
315  }
316 
317  assert(Length < Tok.getLength() &&
318  "NeedsCleaning flag set on token that didn't need cleaning!");
319  return Length;
320 }
321 
322 /// getSpelling() - Return the 'spelling' of this token. The spelling of a
323 /// token are the characters used to represent the token in the source file
324 /// after trigraph expansion and escaped-newline folding. In particular, this
325 /// wants to get the true, uncanonicalized, spelling of things like digraphs
326 /// UCNs, etc.
328  SmallVectorImpl<char> &buffer,
329  const SourceManager &SM,
330  const LangOptions &options,
331  bool *invalid) {
332  // Break down the source location.
333  std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(loc);
334 
335  // Try to the load the file buffer.
336  bool invalidTemp = false;
337  StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
338  if (invalidTemp) {
339  if (invalid) *invalid = true;
340  return {};
341  }
342 
343  const char *tokenBegin = file.data() + locInfo.second;
344 
345  // Lex from the start of the given location.
346  Lexer lexer(SM.getLocForStartOfFile(locInfo.first), options,
347  file.begin(), tokenBegin, file.end());
348  Token token;
349  lexer.LexFromRawLexer(token);
350 
351  unsigned length = token.getLength();
352 
353  // Common case: no need for cleaning.
354  if (!token.needsCleaning())
355  return StringRef(tokenBegin, length);
356 
357  // Hard case, we need to relex the characters into the string.
358  buffer.resize(length);
359  buffer.resize(getSpellingSlow(token, tokenBegin, options, buffer.data()));
360  return StringRef(buffer.data(), buffer.size());
361 }
362 
363 /// getSpelling() - Return the 'spelling' of this token. The spelling of a
364 /// token are the characters used to represent the token in the source file
365 /// after trigraph expansion and escaped-newline folding. In particular, this
366 /// wants to get the true, uncanonicalized, spelling of things like digraphs
367 /// UCNs, etc.
368 std::string Lexer::getSpelling(const Token &Tok, const SourceManager &SourceMgr,
369  const LangOptions &LangOpts, bool *Invalid) {
370  assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
371 
372  bool CharDataInvalid = false;
373  const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation(),
374  &CharDataInvalid);
375  if (Invalid)
376  *Invalid = CharDataInvalid;
377  if (CharDataInvalid)
378  return {};
379 
380  // If this token contains nothing interesting, return it directly.
381  if (!Tok.needsCleaning())
382  return std::string(TokStart, TokStart + Tok.getLength());
383 
384  std::string Result;
385  Result.resize(Tok.getLength());
386  Result.resize(getSpellingSlow(Tok, TokStart, LangOpts, &*Result.begin()));
387  return Result;
388 }
389 
390 /// getSpelling - This method is used to get the spelling of a token into a
391 /// preallocated buffer, instead of as an std::string. The caller is required
392 /// to allocate enough space for the token, which is guaranteed to be at least
393 /// Tok.getLength() bytes long. The actual length of the token is returned.
394 ///
395 /// Note that this method may do two possible things: it may either fill in
396 /// the buffer specified with characters, or it may *change the input pointer*
397 /// to point to a constant buffer with the data already in it (avoiding a
398 /// copy). The caller is not allowed to modify the returned buffer pointer
399 /// if an internal buffer is returned.
400 unsigned Lexer::getSpelling(const Token &Tok, const char *&Buffer,
401  const SourceManager &SourceMgr,
402  const LangOptions &LangOpts, bool *Invalid) {
403  assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
404 
405  const char *TokStart = nullptr;
406  // NOTE: this has to be checked *before* testing for an IdentifierInfo.
407  if (Tok.is(tok::raw_identifier))
408  TokStart = Tok.getRawIdentifier().data();
409  else if (!Tok.hasUCN()) {
410  if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
411  // Just return the string from the identifier table, which is very quick.
412  Buffer = II->getNameStart();
413  return II->getLength();
414  }
415  }
416 
417  // NOTE: this can be checked even after testing for an IdentifierInfo.
418  if (Tok.isLiteral())
419  TokStart = Tok.getLiteralData();
420 
421  if (!TokStart) {
422  // Compute the start of the token in the input lexer buffer.
423  bool CharDataInvalid = false;
424  TokStart = SourceMgr.getCharacterData(Tok.getLocation(), &CharDataInvalid);
425  if (Invalid)
426  *Invalid = CharDataInvalid;
427  if (CharDataInvalid) {
428  Buffer = "";
429  return 0;
430  }
431  }
432 
433  // If this token contains nothing interesting, return it directly.
434  if (!Tok.needsCleaning()) {
435  Buffer = TokStart;
436  return Tok.getLength();
437  }
438 
439  // Otherwise, hard case, relex the characters into the string.
440  return getSpellingSlow(Tok, TokStart, LangOpts, const_cast<char*>(Buffer));
441 }
442 
443 /// MeasureTokenLength - Relex the token at the specified location and return
444 /// its length in bytes in the input file. If the token needs cleaning (e.g.
445 /// includes a trigraph or an escaped newline) then this count includes bytes
446 /// that are part of that.
448  const SourceManager &SM,
449  const LangOptions &LangOpts) {
450  Token TheTok;
451  if (getRawToken(Loc, TheTok, SM, LangOpts))
452  return 0;
453  return TheTok.getLength();
454 }
455 
456 /// Relex the token at the specified location.
457 /// \returns true if there was a failure, false on success.
459  const SourceManager &SM,
460  const LangOptions &LangOpts,
461  bool IgnoreWhiteSpace) {
462  // TODO: this could be special cased for common tokens like identifiers, ')',
463  // etc to make this faster, if it mattered. Just look at StrData[0] to handle
464  // all obviously single-char tokens. This could use
465  // Lexer::isObviouslySimpleCharacter for example to handle identifiers or
466  // something.
467 
468  // If this comes from a macro expansion, we really do want the macro name, not
469  // the token this macro expanded to.
470  Loc = SM.getExpansionLoc(Loc);
471  std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
472  bool Invalid = false;
473  StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
474  if (Invalid)
475  return true;
476 
477  const char *StrData = Buffer.data()+LocInfo.second;
478 
479  if (!IgnoreWhiteSpace && isWhitespace(StrData[0]))
480  return true;
481 
482  // Create a lexer starting at the beginning of this token.
483  Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts,
484  Buffer.begin(), StrData, Buffer.end());
485  TheLexer.SetCommentRetentionState(true);
486  TheLexer.LexFromRawLexer(Result);
487  return false;
488 }
489 
490 /// Returns the pointer that points to the beginning of line that contains
491 /// the given offset, or null if the offset if invalid.
492 static const char *findBeginningOfLine(StringRef Buffer, unsigned Offset) {
493  const char *BufStart = Buffer.data();
494  if (Offset >= Buffer.size())
495  return nullptr;
496 
497  const char *LexStart = BufStart + Offset;
498  for (; LexStart != BufStart; --LexStart) {
499  if (isVerticalWhitespace(LexStart[0]) &&
500  !Lexer::isNewLineEscaped(BufStart, LexStart)) {
501  // LexStart should point at first character of logical line.
502  ++LexStart;
503  break;
504  }
505  }
506  return LexStart;
507 }
508 
510  const SourceManager &SM,
511  const LangOptions &LangOpts) {
512  assert(Loc.isFileID());
513  std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
514  if (LocInfo.first.isInvalid())
515  return Loc;
516 
517  bool Invalid = false;
518  StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
519  if (Invalid)
520  return Loc;
521 
522  // Back up from the current location until we hit the beginning of a line
523  // (or the buffer). We'll relex from that point.
524  const char *StrData = Buffer.data() + LocInfo.second;
525  const char *LexStart = findBeginningOfLine(Buffer, LocInfo.second);
526  if (!LexStart || LexStart == StrData)
527  return Loc;
528 
529  // Create a lexer starting at the beginning of this token.
530  SourceLocation LexerStartLoc = Loc.getLocWithOffset(-LocInfo.second);
531  Lexer TheLexer(LexerStartLoc, LangOpts, Buffer.data(), LexStart,
532  Buffer.end());
533  TheLexer.SetCommentRetentionState(true);
534 
535  // Lex tokens until we find the token that contains the source location.
536  Token TheTok;
537  do {
538  TheLexer.LexFromRawLexer(TheTok);
539 
540  if (TheLexer.getBufferLocation() > StrData) {
541  // Lexing this token has taken the lexer past the source location we're
542  // looking for. If the current token encompasses our source location,
543  // return the beginning of that token.
544  if (TheLexer.getBufferLocation() - TheTok.getLength() <= StrData)
545  return TheTok.getLocation();
546 
547  // We ended up skipping over the source location entirely, which means
548  // that it points into whitespace. We're done here.
549  break;
550  }
551  } while (TheTok.getKind() != tok::eof);
552 
553  // We've passed our source location; just return the original source location.
554  return Loc;
555 }
556 
558  const SourceManager &SM,
559  const LangOptions &LangOpts) {
560  if (Loc.isFileID())
561  return getBeginningOfFileToken(Loc, SM, LangOpts);
562 
563  if (!SM.isMacroArgExpansion(Loc))
564  return Loc;
565 
566  SourceLocation FileLoc = SM.getSpellingLoc(Loc);
567  SourceLocation BeginFileLoc = getBeginningOfFileToken(FileLoc, SM, LangOpts);
568  std::pair<FileID, unsigned> FileLocInfo = SM.getDecomposedLoc(FileLoc);
569  std::pair<FileID, unsigned> BeginFileLocInfo =
570  SM.getDecomposedLoc(BeginFileLoc);
571  assert(FileLocInfo.first == BeginFileLocInfo.first &&
572  FileLocInfo.second >= BeginFileLocInfo.second);
573  return Loc.getLocWithOffset(BeginFileLocInfo.second - FileLocInfo.second);
574 }
575 
576 namespace {
577 
578 enum PreambleDirectiveKind {
579  PDK_Skipped,
580  PDK_Unknown
581 };
582 
583 } // namespace
584 
586  const LangOptions &LangOpts,
587  unsigned MaxLines) {
588  // Create a lexer starting at the beginning of the file. Note that we use a
589  // "fake" file source location at offset 1 so that the lexer will track our
590  // position within the file.
591  const SourceLocation::UIntTy StartOffset = 1;
592  SourceLocation FileLoc = SourceLocation::getFromRawEncoding(StartOffset);
593  Lexer TheLexer(FileLoc, LangOpts, Buffer.begin(), Buffer.begin(),
594  Buffer.end());
595  TheLexer.SetCommentRetentionState(true);
596 
597  bool InPreprocessorDirective = false;
598  Token TheTok;
599  SourceLocation ActiveCommentLoc;
600 
601  unsigned MaxLineOffset = 0;
602  if (MaxLines) {
603  const char *CurPtr = Buffer.begin();
604  unsigned CurLine = 0;
605  while (CurPtr != Buffer.end()) {
606  char ch = *CurPtr++;
607  if (ch == '\n') {
608  ++CurLine;
609  if (CurLine == MaxLines)
610  break;
611  }
612  }
613  if (CurPtr != Buffer.end())
614  MaxLineOffset = CurPtr - Buffer.begin();
615  }
616 
617  do {
618  TheLexer.LexFromRawLexer(TheTok);
619 
620  if (InPreprocessorDirective) {
621  // If we've hit the end of the file, we're done.
622  if (TheTok.getKind() == tok::eof) {
623  break;
624  }
625 
626  // If we haven't hit the end of the preprocessor directive, skip this
627  // token.
628  if (!TheTok.isAtStartOfLine())
629  continue;
630 
631  // We've passed the end of the preprocessor directive, and will look
632  // at this token again below.
633  InPreprocessorDirective = false;
634  }
635 
636  // Keep track of the # of lines in the preamble.
637  if (TheTok.isAtStartOfLine()) {
638  unsigned TokOffset = TheTok.getLocation().getRawEncoding() - StartOffset;
639 
640  // If we were asked to limit the number of lines in the preamble,
641  // and we're about to exceed that limit, we're done.
642  if (MaxLineOffset && TokOffset >= MaxLineOffset)
643  break;
644  }
645 
646  // Comments are okay; skip over them.
647  if (TheTok.getKind() == tok::comment) {
648  if (ActiveCommentLoc.isInvalid())
649  ActiveCommentLoc = TheTok.getLocation();
650  continue;
651  }
652 
653  if (TheTok.isAtStartOfLine() && TheTok.getKind() == tok::hash) {
654  // This is the start of a preprocessor directive.
655  Token HashTok = TheTok;
656  InPreprocessorDirective = true;
657  ActiveCommentLoc = SourceLocation();
658 
659  // Figure out which directive this is. Since we're lexing raw tokens,
660  // we don't have an identifier table available. Instead, just look at
661  // the raw identifier to recognize and categorize preprocessor directives.
662  TheLexer.LexFromRawLexer(TheTok);
663  if (TheTok.getKind() == tok::raw_identifier && !TheTok.needsCleaning()) {
664  StringRef Keyword = TheTok.getRawIdentifier();
665  PreambleDirectiveKind PDK
666  = llvm::StringSwitch<PreambleDirectiveKind>(Keyword)
667  .Case("include", PDK_Skipped)
668  .Case("__include_macros", PDK_Skipped)
669  .Case("define", PDK_Skipped)
670  .Case("undef", PDK_Skipped)
671  .Case("line", PDK_Skipped)
672  .Case("error", PDK_Skipped)
673  .Case("pragma", PDK_Skipped)
674  .Case("import", PDK_Skipped)
675  .Case("include_next", PDK_Skipped)
676  .Case("warning", PDK_Skipped)
677  .Case("ident", PDK_Skipped)
678  .Case("sccs", PDK_Skipped)
679  .Case("assert", PDK_Skipped)
680  .Case("unassert", PDK_Skipped)
681  .Case("if", PDK_Skipped)
682  .Case("ifdef", PDK_Skipped)
683  .Case("ifndef", PDK_Skipped)
684  .Case("elif", PDK_Skipped)
685  .Case("elifdef", PDK_Skipped)
686  .Case("elifndef", PDK_Skipped)
687  .Case("else", PDK_Skipped)
688  .Case("endif", PDK_Skipped)
689  .Default(PDK_Unknown);
690 
691  switch (PDK) {
692  case PDK_Skipped:
693  continue;
694 
695  case PDK_Unknown:
696  // We don't know what this directive is; stop at the '#'.
697  break;
698  }
699  }
700 
701  // We only end up here if we didn't recognize the preprocessor
702  // directive or it was one that can't occur in the preamble at this
703  // point. Roll back the current token to the location of the '#'.
704  TheTok = HashTok;
705  }
706 
707  // We hit a token that we don't recognize as being in the
708  // "preprocessing only" part of the file, so we're no longer in
709  // the preamble.
710  break;
711  } while (true);
712 
714  if (ActiveCommentLoc.isValid())
715  End = ActiveCommentLoc; // don't truncate a decl comment.
716  else
717  End = TheTok.getLocation();
718 
719  return PreambleBounds(End.getRawEncoding() - FileLoc.getRawEncoding(),
720  TheTok.isAtStartOfLine());
721 }
722 
723 unsigned Lexer::getTokenPrefixLength(SourceLocation TokStart, unsigned CharNo,
724  const SourceManager &SM,
725  const LangOptions &LangOpts) {
726  // Figure out how many physical characters away the specified expansion
727  // character is. This needs to take into consideration newlines and
728  // trigraphs.
729  bool Invalid = false;
730  const char *TokPtr = SM.getCharacterData(TokStart, &Invalid);
731 
732  // If they request the first char of the token, we're trivially done.
733  if (Invalid || (CharNo == 0 && Lexer::isObviouslySimpleCharacter(*TokPtr)))
734  return 0;
735 
736  unsigned PhysOffset = 0;
737 
738  // The usual case is that tokens don't contain anything interesting. Skip
739  // over the uninteresting characters. If a token only consists of simple
740  // chars, this method is extremely fast.
741  while (Lexer::isObviouslySimpleCharacter(*TokPtr)) {
742  if (CharNo == 0)
743  return PhysOffset;
744  ++TokPtr;
745  --CharNo;
746  ++PhysOffset;
747  }
748 
749  // If we have a character that may be a trigraph or escaped newline, use a
750  // lexer to parse it correctly.
751  for (; CharNo; --CharNo) {
752  unsigned Size;
753  Lexer::getCharAndSizeNoWarn(TokPtr, Size, LangOpts);
754  TokPtr += Size;
755  PhysOffset += Size;
756  }
757 
758  // Final detail: if we end up on an escaped newline, we want to return the
759  // location of the actual byte of the token. For example foo<newline>bar
760  // advanced by 3 should return the location of b, not of \\. One compounding
761  // detail of this is that the escape may be made by a trigraph.
762  if (!Lexer::isObviouslySimpleCharacter(*TokPtr))
763  PhysOffset += Lexer::SkipEscapedNewLines(TokPtr)-TokPtr;
764 
765  return PhysOffset;
766 }
767 
768 /// Computes the source location just past the end of the
769 /// token at this source location.
770 ///
771 /// This routine can be used to produce a source location that
772 /// points just past the end of the token referenced by \p Loc, and
773 /// is generally used when a diagnostic needs to point just after a
774 /// token where it expected something different that it received. If
775 /// the returned source location would not be meaningful (e.g., if
776 /// it points into a macro), this routine returns an invalid
777 /// source location.
778 ///
779 /// \param Offset an offset from the end of the token, where the source
780 /// location should refer to. The default offset (0) produces a source
781 /// location pointing just past the end of the token; an offset of 1 produces
782 /// a source location pointing to the last character in the token, etc.
784  const SourceManager &SM,
785  const LangOptions &LangOpts) {
786  if (Loc.isInvalid())
787  return {};
788 
789  if (Loc.isMacroID()) {
790  if (Offset > 0 || !isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
791  return {}; // Points inside the macro expansion.
792  }
793 
794  unsigned Len = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
795  if (Len > Offset)
796  Len = Len - Offset;
797  else
798  return Loc;
799 
800  return Loc.getLocWithOffset(Len);
801 }
802 
803 /// Returns true if the given MacroID location points at the first
804 /// token of the macro expansion.
806  const SourceManager &SM,
807  const LangOptions &LangOpts,
808  SourceLocation *MacroBegin) {
809  assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
810 
811  SourceLocation expansionLoc;
812  if (!SM.isAtStartOfImmediateMacroExpansion(loc, &expansionLoc))
813  return false;
814 
815  if (expansionLoc.isFileID()) {
816  // No other macro expansions, this is the first.
817  if (MacroBegin)
818  *MacroBegin = expansionLoc;
819  return true;
820  }
821 
822  return isAtStartOfMacroExpansion(expansionLoc, SM, LangOpts, MacroBegin);
823 }
824 
825 /// Returns true if the given MacroID location points at the last
826 /// token of the macro expansion.
828  const SourceManager &SM,
829  const LangOptions &LangOpts,
830  SourceLocation *MacroEnd) {
831  assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
832 
833  SourceLocation spellLoc = SM.getSpellingLoc(loc);
834  unsigned tokLen = MeasureTokenLength(spellLoc, SM, LangOpts);
835  if (tokLen == 0)
836  return false;
837 
838  SourceLocation afterLoc = loc.getLocWithOffset(tokLen);
839  SourceLocation expansionLoc;
840  if (!SM.isAtEndOfImmediateMacroExpansion(afterLoc, &expansionLoc))
841  return false;
842 
843  if (expansionLoc.isFileID()) {
844  // No other macro expansions.
845  if (MacroEnd)
846  *MacroEnd = expansionLoc;
847  return true;
848  }
849 
850  return isAtEndOfMacroExpansion(expansionLoc, SM, LangOpts, MacroEnd);
851 }
852 
854  const SourceManager &SM,
855  const LangOptions &LangOpts) {
856  SourceLocation Begin = Range.getBegin();
857  SourceLocation End = Range.getEnd();
858  assert(Begin.isFileID() && End.isFileID());
859  if (Range.isTokenRange()) {
860  End = Lexer::getLocForEndOfToken(End, 0, SM,LangOpts);
861  if (End.isInvalid())
862  return {};
863  }
864 
865  // Break down the source locations.
866  FileID FID;
867  unsigned BeginOffs;
868  std::tie(FID, BeginOffs) = SM.getDecomposedLoc(Begin);
869  if (FID.isInvalid())
870  return {};
871 
872  unsigned EndOffs;
873  if (!SM.isInFileID(End, FID, &EndOffs) ||
874  BeginOffs > EndOffs)
875  return {};
876 
878 }
879 
880 // Assumes that `Loc` is in an expansion.
882  const SourceManager &SM) {
883  return SM.getSLocEntry(SM.getFileID(Loc))
884  .getExpansion()
885  .isExpansionTokenRange();
886 }
887 
889  const SourceManager &SM,
890  const LangOptions &LangOpts) {
891  SourceLocation Begin = Range.getBegin();
892  SourceLocation End = Range.getEnd();
893  if (Begin.isInvalid() || End.isInvalid())
894  return {};
895 
896  if (Begin.isFileID() && End.isFileID())
897  return makeRangeFromFileLocs(Range, SM, LangOpts);
898 
899  if (Begin.isMacroID() && End.isFileID()) {
900  if (!isAtStartOfMacroExpansion(Begin, SM, LangOpts, &Begin))
901  return {};
902  Range.setBegin(Begin);
903  return makeRangeFromFileLocs(Range, SM, LangOpts);
904  }
905 
906  if (Begin.isFileID() && End.isMacroID()) {
907  if (Range.isTokenRange()) {
908  if (!isAtEndOfMacroExpansion(End, SM, LangOpts, &End))
909  return {};
910  // Use the *original* end, not the expanded one in `End`.
911  Range.setTokenRange(isInExpansionTokenRange(Range.getEnd(), SM));
912  } else if (!isAtStartOfMacroExpansion(End, SM, LangOpts, &End))
913  return {};
914  Range.setEnd(End);
915  return makeRangeFromFileLocs(Range, SM, LangOpts);
916  }
917 
918  assert(Begin.isMacroID() && End.isMacroID());
919  SourceLocation MacroBegin, MacroEnd;
920  if (isAtStartOfMacroExpansion(Begin, SM, LangOpts, &MacroBegin) &&
921  ((Range.isTokenRange() && isAtEndOfMacroExpansion(End, SM, LangOpts,
922  &MacroEnd)) ||
923  (Range.isCharRange() && isAtStartOfMacroExpansion(End, SM, LangOpts,
924  &MacroEnd)))) {
925  Range.setBegin(MacroBegin);
926  Range.setEnd(MacroEnd);
927  // Use the *original* `End`, not the expanded one in `MacroEnd`.
928  if (Range.isTokenRange())
929  Range.setTokenRange(isInExpansionTokenRange(End, SM));
930  return makeRangeFromFileLocs(Range, SM, LangOpts);
931  }
932 
933  bool Invalid = false;
934  const SrcMgr::SLocEntry &BeginEntry = SM.getSLocEntry(SM.getFileID(Begin),
935  &Invalid);
936  if (Invalid)
937  return {};
938 
939  if (BeginEntry.getExpansion().isMacroArgExpansion()) {
940  const SrcMgr::SLocEntry &EndEntry = SM.getSLocEntry(SM.getFileID(End),
941  &Invalid);
942  if (Invalid)
943  return {};
944 
945  if (EndEntry.getExpansion().isMacroArgExpansion() &&
946  BeginEntry.getExpansion().getExpansionLocStart() ==
947  EndEntry.getExpansion().getExpansionLocStart()) {
948  Range.setBegin(SM.getImmediateSpellingLoc(Begin));
949  Range.setEnd(SM.getImmediateSpellingLoc(End));
950  return makeFileCharRange(Range, SM, LangOpts);
951  }
952  }
953 
954  return {};
955 }
956 
958  const SourceManager &SM,
959  const LangOptions &LangOpts,
960  bool *Invalid) {
961  Range = makeFileCharRange(Range, SM, LangOpts);
962  if (Range.isInvalid()) {
963  if (Invalid) *Invalid = true;
964  return {};
965  }
966 
967  // Break down the source location.
968  std::pair<FileID, unsigned> beginInfo = SM.getDecomposedLoc(Range.getBegin());
969  if (beginInfo.first.isInvalid()) {
970  if (Invalid) *Invalid = true;
971  return {};
972  }
973 
974  unsigned EndOffs;
975  if (!SM.isInFileID(Range.getEnd(), beginInfo.first, &EndOffs) ||
976  beginInfo.second > EndOffs) {
977  if (Invalid) *Invalid = true;
978  return {};
979  }
980 
981  // Try to the load the file buffer.
982  bool invalidTemp = false;
983  StringRef file = SM.getBufferData(beginInfo.first, &invalidTemp);
984  if (invalidTemp) {
985  if (Invalid) *Invalid = true;
986  return {};
987  }
988 
989  if (Invalid) *Invalid = false;
990  return file.substr(beginInfo.second, EndOffs - beginInfo.second);
991 }
992 
994  const SourceManager &SM,
995  const LangOptions &LangOpts) {
996  assert(Loc.isMacroID() && "Only reasonable to call this on macros");
997 
998  // Find the location of the immediate macro expansion.
999  while (true) {
1000  FileID FID = SM.getFileID(Loc);
1001  const SrcMgr::SLocEntry *E = &SM.getSLocEntry(FID);
1002  const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
1003  Loc = Expansion.getExpansionLocStart();
1004  if (!Expansion.isMacroArgExpansion())
1005  break;
1006 
1007  // For macro arguments we need to check that the argument did not come
1008  // from an inner macro, e.g: "MAC1( MAC2(foo) )"
1009 
1010  // Loc points to the argument id of the macro definition, move to the
1011  // macro expansion.
1012  Loc = SM.getImmediateExpansionRange(Loc).getBegin();
1013  SourceLocation SpellLoc = Expansion.getSpellingLoc();
1014  if (SpellLoc.isFileID())
1015  break; // No inner macro.
1016 
1017  // If spelling location resides in the same FileID as macro expansion
1018  // location, it means there is no inner macro.
1019  FileID MacroFID = SM.getFileID(Loc);
1020  if (SM.isInFileID(SpellLoc, MacroFID))
1021  break;
1022 
1023  // Argument came from inner macro.
1024  Loc = SpellLoc;
1025  }
1026 
1027  // Find the spelling location of the start of the non-argument expansion
1028  // range. This is where the macro name was spelled in order to begin
1029  // expanding this macro.
1030  Loc = SM.getSpellingLoc(Loc);
1031 
1032  // Dig out the buffer where the macro name was spelled and the extents of the
1033  // name so that we can render it into the expansion note.
1034  std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
1035  unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
1036  StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
1037  return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
1038 }
1039 
1041  SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts) {
1042  assert(Loc.isMacroID() && "Only reasonable to call this on macros");
1043  // Walk past macro argument expansions.
1044  while (SM.isMacroArgExpansion(Loc))
1045  Loc = SM.getImmediateExpansionRange(Loc).getBegin();
1046 
1047  // If the macro's spelling has no FileID, then it's actually a token paste
1048  // or stringization (or similar) and not a macro at all.
1049  if (!SM.getFileEntryForID(SM.getFileID(SM.getSpellingLoc(Loc))))
1050  return {};
1051 
1052  // Find the spelling location of the start of the non-argument expansion
1053  // range. This is where the macro name was spelled in order to begin
1054  // expanding this macro.
1055  Loc = SM.getSpellingLoc(SM.getImmediateExpansionRange(Loc).getBegin());
1056 
1057  // Dig out the buffer where the macro name was spelled and the extents of the
1058  // name so that we can render it into the expansion note.
1059  std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
1060  unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
1061  StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
1062  return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
1063 }
1064 
1066  return isAsciiIdentifierContinue(c, LangOpts.DollarIdents);
1067 }
1068 
1069 bool Lexer::isNewLineEscaped(const char *BufferStart, const char *Str) {
1070  assert(isVerticalWhitespace(Str[0]));
1071  if (Str - 1 < BufferStart)
1072  return false;
1073 
1074  if ((Str[0] == '\n' && Str[-1] == '\r') ||
1075  (Str[0] == '\r' && Str[-1] == '\n')) {
1076  if (Str - 2 < BufferStart)
1077  return false;
1078  --Str;
1079  }
1080  --Str;
1081 
1082  // Rewind to first non-space character:
1083  while (Str > BufferStart && isHorizontalWhitespace(*Str))
1084  --Str;
1085 
1086  return *Str == '\\';
1087 }
1088 
1090  const SourceManager &SM) {
1091  if (Loc.isInvalid() || Loc.isMacroID())
1092  return {};
1093  std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1094  if (LocInfo.first.isInvalid())
1095  return {};
1096  bool Invalid = false;
1097  StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
1098  if (Invalid)
1099  return {};
1100  const char *Line = findBeginningOfLine(Buffer, LocInfo.second);
1101  if (!Line)
1102  return {};
1103  StringRef Rest = Buffer.substr(Line - Buffer.data());
1104  size_t NumWhitespaceChars = Rest.find_first_not_of(" \t");
1105  return NumWhitespaceChars == StringRef::npos
1106  ? ""
1107  : Rest.take_front(NumWhitespaceChars);
1108 }
1109 
1110 //===----------------------------------------------------------------------===//
1111 // Diagnostics forwarding code.
1112 //===----------------------------------------------------------------------===//
1113 
1114 /// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
1115 /// lexer buffer was all expanded at a single point, perform the mapping.
1116 /// This is currently only used for _Pragma implementation, so it is the slow
1117 /// path of the hot getSourceLocation method. Do not allow it to be inlined.
1118 static LLVM_ATTRIBUTE_NOINLINE SourceLocation GetMappedTokenLoc(
1119  Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen);
1121  SourceLocation FileLoc,
1122  unsigned CharNo, unsigned TokLen) {
1123  assert(FileLoc.isMacroID() && "Must be a macro expansion");
1124 
1125  // Otherwise, we're lexing "mapped tokens". This is used for things like
1126  // _Pragma handling. Combine the expansion location of FileLoc with the
1127  // spelling location.
1129 
1130  // Create a new SLoc which is expanded from Expansion(FileLoc) but whose
1131  // characters come from spelling(FileLoc)+Offset.
1132  SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc);
1133  SpellingLoc = SpellingLoc.getLocWithOffset(CharNo);
1134 
1135  // Figure out the expansion loc range, which is the range covered by the
1136  // original _Pragma(...) sequence.
1137  CharSourceRange II = SM.getImmediateExpansionRange(FileLoc);
1138 
1139  return SM.createExpansionLoc(SpellingLoc, II.getBegin(), II.getEnd(), TokLen);
1140 }
1141 
1142 /// getSourceLocation - Return a source location identifier for the specified
1143 /// offset in the current file.
1145  unsigned TokLen) const {
1146  assert(Loc >= BufferStart && Loc <= BufferEnd &&
1147  "Location out of range for this buffer!");
1148 
1149  // In the normal case, we're just lexing from a simple file buffer, return
1150  // the file id from FileLoc with the offset specified.
1151  unsigned CharNo = Loc-BufferStart;
1152  if (FileLoc.isFileID())
1153  return FileLoc.getLocWithOffset(CharNo);
1154 
1155  // Otherwise, this is the _Pragma lexer case, which pretends that all of the
1156  // tokens are lexed from where the _Pragma was defined.
1157  assert(PP && "This doesn't work on raw lexers");
1158  return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen);
1159 }
1160 
1161 /// Diag - Forwarding function for diagnostics. This translate a source
1162 /// position in the current buffer into a SourceLocation object for rendering.
1163 DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
1164  return PP->Diag(getSourceLocation(Loc), DiagID);
1165 }
1166 
1167 //===----------------------------------------------------------------------===//
1168 // Trigraph and Escaped Newline Handling Code.
1169 //===----------------------------------------------------------------------===//
1170 
1171 /// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
1172 /// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
1173 static char GetTrigraphCharForLetter(char Letter) {
1174  switch (Letter) {
1175  default: return 0;
1176  case '=': return '#';
1177  case ')': return ']';
1178  case '(': return '[';
1179  case '!': return '|';
1180  case '\'': return '^';
1181  case '>': return '}';
1182  case '/': return '\\';
1183  case '<': return '{';
1184  case '-': return '~';
1185  }
1186 }
1187 
1188 /// DecodeTrigraphChar - If the specified character is a legal trigraph when
1189 /// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
1190 /// return the result character. Finally, emit a warning about trigraph use
1191 /// whether trigraphs are enabled or not.
1192 static char DecodeTrigraphChar(const char *CP, Lexer *L) {
1193  char Res = GetTrigraphCharForLetter(*CP);
1194  if (!Res || !L) return Res;
1195 
1196  if (!L->getLangOpts().Trigraphs) {
1197  if (!L->isLexingRawMode())
1198  L->Diag(CP-2, diag::trigraph_ignored);
1199  return 0;
1200  }
1201 
1202  if (!L->isLexingRawMode())
1203  L->Diag(CP-2, diag::trigraph_converted) << StringRef(&Res, 1);
1204  return Res;
1205 }
1206 
1207 /// getEscapedNewLineSize - Return the size of the specified escaped newline,
1208 /// or 0 if it is not an escaped newline. P[-1] is known to be a "\" or a
1209 /// trigraph equivalent on entry to this function.
1210 unsigned Lexer::getEscapedNewLineSize(const char *Ptr) {
1211  unsigned Size = 0;
1212  while (isWhitespace(Ptr[Size])) {
1213  ++Size;
1214 
1215  if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r')
1216  continue;
1217 
1218  // If this is a \r\n or \n\r, skip the other half.
1219  if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') &&
1220  Ptr[Size-1] != Ptr[Size])
1221  ++Size;
1222 
1223  return Size;
1224  }
1225 
1226  // Not an escaped newline, must be a \t or something else.
1227  return 0;
1228 }
1229 
1230 /// SkipEscapedNewLines - If P points to an escaped newline (or a series of
1231 /// them), skip over them and return the first non-escaped-newline found,
1232 /// otherwise return P.
1233 const char *Lexer::SkipEscapedNewLines(const char *P) {
1234  while (true) {
1235  const char *AfterEscape;
1236  if (*P == '\\') {
1237  AfterEscape = P+1;
1238  } else if (*P == '?') {
1239  // If not a trigraph for escape, bail out.
1240  if (P[1] != '?' || P[2] != '/')
1241  return P;
1242  // FIXME: Take LangOpts into account; the language might not
1243  // support trigraphs.
1244  AfterEscape = P+3;
1245  } else {
1246  return P;
1247  }
1248 
1249  unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape);
1250  if (NewLineSize == 0) return P;
1251  P = AfterEscape+NewLineSize;
1252  }
1253 }
1254 
1256  const SourceManager &SM,
1257  const LangOptions &LangOpts) {
1258  if (Loc.isMacroID()) {
1259  if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
1260  return None;
1261  }
1262  Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts);
1263 
1264  // Break down the source location.
1265  std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1266 
1267  // Try to load the file buffer.
1268  bool InvalidTemp = false;
1269  StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
1270  if (InvalidTemp)
1271  return None;
1272 
1273  const char *TokenBegin = File.data() + LocInfo.second;
1274 
1275  // Lex from the start of the given location.
1276  Lexer lexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
1277  TokenBegin, File.end());
1278  // Find the token.
1279  Token Tok;
1280  lexer.LexFromRawLexer(Tok);
1281  return Tok;
1282 }
1283 
1284 /// Checks that the given token is the first token that occurs after the
1285 /// given location (this excludes comments and whitespace). Returns the location
1286 /// immediately after the specified token. If the token is not found or the
1287 /// location is inside a macro, the returned source location will be invalid.
1289  SourceLocation Loc, tok::TokenKind TKind, const SourceManager &SM,
1290  const LangOptions &LangOpts, bool SkipTrailingWhitespaceAndNewLine) {
1291  Optional<Token> Tok = findNextToken(Loc, SM, LangOpts);
1292  if (!Tok || Tok->isNot(TKind))
1293  return {};
1294  SourceLocation TokenLoc = Tok->getLocation();
1295 
1296  // Calculate how much whitespace needs to be skipped if any.
1297  unsigned NumWhitespaceChars = 0;
1298  if (SkipTrailingWhitespaceAndNewLine) {
1299  const char *TokenEnd = SM.getCharacterData(TokenLoc) + Tok->getLength();
1300  unsigned char C = *TokenEnd;
1301  while (isHorizontalWhitespace(C)) {
1302  C = *(++TokenEnd);
1303  NumWhitespaceChars++;
1304  }
1305 
1306  // Skip \r, \n, \r\n, or \n\r
1307  if (C == '\n' || C == '\r') {
1308  char PrevC = C;
1309  C = *(++TokenEnd);
1310  NumWhitespaceChars++;
1311  if ((C == '\n' || C == '\r') && C != PrevC)
1312  NumWhitespaceChars++;
1313  }
1314  }
1315 
1316  return TokenLoc.getLocWithOffset(Tok->getLength() + NumWhitespaceChars);
1317 }
1318 
1319 /// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
1320 /// get its size, and return it. This is tricky in several cases:
1321 /// 1. If currently at the start of a trigraph, we warn about the trigraph,
1322 /// then either return the trigraph (skipping 3 chars) or the '?',
1323 /// depending on whether trigraphs are enabled or not.
1324 /// 2. If this is an escaped newline (potentially with whitespace between
1325 /// the backslash and newline), implicitly skip the newline and return
1326 /// the char after it.
1327 ///
1328 /// This handles the slow/uncommon case of the getCharAndSize method. Here we
1329 /// know that we can accumulate into Size, and that we have already incremented
1330 /// Ptr by Size bytes.
1331 ///
1332 /// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
1333 /// be updated to match.
1334 char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
1335  Token *Tok) {
1336  // If we have a slash, look for an escaped newline.
1337  if (Ptr[0] == '\\') {
1338  ++Size;
1339  ++Ptr;
1340 Slash:
1341  // Common case, backslash-char where the char is not whitespace.
1342  if (!isWhitespace(Ptr[0])) return '\\';
1343 
1344  // See if we have optional whitespace characters between the slash and
1345  // newline.
1346  if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1347  // Remember that this token needs to be cleaned.
1348  if (Tok) Tok->setFlag(Token::NeedsCleaning);
1349 
1350  // Warn if there was whitespace between the backslash and newline.
1351  if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode())
1352  Diag(Ptr, diag::backslash_newline_space);
1353 
1354  // Found backslash<whitespace><newline>. Parse the char after it.
1355  Size += EscapedNewLineSize;
1356  Ptr += EscapedNewLineSize;
1357 
1358  // Use slow version to accumulate a correct size field.
1359  return getCharAndSizeSlow(Ptr, Size, Tok);
1360  }
1361 
1362  // Otherwise, this is not an escaped newline, just return the slash.
1363  return '\\';
1364  }
1365 
1366  // If this is a trigraph, process it.
1367  if (Ptr[0] == '?' && Ptr[1] == '?') {
1368  // If this is actually a legal trigraph (not something like "??x"), emit
1369  // a trigraph warning. If so, and if trigraphs are enabled, return it.
1370  if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : nullptr)) {
1371  // Remember that this token needs to be cleaned.
1372  if (Tok) Tok->setFlag(Token::NeedsCleaning);
1373 
1374  Ptr += 3;
1375  Size += 3;
1376  if (C == '\\') goto Slash;
1377  return C;
1378  }
1379  }
1380 
1381  // If this is neither, return a single character.
1382  ++Size;
1383  return *Ptr;
1384 }
1385 
1386 /// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
1387 /// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
1388 /// and that we have already incremented Ptr by Size bytes.
1389 ///
1390 /// NOTE: When this method is updated, getCharAndSizeSlow (above) should
1391 /// be updated to match.
1392 char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
1393  const LangOptions &LangOpts) {
1394  // If we have a slash, look for an escaped newline.
1395  if (Ptr[0] == '\\') {
1396  ++Size;
1397  ++Ptr;
1398 Slash:
1399  // Common case, backslash-char where the char is not whitespace.
1400  if (!isWhitespace(Ptr[0])) return '\\';
1401 
1402  // See if we have optional whitespace characters followed by a newline.
1403  if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1404  // Found backslash<whitespace><newline>. Parse the char after it.
1405  Size += EscapedNewLineSize;
1406  Ptr += EscapedNewLineSize;
1407 
1408  // Use slow version to accumulate a correct size field.
1409  return getCharAndSizeSlowNoWarn(Ptr, Size, LangOpts);
1410  }
1411 
1412  // Otherwise, this is not an escaped newline, just return the slash.
1413  return '\\';
1414  }
1415 
1416  // If this is a trigraph, process it.
1417  if (LangOpts.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
1418  // If this is actually a legal trigraph (not something like "??x"), return
1419  // it.
1420  if (char C = GetTrigraphCharForLetter(Ptr[2])) {
1421  Ptr += 3;
1422  Size += 3;
1423  if (C == '\\') goto Slash;
1424  return C;
1425  }
1426  }
1427 
1428  // If this is neither, return a single character.
1429  ++Size;
1430  return *Ptr;
1431 }
1432 
1433 //===----------------------------------------------------------------------===//
1434 // Helper methods for lexing.
1435 //===----------------------------------------------------------------------===//
1436 
1437 /// Routine that indiscriminately sets the offset into the source file.
1438 void Lexer::SetByteOffset(unsigned Offset, bool StartOfLine) {
1439  BufferPtr = BufferStart + Offset;
1440  if (BufferPtr > BufferEnd)
1441  BufferPtr = BufferEnd;
1442  // FIXME: What exactly does the StartOfLine bit mean? There are two
1443  // possible meanings for the "start" of the line: the first token on the
1444  // unexpanded line, or the first token on the expanded line.
1445  IsAtStartOfLine = StartOfLine;
1446  IsAtPhysicalStartOfLine = StartOfLine;
1447 }
1448 
1449 static bool isUnicodeWhitespace(uint32_t Codepoint) {
1450  static const llvm::sys::UnicodeCharSet UnicodeWhitespaceChars(
1452  return UnicodeWhitespaceChars.contains(Codepoint);
1453 }
1454 
1455 static bool isAllowedIDChar(uint32_t C, const LangOptions &LangOpts) {
1456  if (LangOpts.AsmPreprocessor) {
1457  return false;
1458  } else if (LangOpts.DollarIdents && '$' == C) {
1459  return true;
1460  } else if (LangOpts.CPlusPlus) {
1461  // A non-leading codepoint must have the XID_Continue property.
1462  // XIDContinueRanges doesn't contains characters also in XIDStartRanges,
1463  // so we need to check both tables.
1464  // '_' doesn't have the XID_Continue property but is allowed in C++.
1465  static const llvm::sys::UnicodeCharSet XIDStartChars(XIDStartRanges);
1466  static const llvm::sys::UnicodeCharSet XIDContinueChars(XIDContinueRanges);
1467  return C == '_' || XIDStartChars.contains(C) ||
1468  XIDContinueChars.contains(C);
1469  } else if (LangOpts.C11) {
1470  static const llvm::sys::UnicodeCharSet C11AllowedIDChars(
1472  return C11AllowedIDChars.contains(C);
1473  } else {
1474  static const llvm::sys::UnicodeCharSet C99AllowedIDChars(
1476  return C99AllowedIDChars.contains(C);
1477  }
1478 }
1479 
1480 static bool isAllowedInitiallyIDChar(uint32_t C, const LangOptions &LangOpts) {
1481  if (LangOpts.AsmPreprocessor) {
1482  return false;
1483  }
1484  if (LangOpts.CPlusPlus) {
1485  static const llvm::sys::UnicodeCharSet XIDStartChars(XIDStartRanges);
1486  // '_' doesn't have the XID_Start property but is allowed in C++.
1487  return C == '_' || XIDStartChars.contains(C);
1488  }
1489  if (!isAllowedIDChar(C, LangOpts))
1490  return false;
1491  if (LangOpts.C11) {
1492  static const llvm::sys::UnicodeCharSet C11DisallowedInitialIDChars(
1494  return !C11DisallowedInitialIDChars.contains(C);
1495  }
1496  static const llvm::sys::UnicodeCharSet C99DisallowedInitialIDChars(
1498  return !C99DisallowedInitialIDChars.contains(C);
1499 }
1500 
1501 static inline CharSourceRange makeCharRange(Lexer &L, const char *Begin,
1502  const char *End) {
1504  L.getSourceLocation(End));
1505 }
1506 
1507 static void maybeDiagnoseIDCharCompat(DiagnosticsEngine &Diags, uint32_t C,
1508  CharSourceRange Range, bool IsFirst) {
1509  // Check C99 compatibility.
1510  if (!Diags.isIgnored(diag::warn_c99_compat_unicode_id, Range.getBegin())) {
1511  enum {
1512  CannotAppearInIdentifier = 0,
1513  CannotStartIdentifier
1514  };
1515 
1516  static const llvm::sys::UnicodeCharSet C99AllowedIDChars(
1518  static const llvm::sys::UnicodeCharSet C99DisallowedInitialIDChars(
1520  if (!C99AllowedIDChars.contains(C)) {
1521  Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1522  << Range
1523  << CannotAppearInIdentifier;
1524  } else if (IsFirst && C99DisallowedInitialIDChars.contains(C)) {
1525  Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1526  << Range
1527  << CannotStartIdentifier;
1528  }
1529  }
1530 }
1531 
1532 /// After encountering UTF-8 character C and interpreting it as an identifier
1533 /// character, check whether it's a homoglyph for a common non-identifier
1534 /// source character that is unlikely to be an intentional identifier
1535 /// character and warn if so.
1536 static void maybeDiagnoseUTF8Homoglyph(DiagnosticsEngine &Diags, uint32_t C,
1537  CharSourceRange Range) {
1538  // FIXME: Handle Unicode quotation marks (smart quotes, fullwidth quotes).
1539  struct HomoglyphPair {
1540  uint32_t Character;
1541  char LooksLike;
1542  bool operator<(HomoglyphPair R) const { return Character < R.Character; }
1543  };
1544  static constexpr HomoglyphPair SortedHomoglyphs[] = {
1545  {U'\u00ad', 0}, // SOFT HYPHEN
1546  {U'\u01c3', '!'}, // LATIN LETTER RETROFLEX CLICK
1547  {U'\u037e', ';'}, // GREEK QUESTION MARK
1548  {U'\u200b', 0}, // ZERO WIDTH SPACE
1549  {U'\u200c', 0}, // ZERO WIDTH NON-JOINER
1550  {U'\u200d', 0}, // ZERO WIDTH JOINER
1551  {U'\u2060', 0}, // WORD JOINER
1552  {U'\u2061', 0}, // FUNCTION APPLICATION
1553  {U'\u2062', 0}, // INVISIBLE TIMES
1554  {U'\u2063', 0}, // INVISIBLE SEPARATOR
1555  {U'\u2064', 0}, // INVISIBLE PLUS
1556  {U'\u2212', '-'}, // MINUS SIGN
1557  {U'\u2215', '/'}, // DIVISION SLASH
1558  {U'\u2216', '\\'}, // SET MINUS
1559  {U'\u2217', '*'}, // ASTERISK OPERATOR
1560  {U'\u2223', '|'}, // DIVIDES
1561  {U'\u2227', '^'}, // LOGICAL AND
1562  {U'\u2236', ':'}, // RATIO
1563  {U'\u223c', '~'}, // TILDE OPERATOR
1564  {U'\ua789', ':'}, // MODIFIER LETTER COLON
1565  {U'\ufeff', 0}, // ZERO WIDTH NO-BREAK SPACE
1566  {U'\uff01', '!'}, // FULLWIDTH EXCLAMATION MARK
1567  {U'\uff03', '#'}, // FULLWIDTH NUMBER SIGN
1568  {U'\uff04', '$'}, // FULLWIDTH DOLLAR SIGN
1569  {U'\uff05', '%'}, // FULLWIDTH PERCENT SIGN
1570  {U'\uff06', '&'}, // FULLWIDTH AMPERSAND
1571  {U'\uff08', '('}, // FULLWIDTH LEFT PARENTHESIS
1572  {U'\uff09', ')'}, // FULLWIDTH RIGHT PARENTHESIS
1573  {U'\uff0a', '*'}, // FULLWIDTH ASTERISK
1574  {U'\uff0b', '+'}, // FULLWIDTH ASTERISK
1575  {U'\uff0c', ','}, // FULLWIDTH COMMA
1576  {U'\uff0d', '-'}, // FULLWIDTH HYPHEN-MINUS
1577  {U'\uff0e', '.'}, // FULLWIDTH FULL STOP
1578  {U'\uff0f', '/'}, // FULLWIDTH SOLIDUS
1579  {U'\uff1a', ':'}, // FULLWIDTH COLON
1580  {U'\uff1b', ';'}, // FULLWIDTH SEMICOLON
1581  {U'\uff1c', '<'}, // FULLWIDTH LESS-THAN SIGN
1582  {U'\uff1d', '='}, // FULLWIDTH EQUALS SIGN
1583  {U'\uff1e', '>'}, // FULLWIDTH GREATER-THAN SIGN
1584  {U'\uff1f', '?'}, // FULLWIDTH QUESTION MARK
1585  {U'\uff20', '@'}, // FULLWIDTH COMMERCIAL AT
1586  {U'\uff3b', '['}, // FULLWIDTH LEFT SQUARE BRACKET
1587  {U'\uff3c', '\\'}, // FULLWIDTH REVERSE SOLIDUS
1588  {U'\uff3d', ']'}, // FULLWIDTH RIGHT SQUARE BRACKET
1589  {U'\uff3e', '^'}, // FULLWIDTH CIRCUMFLEX ACCENT
1590  {U'\uff5b', '{'}, // FULLWIDTH LEFT CURLY BRACKET
1591  {U'\uff5c', '|'}, // FULLWIDTH VERTICAL LINE
1592  {U'\uff5d', '}'}, // FULLWIDTH RIGHT CURLY BRACKET
1593  {U'\uff5e', '~'}, // FULLWIDTH TILDE
1594  {0, 0}
1595  };
1596  auto Homoglyph =
1597  std::lower_bound(std::begin(SortedHomoglyphs),
1598  std::end(SortedHomoglyphs) - 1, HomoglyphPair{C, '\0'});
1599  if (Homoglyph->Character == C) {
1600  llvm::SmallString<5> CharBuf;
1601  {
1602  llvm::raw_svector_ostream CharOS(CharBuf);
1603  llvm::write_hex(CharOS, C, llvm::HexPrintStyle::Upper, 4);
1604  }
1605  if (Homoglyph->LooksLike) {
1606  const char LooksLikeStr[] = {Homoglyph->LooksLike, 0};
1607  Diags.Report(Range.getBegin(), diag::warn_utf8_symbol_homoglyph)
1608  << Range << CharBuf << LooksLikeStr;
1609  } else {
1610  Diags.Report(Range.getBegin(), diag::warn_utf8_symbol_zero_width)
1611  << Range << CharBuf;
1612  }
1613  }
1614 }
1615 
1617  DiagnosticsEngine &Diags, const LangOptions &LangOpts, uint32_t CodePoint,
1618  CharSourceRange Range, bool IsFirst) {
1619  if (isASCII(CodePoint))
1620  return;
1621 
1622  bool IsIDStart = isAllowedInitiallyIDChar(CodePoint, LangOpts);
1623  bool IsIDContinue = IsIDStart || isAllowedIDChar(CodePoint, LangOpts);
1624 
1625  if ((IsFirst && IsIDStart) || (!IsFirst && IsIDContinue))
1626  return;
1627 
1628  bool InvalidOnlyAtStart = IsFirst && !IsIDStart && IsIDContinue;
1629 
1630  llvm::SmallString<5> CharBuf;
1631  llvm::raw_svector_ostream CharOS(CharBuf);
1632  llvm::write_hex(CharOS, CodePoint, llvm::HexPrintStyle::Upper, 4);
1633 
1634  if (!IsFirst || InvalidOnlyAtStart) {
1635  Diags.Report(Range.getBegin(), diag::err_character_not_allowed_identifier)
1636  << Range << CharBuf << int(InvalidOnlyAtStart)
1637  << FixItHint::CreateRemoval(Range);
1638  } else {
1639  Diags.Report(Range.getBegin(), diag::err_character_not_allowed)
1640  << Range << CharBuf << FixItHint::CreateRemoval(Range);
1641  }
1642 }
1643 
1644 bool Lexer::tryConsumeIdentifierUCN(const char *&CurPtr, unsigned Size,
1645  Token &Result) {
1646  const char *UCNPtr = CurPtr + Size;
1647  uint32_t CodePoint = tryReadUCN(UCNPtr, CurPtr, /*Token=*/nullptr);
1648  if (CodePoint == 0) {
1649  return false;
1650  }
1651 
1652  if (!isAllowedIDChar(CodePoint, LangOpts)) {
1653  if (isASCII(CodePoint) || isUnicodeWhitespace(CodePoint))
1654  return false;
1658  PP->getDiagnostics(), LangOpts, CodePoint,
1659  makeCharRange(*this, CurPtr, UCNPtr),
1660  /*IsFirst=*/false);
1661 
1662  // We got a unicode codepoint that is neither a space nor a
1663  // a valid identifier part.
1664  // Carry on as if the codepoint was valid for recovery purposes.
1665  } else if (!isLexingRawMode())
1667  makeCharRange(*this, CurPtr, UCNPtr),
1668  /*IsFirst=*/false);
1669 
1670  Result.setFlag(Token::HasUCN);
1671  if ((UCNPtr - CurPtr == 6 && CurPtr[1] == 'u') ||
1672  (UCNPtr - CurPtr == 10 && CurPtr[1] == 'U'))
1673  CurPtr = UCNPtr;
1674  else
1675  while (CurPtr != UCNPtr)
1676  (void)getAndAdvanceChar(CurPtr, Result);
1677  return true;
1678 }
1679 
1680 bool Lexer::tryConsumeIdentifierUTF8Char(const char *&CurPtr) {
1681  const char *UnicodePtr = CurPtr;
1682  llvm::UTF32 CodePoint;
1683  llvm::ConversionResult Result =
1684  llvm::convertUTF8Sequence((const llvm::UTF8 **)&UnicodePtr,
1685  (const llvm::UTF8 *)BufferEnd,
1686  &CodePoint,
1687  llvm::strictConversion);
1688  if (Result != llvm::conversionOK)
1689  return false;
1690 
1691  if (!isAllowedIDChar(static_cast<uint32_t>(CodePoint), LangOpts)) {
1692  if (isASCII(CodePoint) || isUnicodeWhitespace(CodePoint))
1693  return false;
1694 
1698  PP->getDiagnostics(), LangOpts, CodePoint,
1699  makeCharRange(*this, CurPtr, UnicodePtr), /*IsFirst=*/false);
1700  // We got a unicode codepoint that is neither a space nor a
1701  // a valid identifier part. Carry on as if the codepoint was
1702  // valid for recovery purposes.
1703  } else if (!isLexingRawMode()) {
1705  makeCharRange(*this, CurPtr, UnicodePtr),
1706  /*IsFirst=*/false);
1708  makeCharRange(*this, CurPtr, UnicodePtr));
1709  }
1710 
1711  CurPtr = UnicodePtr;
1712  return true;
1713 }
1714 
1715 bool Lexer::LexUnicodeIdentifierStart(Token &Result, uint32_t C,
1716  const char *CurPtr) {
1717  if (isAllowedInitiallyIDChar(C, LangOpts)) {
1719  !PP->isPreprocessedOutput()) {
1721  makeCharRange(*this, BufferPtr, CurPtr),
1722  /*IsFirst=*/true);
1724  makeCharRange(*this, BufferPtr, CurPtr));
1725  }
1726 
1727  MIOpt.ReadToken();
1728  return LexIdentifierContinue(Result, CurPtr);
1729  }
1730 
1732  !PP->isPreprocessedOutput() && !isASCII(*BufferPtr) &&
1733  !isAllowedInitiallyIDChar(C, LangOpts) && !isUnicodeWhitespace(C)) {
1734  // Non-ASCII characters tend to creep into source code unintentionally.
1735  // Instead of letting the parser complain about the unknown token,
1736  // just drop the character.
1737  // Note that we can /only/ do this when the non-ASCII character is actually
1738  // spelled as Unicode, not written as a UCN. The standard requires that
1739  // we not throw away any possible preprocessor tokens, but there's a
1740  // loophole in the mapping of Unicode characters to basic character set
1741  // characters that allows us to map these particular characters to, say,
1742  // whitespace.
1744  PP->getDiagnostics(), LangOpts, C,
1745  makeCharRange(*this, BufferPtr, CurPtr), /*IsStart*/ true);
1746  BufferPtr = CurPtr;
1747  return false;
1748  }
1749 
1750  // Otherwise, we have an explicit UCN or a character that's unlikely to show
1751  // up by accident.
1752  MIOpt.ReadToken();
1753  FormTokenWithChars(Result, CurPtr, tok::unknown);
1754  return true;
1755 }
1756 
1757 bool Lexer::LexIdentifierContinue(Token &Result, const char *CurPtr) {
1758  // Match [_A-Za-z0-9]*, we have already matched an identifier start.
1759  while (true) {
1760  unsigned char C = *CurPtr;
1761  // Fast path.
1762  if (isAsciiIdentifierContinue(C)) {
1763  ++CurPtr;
1764  continue;
1765  }
1766 
1767  unsigned Size;
1768  // Slow path: handle trigraph, unicode codepoints, UCNs.
1769  C = getCharAndSize(CurPtr, Size);
1770  if (isAsciiIdentifierContinue(C)) {
1771  CurPtr = ConsumeChar(CurPtr, Size, Result);
1772  continue;
1773  }
1774  if (C == '$') {
1775  // If we hit a $ and they are not supported in identifiers, we are done.
1776  if (!LangOpts.DollarIdents)
1777  break;
1778  // Otherwise, emit a diagnostic and continue.
1779  if (!isLexingRawMode())
1780  Diag(CurPtr, diag::ext_dollar_in_identifier);
1781  CurPtr = ConsumeChar(CurPtr, Size, Result);
1782  continue;
1783  }
1784  if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result))
1785  continue;
1786  if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr))
1787  continue;
1788  // Neither an expected Unicode codepoint nor a UCN.
1789  break;
1790  }
1791 
1792  const char *IdStart = BufferPtr;
1793  FormTokenWithChars(Result, CurPtr, tok::raw_identifier);
1794  Result.setRawIdentifierData(IdStart);
1795 
1796  // If we are in raw mode, return this identifier raw. There is no need to
1797  // look up identifier information or attempt to macro expand it.
1798  if (LexingRawMode)
1799  return true;
1800 
1801  // Fill in Result.IdentifierInfo and update the token kind,
1802  // looking up the identifier in the identifier table.
1803  IdentifierInfo *II = PP->LookUpIdentifierInfo(Result);
1804  // Note that we have to call PP->LookUpIdentifierInfo() even for code
1805  // completion, it writes IdentifierInfo into Result, and callers rely on it.
1806 
1807  // If the completion point is at the end of an identifier, we want to treat
1808  // the identifier as incomplete even if it resolves to a macro or a keyword.
1809  // This allows e.g. 'class^' to complete to 'classifier'.
1810  if (isCodeCompletionPoint(CurPtr)) {
1811  // Return the code-completion token.
1812  Result.setKind(tok::code_completion);
1813  // Skip the code-completion char and all immediate identifier characters.
1814  // This ensures we get consistent behavior when completing at any point in
1815  // an identifier (i.e. at the start, in the middle, at the end). Note that
1816  // only simple cases (i.e. [a-zA-Z0-9_]) are supported to keep the code
1817  // simpler.
1818  assert(*CurPtr == 0 && "Completion character must be 0");
1819  ++CurPtr;
1820  // Note that code completion token is not added as a separate character
1821  // when the completion point is at the end of the buffer. Therefore, we need
1822  // to check if the buffer has ended.
1823  if (CurPtr < BufferEnd) {
1824  while (isAsciiIdentifierContinue(*CurPtr))
1825  ++CurPtr;
1826  }
1827  BufferPtr = CurPtr;
1828  return true;
1829  }
1830 
1831  // Finally, now that we know we have an identifier, pass this off to the
1832  // preprocessor, which may macro expand it or something.
1833  if (II->isHandleIdentifierCase())
1834  return PP->HandleIdentifier(Result);
1835 
1836  return true;
1837 }
1838 
1839 /// isHexaLiteral - Return true if Start points to a hex constant.
1840 /// in microsoft mode (where this is supposed to be several different tokens).
1841 bool Lexer::isHexaLiteral(const char *Start, const LangOptions &LangOpts) {
1842  unsigned Size;
1843  char C1 = Lexer::getCharAndSizeNoWarn(Start, Size, LangOpts);
1844  if (C1 != '0')
1845  return false;
1846  char C2 = Lexer::getCharAndSizeNoWarn(Start + Size, Size, LangOpts);
1847  return (C2 == 'x' || C2 == 'X');
1848 }
1849 
1850 /// LexNumericConstant - Lex the remainder of a integer or floating point
1851 /// constant. From[-1] is the first character lexed. Return the end of the
1852 /// constant.
1853 bool Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
1854  unsigned Size;
1855  char C = getCharAndSize(CurPtr, Size);
1856  char PrevCh = 0;
1857  while (isPreprocessingNumberBody(C)) {
1858  CurPtr = ConsumeChar(CurPtr, Size, Result);
1859  PrevCh = C;
1860  C = getCharAndSize(CurPtr, Size);
1861  }
1862 
1863  // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
1864  if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) {
1865  // If we are in Microsoft mode, don't continue if the constant is hex.
1866  // For example, MSVC will accept the following as 3 tokens: 0x1234567e+1
1867  if (!LangOpts.MicrosoftExt || !isHexaLiteral(BufferPtr, LangOpts))
1868  return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1869  }
1870 
1871  // If we have a hex FP constant, continue.
1872  if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p')) {
1873  // Outside C99 and C++17, we accept hexadecimal floating point numbers as a
1874  // not-quite-conforming extension. Only do so if this looks like it's
1875  // actually meant to be a hexfloat, and not if it has a ud-suffix.
1876  bool IsHexFloat = true;
1877  if (!LangOpts.C99) {
1878  if (!isHexaLiteral(BufferPtr, LangOpts))
1879  IsHexFloat = false;
1880  else if (!getLangOpts().CPlusPlus17 &&
1881  std::find(BufferPtr, CurPtr, '_') != CurPtr)
1882  IsHexFloat = false;
1883  }
1884  if (IsHexFloat)
1885  return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1886  }
1887 
1888  // If we have a digit separator, continue.
1889  if (C == '\'' && (getLangOpts().CPlusPlus14 || getLangOpts().C2x)) {
1890  unsigned NextSize;
1891  char Next = getCharAndSizeNoWarn(CurPtr + Size, NextSize, getLangOpts());
1892  if (isAsciiIdentifierContinue(Next)) {
1893  if (!isLexingRawMode())
1894  Diag(CurPtr, getLangOpts().CPlusPlus
1895  ? diag::warn_cxx11_compat_digit_separator
1896  : diag::warn_c2x_compat_digit_separator);
1897  CurPtr = ConsumeChar(CurPtr, Size, Result);
1898  CurPtr = ConsumeChar(CurPtr, NextSize, Result);
1899  return LexNumericConstant(Result, CurPtr);
1900  }
1901  }
1902 
1903  // If we have a UCN or UTF-8 character (perhaps in a ud-suffix), continue.
1904  if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result))
1905  return LexNumericConstant(Result, CurPtr);
1906  if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr))
1907  return LexNumericConstant(Result, CurPtr);
1908 
1909  // Update the location of token as well as BufferPtr.
1910  const char *TokStart = BufferPtr;
1911  FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
1912  Result.setLiteralData(TokStart);
1913  return true;
1914 }
1915 
1916 /// LexUDSuffix - Lex the ud-suffix production for user-defined literal suffixes
1917 /// in C++11, or warn on a ud-suffix in C++98.
1918 const char *Lexer::LexUDSuffix(Token &Result, const char *CurPtr,
1919  bool IsStringLiteral) {
1920  assert(getLangOpts().CPlusPlus);
1921 
1922  // Maximally munch an identifier.
1923  unsigned Size;
1924  char C = getCharAndSize(CurPtr, Size);
1925  bool Consumed = false;
1926 
1927  if (!isAsciiIdentifierStart(C)) {
1928  if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result))
1929  Consumed = true;
1930  else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr))
1931  Consumed = true;
1932  else
1933  return CurPtr;
1934  }
1935 
1936  if (!getLangOpts().CPlusPlus11) {
1937  if (!isLexingRawMode())
1938  Diag(CurPtr,
1939  C == '_' ? diag::warn_cxx11_compat_user_defined_literal
1940  : diag::warn_cxx11_compat_reserved_user_defined_literal)
1942  return CurPtr;
1943  }
1944 
1945  // C++11 [lex.ext]p10, [usrlit.suffix]p1: A program containing a ud-suffix
1946  // that does not start with an underscore is ill-formed. As a conforming
1947  // extension, we treat all such suffixes as if they had whitespace before
1948  // them. We assume a suffix beginning with a UCN or UTF-8 character is more
1949  // likely to be a ud-suffix than a macro, however, and accept that.
1950  if (!Consumed) {
1951  bool IsUDSuffix = false;
1952  if (C == '_')
1953  IsUDSuffix = true;
1954  else if (IsStringLiteral && getLangOpts().CPlusPlus14) {
1955  // In C++1y, we need to look ahead a few characters to see if this is a
1956  // valid suffix for a string literal or a numeric literal (this could be
1957  // the 'operator""if' defining a numeric literal operator).
1958  const unsigned MaxStandardSuffixLength = 3;
1959  char Buffer[MaxStandardSuffixLength] = { C };
1960  unsigned Consumed = Size;
1961  unsigned Chars = 1;
1962  while (true) {
1963  unsigned NextSize;
1964  char Next = getCharAndSizeNoWarn(CurPtr + Consumed, NextSize,
1965  getLangOpts());
1966  if (!isAsciiIdentifierContinue(Next)) {
1967  // End of suffix. Check whether this is on the allowed list.
1968  const StringRef CompleteSuffix(Buffer, Chars);
1970  CompleteSuffix);
1971  break;
1972  }
1973 
1974  if (Chars == MaxStandardSuffixLength)
1975  // Too long: can't be a standard suffix.
1976  break;
1977 
1978  Buffer[Chars++] = Next;
1979  Consumed += NextSize;
1980  }
1981  }
1982 
1983  if (!IsUDSuffix) {
1984  if (!isLexingRawMode())
1985  Diag(CurPtr, getLangOpts().MSVCCompat
1986  ? diag::ext_ms_reserved_user_defined_literal
1987  : diag::ext_reserved_user_defined_literal)
1989  return CurPtr;
1990  }
1991 
1992  CurPtr = ConsumeChar(CurPtr, Size, Result);
1993  }
1994 
1995  Result.setFlag(Token::HasUDSuffix);
1996  while (true) {
1997  C = getCharAndSize(CurPtr, Size);
1998  if (isAsciiIdentifierContinue(C)) {
1999  CurPtr = ConsumeChar(CurPtr, Size, Result);
2000  } else if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result)) {
2001  } else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr)) {
2002  } else
2003  break;
2004  }
2005 
2006  return CurPtr;
2007 }
2008 
2009 /// LexStringLiteral - Lex the remainder of a string literal, after having lexed
2010 /// either " or L" or u8" or u" or U".
2011 bool Lexer::LexStringLiteral(Token &Result, const char *CurPtr,
2012  tok::TokenKind Kind) {
2013  const char *AfterQuote = CurPtr;
2014  // Does this string contain the \0 character?
2015  const char *NulCharacter = nullptr;
2016 
2017  if (!isLexingRawMode() &&
2018  (Kind == tok::utf8_string_literal ||
2019  Kind == tok::utf16_string_literal ||
2020  Kind == tok::utf32_string_literal))
2021  Diag(BufferPtr, getLangOpts().CPlusPlus
2022  ? diag::warn_cxx98_compat_unicode_literal
2023  : diag::warn_c99_compat_unicode_literal);
2024 
2025  char C = getAndAdvanceChar(CurPtr, Result);
2026  while (C != '"') {
2027  // Skip escaped characters. Escaped newlines will already be processed by
2028  // getAndAdvanceChar.
2029  if (C == '\\')
2030  C = getAndAdvanceChar(CurPtr, Result);
2031 
2032  if (C == '\n' || C == '\r' || // Newline.
2033  (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
2034  if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
2035  Diag(BufferPtr, diag::ext_unterminated_char_or_string) << 1;
2036  FormTokenWithChars(Result, CurPtr-1, tok::unknown);
2037  return true;
2038  }
2039 
2040  if (C == 0) {
2041  if (isCodeCompletionPoint(CurPtr-1)) {
2042  if (ParsingFilename)
2043  codeCompleteIncludedFile(AfterQuote, CurPtr - 1, /*IsAngled=*/false);
2044  else
2046  FormTokenWithChars(Result, CurPtr - 1, tok::unknown);
2047  cutOffLexing();
2048  return true;
2049  }
2050 
2051  NulCharacter = CurPtr-1;
2052  }
2053  C = getAndAdvanceChar(CurPtr, Result);
2054  }
2055 
2056  // If we are in C++11, lex the optional ud-suffix.
2057  if (getLangOpts().CPlusPlus)
2058  CurPtr = LexUDSuffix(Result, CurPtr, true);
2059 
2060  // If a nul character existed in the string, warn about it.
2061  if (NulCharacter && !isLexingRawMode())
2062  Diag(NulCharacter, diag::null_in_char_or_string) << 1;
2063 
2064  // Update the location of the token as well as the BufferPtr instance var.
2065  const char *TokStart = BufferPtr;
2066  FormTokenWithChars(Result, CurPtr, Kind);
2067  Result.setLiteralData(TokStart);
2068  return true;
2069 }
2070 
2071 /// LexRawStringLiteral - Lex the remainder of a raw string literal, after
2072 /// having lexed R", LR", u8R", uR", or UR".
2073 bool Lexer::LexRawStringLiteral(Token &Result, const char *CurPtr,
2074  tok::TokenKind Kind) {
2075  // This function doesn't use getAndAdvanceChar because C++0x [lex.pptoken]p3:
2076  // Between the initial and final double quote characters of the raw string,
2077  // any transformations performed in phases 1 and 2 (trigraphs,
2078  // universal-character-names, and line splicing) are reverted.
2079 
2080  if (!isLexingRawMode())
2081  Diag(BufferPtr, diag::warn_cxx98_compat_raw_string_literal);
2082 
2083  unsigned PrefixLen = 0;
2084 
2085  while (PrefixLen != 16 && isRawStringDelimBody(CurPtr[PrefixLen]))
2086  ++PrefixLen;
2087 
2088  // If the last character was not a '(', then we didn't lex a valid delimiter.
2089  if (CurPtr[PrefixLen] != '(') {
2090  if (!isLexingRawMode()) {
2091  const char *PrefixEnd = &CurPtr[PrefixLen];
2092  if (PrefixLen == 16) {
2093  Diag(PrefixEnd, diag::err_raw_delim_too_long);
2094  } else {
2095  Diag(PrefixEnd, diag::err_invalid_char_raw_delim)
2096  << StringRef(PrefixEnd, 1);
2097  }
2098  }
2099 
2100  // Search for the next '"' in hopes of salvaging the lexer. Unfortunately,
2101  // it's possible the '"' was intended to be part of the raw string, but
2102  // there's not much we can do about that.
2103  while (true) {
2104  char C = *CurPtr++;
2105 
2106  if (C == '"')
2107  break;
2108  if (C == 0 && CurPtr-1 == BufferEnd) {
2109  --CurPtr;
2110  break;
2111  }
2112  }
2113 
2114  FormTokenWithChars(Result, CurPtr, tok::unknown);
2115  return true;
2116  }
2117 
2118  // Save prefix and move CurPtr past it
2119  const char *Prefix = CurPtr;
2120  CurPtr += PrefixLen + 1; // skip over prefix and '('
2121 
2122  while (true) {
2123  char C = *CurPtr++;
2124 
2125  if (C == ')') {
2126  // Check for prefix match and closing quote.
2127  if (strncmp(CurPtr, Prefix, PrefixLen) == 0 && CurPtr[PrefixLen] == '"') {
2128  CurPtr += PrefixLen + 1; // skip over prefix and '"'
2129  break;
2130  }
2131  } else if (C == 0 && CurPtr-1 == BufferEnd) { // End of file.
2132  if (!isLexingRawMode())
2133  Diag(BufferPtr, diag::err_unterminated_raw_string)
2134  << StringRef(Prefix, PrefixLen);
2135  FormTokenWithChars(Result, CurPtr-1, tok::unknown);
2136  return true;
2137  }
2138  }
2139 
2140  // If we are in C++11, lex the optional ud-suffix.
2141  if (getLangOpts().CPlusPlus)
2142  CurPtr = LexUDSuffix(Result, CurPtr, true);
2143 
2144  // Update the location of token as well as BufferPtr.
2145  const char *TokStart = BufferPtr;
2146  FormTokenWithChars(Result, CurPtr, Kind);
2147  Result.setLiteralData(TokStart);
2148  return true;
2149 }
2150 
2151 /// LexAngledStringLiteral - Lex the remainder of an angled string literal,
2152 /// after having lexed the '<' character. This is used for #include filenames.
2153 bool Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
2154  // Does this string contain the \0 character?
2155  const char *NulCharacter = nullptr;
2156  const char *AfterLessPos = CurPtr;
2157  char C = getAndAdvanceChar(CurPtr, Result);
2158  while (C != '>') {
2159  // Skip escaped characters. Escaped newlines will already be processed by
2160  // getAndAdvanceChar.
2161  if (C == '\\')
2162  C = getAndAdvanceChar(CurPtr, Result);
2163 
2164  if (isVerticalWhitespace(C) || // Newline.
2165  (C == 0 && (CurPtr - 1 == BufferEnd))) { // End of file.
2166  // If the filename is unterminated, then it must just be a lone <
2167  // character. Return this as such.
2168  FormTokenWithChars(Result, AfterLessPos, tok::less);
2169  return true;
2170  }
2171 
2172  if (C == 0) {
2173  if (isCodeCompletionPoint(CurPtr - 1)) {
2174  codeCompleteIncludedFile(AfterLessPos, CurPtr - 1, /*IsAngled=*/true);
2175  cutOffLexing();
2176  FormTokenWithChars(Result, CurPtr - 1, tok::unknown);
2177  return true;
2178  }
2179  NulCharacter = CurPtr-1;
2180  }
2181  C = getAndAdvanceChar(CurPtr, Result);
2182  }
2183 
2184  // If a nul character existed in the string, warn about it.
2185  if (NulCharacter && !isLexingRawMode())
2186  Diag(NulCharacter, diag::null_in_char_or_string) << 1;
2187 
2188  // Update the location of token as well as BufferPtr.
2189  const char *TokStart = BufferPtr;
2190  FormTokenWithChars(Result, CurPtr, tok::header_name);
2191  Result.setLiteralData(TokStart);
2192  return true;
2193 }
2194 
2195 void Lexer::codeCompleteIncludedFile(const char *PathStart,
2196  const char *CompletionPoint,
2197  bool IsAngled) {
2198  // Completion only applies to the filename, after the last slash.
2199  StringRef PartialPath(PathStart, CompletionPoint - PathStart);
2200  llvm::StringRef SlashChars = LangOpts.MSVCCompat ? "/\\" : "/";
2201  auto Slash = PartialPath.find_last_of(SlashChars);
2202  StringRef Dir =
2203  (Slash == StringRef::npos) ? "" : PartialPath.take_front(Slash);
2204  const char *StartOfFilename =
2205  (Slash == StringRef::npos) ? PathStart : PathStart + Slash + 1;
2206  // Code completion filter range is the filename only, up to completion point.
2208  StringRef(StartOfFilename, CompletionPoint - StartOfFilename)));
2209  // We should replace the characters up to the closing quote or closest slash,
2210  // if any.
2211  while (CompletionPoint < BufferEnd) {
2212  char Next = *(CompletionPoint + 1);
2213  if (Next == 0 || Next == '\r' || Next == '\n')
2214  break;
2215  ++CompletionPoint;
2216  if (Next == (IsAngled ? '>' : '"'))
2217  break;
2218  if (llvm::is_contained(SlashChars, Next))
2219  break;
2220  }
2221 
2223  FileLoc.getLocWithOffset(StartOfFilename - BufferStart),
2224  FileLoc.getLocWithOffset(CompletionPoint - BufferStart));
2225  PP->CodeCompleteIncludedFile(Dir, IsAngled);
2226 }
2227 
2228 /// LexCharConstant - Lex the remainder of a character constant, after having
2229 /// lexed either ' or L' or u8' or u' or U'.
2230 bool Lexer::LexCharConstant(Token &Result, const char *CurPtr,
2231  tok::TokenKind Kind) {
2232  // Does this character contain the \0 character?
2233  const char *NulCharacter = nullptr;
2234 
2235  if (!isLexingRawMode()) {
2236  if (Kind == tok::utf16_char_constant || Kind == tok::utf32_char_constant)
2237  Diag(BufferPtr, getLangOpts().CPlusPlus
2238  ? diag::warn_cxx98_compat_unicode_literal
2239  : diag::warn_c99_compat_unicode_literal);
2240  else if (Kind == tok::utf8_char_constant)
2241  Diag(BufferPtr, diag::warn_cxx14_compat_u8_character_literal);
2242  }
2243 
2244  char C = getAndAdvanceChar(CurPtr, Result);
2245  if (C == '\'') {
2246  if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
2247  Diag(BufferPtr, diag::ext_empty_character);
2248  FormTokenWithChars(Result, CurPtr, tok::unknown);
2249  return true;
2250  }
2251 
2252  while (C != '\'') {
2253  // Skip escaped characters.
2254  if (C == '\\')
2255  C = getAndAdvanceChar(CurPtr, Result);
2256 
2257  if (C == '\n' || C == '\r' || // Newline.
2258  (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
2259  if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
2260  Diag(BufferPtr, diag::ext_unterminated_char_or_string) << 0;
2261  FormTokenWithChars(Result, CurPtr-1, tok::unknown);
2262  return true;
2263  }
2264 
2265  if (C == 0) {
2266  if (isCodeCompletionPoint(CurPtr-1)) {
2268  FormTokenWithChars(Result, CurPtr-1, tok::unknown);
2269  cutOffLexing();
2270  return true;
2271  }
2272 
2273  NulCharacter = CurPtr-1;
2274  }
2275  C = getAndAdvanceChar(CurPtr, Result);
2276  }
2277 
2278  // If we are in C++11, lex the optional ud-suffix.
2279  if (getLangOpts().CPlusPlus)
2280  CurPtr = LexUDSuffix(Result, CurPtr, false);
2281 
2282  // If a nul character existed in the character, warn about it.
2283  if (NulCharacter && !isLexingRawMode())
2284  Diag(NulCharacter, diag::null_in_char_or_string) << 0;
2285 
2286  // Update the location of token as well as BufferPtr.
2287  const char *TokStart = BufferPtr;
2288  FormTokenWithChars(Result, CurPtr, Kind);
2289  Result.setLiteralData(TokStart);
2290  return true;
2291 }
2292 
2293 /// SkipWhitespace - Efficiently skip over a series of whitespace characters.
2294 /// Update BufferPtr to point to the next non-whitespace character and return.
2295 ///
2296 /// This method forms a token and returns true if KeepWhitespaceMode is enabled.
2297 bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr,
2298  bool &TokAtPhysicalStartOfLine) {
2299  // Whitespace - Skip it, then return the token after the whitespace.
2300  bool SawNewline = isVerticalWhitespace(CurPtr[-1]);
2301 
2302  unsigned char Char = *CurPtr;
2303 
2304  const char *lastNewLine = nullptr;
2305  auto setLastNewLine = [&](const char *Ptr) {
2306  lastNewLine = Ptr;
2307  if (!NewLinePtr)
2308  NewLinePtr = Ptr;
2309  };
2310  if (SawNewline)
2311  setLastNewLine(CurPtr - 1);
2312 
2313  // Skip consecutive spaces efficiently.
2314  while (true) {
2315  // Skip horizontal whitespace very aggressively.
2316  while (isHorizontalWhitespace(Char))
2317  Char = *++CurPtr;
2318 
2319  // Otherwise if we have something other than whitespace, we're done.
2320  if (!isVerticalWhitespace(Char))
2321  break;
2322 
2324  // End of preprocessor directive line, let LexTokenInternal handle this.
2325  BufferPtr = CurPtr;
2326  return false;
2327  }
2328 
2329  // OK, but handle newline.
2330  if (*CurPtr == '\n')
2331  setLastNewLine(CurPtr);
2332  SawNewline = true;
2333  Char = *++CurPtr;
2334  }
2335 
2336  // If the client wants us to return whitespace, return it now.
2337  if (isKeepWhitespaceMode()) {
2338  FormTokenWithChars(Result, CurPtr, tok::unknown);
2339  if (SawNewline) {
2340  IsAtStartOfLine = true;
2341  IsAtPhysicalStartOfLine = true;
2342  }
2343  // FIXME: The next token will not have LeadingSpace set.
2344  return true;
2345  }
2346 
2347  // If this isn't immediately after a newline, there is leading space.
2348  char PrevChar = CurPtr[-1];
2349  bool HasLeadingSpace = !isVerticalWhitespace(PrevChar);
2350 
2351  Result.setFlagValue(Token::LeadingSpace, HasLeadingSpace);
2352  if (SawNewline) {
2353  Result.setFlag(Token::StartOfLine);
2354  TokAtPhysicalStartOfLine = true;
2355 
2356  if (NewLinePtr && lastNewLine && NewLinePtr != lastNewLine && PP) {
2357  if (auto *Handler = PP->getEmptylineHandler())
2358  Handler->HandleEmptyline(SourceRange(getSourceLocation(NewLinePtr + 1),
2359  getSourceLocation(lastNewLine)));
2360  }
2361  }
2362 
2363  BufferPtr = CurPtr;
2364  return false;
2365 }
2366 
2367 /// We have just read the // characters from input. Skip until we find the
2368 /// newline character that terminates the comment. Then update BufferPtr and
2369 /// return.
2370 ///
2371 /// If we're in KeepCommentMode or any CommentHandler has inserted
2372 /// some tokens, this will store the first token and return true.
2373 bool Lexer::SkipLineComment(Token &Result, const char *CurPtr,
2374  bool &TokAtPhysicalStartOfLine) {
2375  // If Line comments aren't explicitly enabled for this language, emit an
2376  // extension warning.
2377  if (!LangOpts.LineComment && !isLexingRawMode()) {
2378  Diag(BufferPtr, diag::ext_line_comment);
2379 
2380  // Mark them enabled so we only emit one warning for this translation
2381  // unit.
2382  LangOpts.LineComment = true;
2383  }
2384 
2385  // Scan over the body of the comment. The common case, when scanning, is that
2386  // the comment contains normal ascii characters with nothing interesting in
2387  // them. As such, optimize for this case with the inner loop.
2388  //
2389  // This loop terminates with CurPtr pointing at the newline (or end of buffer)
2390  // character that ends the line comment.
2391  char C;
2392  while (true) {
2393  C = *CurPtr;
2394  // Skip over characters in the fast loop.
2395  while (C != 0 && // Potentially EOF.
2396  C != '\n' && C != '\r') // Newline or DOS-style newline.
2397  C = *++CurPtr;
2398 
2399  const char *NextLine = CurPtr;
2400  if (C != 0) {
2401  // We found a newline, see if it's escaped.
2402  const char *EscapePtr = CurPtr-1;
2403  bool HasSpace = false;
2404  while (isHorizontalWhitespace(*EscapePtr)) { // Skip whitespace.
2405  --EscapePtr;
2406  HasSpace = true;
2407  }
2408 
2409  if (*EscapePtr == '\\')
2410  // Escaped newline.
2411  CurPtr = EscapePtr;
2412  else if (EscapePtr[0] == '/' && EscapePtr[-1] == '?' &&
2413  EscapePtr[-2] == '?' && LangOpts.Trigraphs)
2414  // Trigraph-escaped newline.
2415  CurPtr = EscapePtr-2;
2416  else
2417  break; // This is a newline, we're done.
2418 
2419  // If there was space between the backslash and newline, warn about it.
2420  if (HasSpace && !isLexingRawMode())
2421  Diag(EscapePtr, diag::backslash_newline_space);
2422  }
2423 
2424  // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
2425  // properly decode the character. Read it in raw mode to avoid emitting
2426  // diagnostics about things like trigraphs. If we see an escaped newline,
2427  // we'll handle it below.
2428  const char *OldPtr = CurPtr;
2429  bool OldRawMode = isLexingRawMode();
2430  LexingRawMode = true;
2431  C = getAndAdvanceChar(CurPtr, Result);
2432  LexingRawMode = OldRawMode;
2433 
2434  // If we only read only one character, then no special handling is needed.
2435  // We're done and can skip forward to the newline.
2436  if (C != 0 && CurPtr == OldPtr+1) {
2437  CurPtr = NextLine;
2438  break;
2439  }
2440 
2441  // If we read multiple characters, and one of those characters was a \r or
2442  // \n, then we had an escaped newline within the comment. Emit diagnostic
2443  // unless the next line is also a // comment.
2444  if (CurPtr != OldPtr + 1 && C != '/' &&
2445  (CurPtr == BufferEnd + 1 || CurPtr[0] != '/')) {
2446  for (; OldPtr != CurPtr; ++OldPtr)
2447  if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
2448  // Okay, we found a // comment that ends in a newline, if the next
2449  // line is also a // comment, but has spaces, don't emit a diagnostic.
2450  if (isWhitespace(C)) {
2451  const char *ForwardPtr = CurPtr;
2452  while (isWhitespace(*ForwardPtr)) // Skip whitespace.
2453  ++ForwardPtr;
2454  if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
2455  break;
2456  }
2457 
2458  if (!isLexingRawMode())
2459  Diag(OldPtr-1, diag::ext_multi_line_line_comment);
2460  break;
2461  }
2462  }
2463 
2464  if (C == '\r' || C == '\n' || CurPtr == BufferEnd + 1) {
2465  --CurPtr;
2466  break;
2467  }
2468 
2469  if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2471  cutOffLexing();
2472  return false;
2473  }
2474  }
2475 
2476  // Found but did not consume the newline. Notify comment handlers about the
2477  // comment unless we're in a #if 0 block.
2478  if (PP && !isLexingRawMode() &&
2479  PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2480  getSourceLocation(CurPtr)))) {
2481  BufferPtr = CurPtr;
2482  return true; // A token has to be returned.
2483  }
2484 
2485  // If we are returning comments as tokens, return this comment as a token.
2486  if (inKeepCommentMode())
2487  return SaveLineComment(Result, CurPtr);
2488 
2489  // If we are inside a preprocessor directive and we see the end of line,
2490  // return immediately, so that the lexer can return this as an EOD token.
2491  if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
2492  BufferPtr = CurPtr;
2493  return false;
2494  }
2495 
2496  // Otherwise, eat the \n character. We don't care if this is a \n\r or
2497  // \r\n sequence. This is an efficiency hack (because we know the \n can't
2498  // contribute to another token), it isn't needed for correctness. Note that
2499  // this is ok even in KeepWhitespaceMode, because we would have returned the
2500  /// comment above in that mode.
2501  NewLinePtr = CurPtr++;
2502 
2503  // The next returned token is at the start of the line.
2504  Result.setFlag(Token::StartOfLine);
2505  TokAtPhysicalStartOfLine = true;
2506  // No leading whitespace seen so far.
2507  Result.clearFlag(Token::LeadingSpace);
2508  BufferPtr = CurPtr;
2509  return false;
2510 }
2511 
2512 /// If in save-comment mode, package up this Line comment in an appropriate
2513 /// way and return it.
2514 bool Lexer::SaveLineComment(Token &Result, const char *CurPtr) {
2515  // If we're not in a preprocessor directive, just return the // comment
2516  // directly.
2517  FormTokenWithChars(Result, CurPtr, tok::comment);
2518 
2520  return true;
2521 
2522  // If this Line-style comment is in a macro definition, transmogrify it into
2523  // a C-style block comment.
2524  bool Invalid = false;
2525  std::string Spelling = PP->getSpelling(Result, &Invalid);
2526  if (Invalid)
2527  return true;
2528 
2529  assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not line comment?");
2530  Spelling[1] = '*'; // Change prefix to "/*".
2531  Spelling += "*/"; // add suffix.
2532 
2533  Result.setKind(tok::comment);
2534  PP->CreateString(Spelling, Result,
2535  Result.getLocation(), Result.getLocation());
2536  return true;
2537 }
2538 
2539 /// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
2540 /// character (either \\n or \\r) is part of an escaped newline sequence. Issue
2541 /// a diagnostic if so. We know that the newline is inside of a block comment.
2542 static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
2543  Lexer *L) {
2544  assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
2545 
2546  // Position of the first trigraph in the ending sequence.
2547  const char *TrigraphPos = 0;
2548  // Position of the first whitespace after a '\' in the ending sequence.
2549  const char *SpacePos = 0;
2550 
2551  while (true) {
2552  // Back up off the newline.
2553  --CurPtr;
2554 
2555  // If this is a two-character newline sequence, skip the other character.
2556  if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
2557  // \n\n or \r\r -> not escaped newline.
2558  if (CurPtr[0] == CurPtr[1])
2559  return false;
2560  // \n\r or \r\n -> skip the newline.
2561  --CurPtr;
2562  }
2563 
2564  // If we have horizontal whitespace, skip over it. We allow whitespace
2565  // between the slash and newline.
2566  while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
2567  SpacePos = CurPtr;
2568  --CurPtr;
2569  }
2570 
2571  // If we have a slash, this is an escaped newline.
2572  if (*CurPtr == '\\') {
2573  --CurPtr;
2574  } else if (CurPtr[0] == '/' && CurPtr[-1] == '?' && CurPtr[-2] == '?') {
2575  // This is a trigraph encoding of a slash.
2576  TrigraphPos = CurPtr - 2;
2577  CurPtr -= 3;
2578  } else {
2579  return false;
2580  }
2581 
2582  // If the character preceding the escaped newline is a '*', then after line
2583  // splicing we have a '*/' ending the comment.
2584  if (*CurPtr == '*')
2585  break;
2586 
2587  if (*CurPtr != '\n' && *CurPtr != '\r')
2588  return false;
2589  }
2590 
2591  if (TrigraphPos) {
2592  // If no trigraphs are enabled, warn that we ignored this trigraph and
2593  // ignore this * character.
2594  if (!L->getLangOpts().Trigraphs) {
2595  if (!L->isLexingRawMode())
2596  L->Diag(TrigraphPos, diag::trigraph_ignored_block_comment);
2597  return false;
2598  }
2599  if (!L->isLexingRawMode())
2600  L->Diag(TrigraphPos, diag::trigraph_ends_block_comment);
2601  }
2602 
2603  // Warn about having an escaped newline between the */ characters.
2604  if (!L->isLexingRawMode())
2605  L->Diag(CurPtr + 1, diag::escaped_newline_block_comment_end);
2606 
2607  // If there was space between the backslash and newline, warn about it.
2608  if (SpacePos && !L->isLexingRawMode())
2609  L->Diag(SpacePos, diag::backslash_newline_space);
2610 
2611  return true;
2612 }
2613 
2614 #ifdef __SSE2__
2615 #include <emmintrin.h>
2616 #elif __ALTIVEC__
2617 #include <altivec.h>
2618 #undef bool
2619 #endif
2620 
2621 /// We have just read from input the / and * characters that started a comment.
2622 /// Read until we find the * and / characters that terminate the comment.
2623 /// Note that we don't bother decoding trigraphs or escaped newlines in block
2624 /// comments, because they cannot cause the comment to end. The only thing
2625 /// that can happen is the comment could end with an escaped newline between
2626 /// the terminating * and /.
2627 ///
2628 /// If we're in KeepCommentMode or any CommentHandler has inserted
2629 /// some tokens, this will store the first token and return true.
2630 bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr,
2631  bool &TokAtPhysicalStartOfLine) {
2632  // Scan one character past where we should, looking for a '/' character. Once
2633  // we find it, check to see if it was preceded by a *. This common
2634  // optimization helps people who like to put a lot of * characters in their
2635  // comments.
2636 
2637  // The first character we get with newlines and trigraphs skipped to handle
2638  // the degenerate /*/ case below correctly if the * has an escaped newline
2639  // after it.
2640  unsigned CharSize;
2641  unsigned char C = getCharAndSize(CurPtr, CharSize);
2642  CurPtr += CharSize;
2643  if (C == 0 && CurPtr == BufferEnd+1) {
2644  if (!isLexingRawMode())
2645  Diag(BufferPtr, diag::err_unterminated_block_comment);
2646  --CurPtr;
2647 
2648  // KeepWhitespaceMode should return this broken comment as a token. Since
2649  // it isn't a well formed comment, just return it as an 'unknown' token.
2650  if (isKeepWhitespaceMode()) {
2651  FormTokenWithChars(Result, CurPtr, tok::unknown);
2652  return true;
2653  }
2654 
2655  BufferPtr = CurPtr;
2656  return false;
2657  }
2658 
2659  // Check to see if the first character after the '/*' is another /. If so,
2660  // then this slash does not end the block comment, it is part of it.
2661  if (C == '/')
2662  C = *CurPtr++;
2663 
2664  while (true) {
2665  // Skip over all non-interesting characters until we find end of buffer or a
2666  // (probably ending) '/' character.
2667  if (CurPtr + 24 < BufferEnd &&
2668  // If there is a code-completion point avoid the fast scan because it
2669  // doesn't check for '\0'.
2670  !(PP && PP->getCodeCompletionFileLoc() == FileLoc)) {
2671  // While not aligned to a 16-byte boundary.
2672  while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
2673  C = *CurPtr++;
2674 
2675  if (C == '/') goto FoundSlash;
2676 
2677 #ifdef __SSE2__
2678  __m128i Slashes = _mm_set1_epi8('/');
2679  while (CurPtr+16 <= BufferEnd) {
2680  int cmp = _mm_movemask_epi8(_mm_cmpeq_epi8(*(const __m128i*)CurPtr,
2681  Slashes));
2682  if (cmp != 0) {
2683  // Adjust the pointer to point directly after the first slash. It's
2684  // not necessary to set C here, it will be overwritten at the end of
2685  // the outer loop.
2686  CurPtr += llvm::countTrailingZeros<unsigned>(cmp) + 1;
2687  goto FoundSlash;
2688  }
2689  CurPtr += 16;
2690  }
2691 #elif __ALTIVEC__
2692  __vector unsigned char Slashes = {
2693  '/', '/', '/', '/', '/', '/', '/', '/',
2694  '/', '/', '/', '/', '/', '/', '/', '/'
2695  };
2696  while (CurPtr + 16 <= BufferEnd &&
2697  !vec_any_eq(*(const __vector unsigned char *)CurPtr, Slashes))
2698  CurPtr += 16;
2699 #else
2700  // Scan for '/' quickly. Many block comments are very large.
2701  while (CurPtr[0] != '/' &&
2702  CurPtr[1] != '/' &&
2703  CurPtr[2] != '/' &&
2704  CurPtr[3] != '/' &&
2705  CurPtr+4 < BufferEnd) {
2706  CurPtr += 4;
2707  }
2708 #endif
2709 
2710  // It has to be one of the bytes scanned, increment to it and read one.
2711  C = *CurPtr++;
2712  }
2713 
2714  // Loop to scan the remainder.
2715  while (C != '/' && C != '\0')
2716  C = *CurPtr++;
2717 
2718  if (C == '/') {
2719  FoundSlash:
2720  if (CurPtr[-2] == '*') // We found the final */. We're done!
2721  break;
2722 
2723  if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
2724  if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
2725  // We found the final */, though it had an escaped newline between the
2726  // * and /. We're done!
2727  break;
2728  }
2729  }
2730  if (CurPtr[0] == '*' && CurPtr[1] != '/') {
2731  // If this is a /* inside of the comment, emit a warning. Don't do this
2732  // if this is a /*/, which will end the comment. This misses cases with
2733  // embedded escaped newlines, but oh well.
2734  if (!isLexingRawMode())
2735  Diag(CurPtr-1, diag::warn_nested_block_comment);
2736  }
2737  } else if (C == 0 && CurPtr == BufferEnd+1) {
2738  if (!isLexingRawMode())
2739  Diag(BufferPtr, diag::err_unterminated_block_comment);
2740  // Note: the user probably forgot a */. We could continue immediately
2741  // after the /*, but this would involve lexing a lot of what really is the
2742  // comment, which surely would confuse the parser.
2743  --CurPtr;
2744 
2745  // KeepWhitespaceMode should return this broken comment as a token. Since
2746  // it isn't a well formed comment, just return it as an 'unknown' token.
2747  if (isKeepWhitespaceMode()) {
2748  FormTokenWithChars(Result, CurPtr, tok::unknown);
2749  return true;
2750  }
2751 
2752  BufferPtr = CurPtr;
2753  return false;
2754  } else if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2756  cutOffLexing();
2757  return false;
2758  }
2759 
2760  C = *CurPtr++;
2761  }
2762 
2763  // Notify comment handlers about the comment unless we're in a #if 0 block.
2764  if (PP && !isLexingRawMode() &&
2765  PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2766  getSourceLocation(CurPtr)))) {
2767  BufferPtr = CurPtr;
2768  return true; // A token has to be returned.
2769  }
2770 
2771  // If we are returning comments as tokens, return this comment as a token.
2772  if (inKeepCommentMode()) {
2773  FormTokenWithChars(Result, CurPtr, tok::comment);
2774  return true;
2775  }
2776 
2777  // It is common for the tokens immediately after a /**/ comment to be
2778  // whitespace. Instead of going through the big switch, handle it
2779  // efficiently now. This is safe even in KeepWhitespaceMode because we would
2780  // have already returned above with the comment as a token.
2781  if (isHorizontalWhitespace(*CurPtr)) {
2782  SkipWhitespace(Result, CurPtr+1, TokAtPhysicalStartOfLine);
2783  return false;
2784  }
2785 
2786  // Otherwise, just return so that the next character will be lexed as a token.
2787  BufferPtr = CurPtr;
2788  Result.setFlag(Token::LeadingSpace);
2789  return false;
2790 }
2791 
2792 //===----------------------------------------------------------------------===//
2793 // Primary Lexing Entry Points
2794 //===----------------------------------------------------------------------===//
2795 
2796 /// ReadToEndOfLine - Read the rest of the current preprocessor line as an
2797 /// uninterpreted string. This switches the lexer out of directive mode.
2799  assert(ParsingPreprocessorDirective && ParsingFilename == false &&
2800  "Must be in a preprocessing directive!");
2801  Token Tmp;
2802  Tmp.startToken();
2803 
2804  // CurPtr - Cache BufferPtr in an automatic variable.
2805  const char *CurPtr = BufferPtr;
2806  while (true) {
2807  char Char = getAndAdvanceChar(CurPtr, Tmp);
2808  switch (Char) {
2809  default:
2810  if (Result)
2811  Result->push_back(Char);
2812  break;
2813  case 0: // Null.
2814  // Found end of file?
2815  if (CurPtr-1 != BufferEnd) {
2816  if (isCodeCompletionPoint(CurPtr-1)) {
2818  cutOffLexing();
2819  return;
2820  }
2821 
2822  // Nope, normal character, continue.
2823  if (Result)
2824  Result->push_back(Char);
2825  break;
2826  }
2827  // FALL THROUGH.
2828  LLVM_FALLTHROUGH;
2829  case '\r':
2830  case '\n':
2831  // Okay, we found the end of the line. First, back up past the \0, \r, \n.
2832  assert(CurPtr[-1] == Char && "Trigraphs for newline?");
2833  BufferPtr = CurPtr-1;
2834 
2835  // Next, lex the character, which should handle the EOD transition.
2836  Lex(Tmp);
2837  if (Tmp.is(tok::code_completion)) {
2838  if (PP)
2840  Lex(Tmp);
2841  }
2842  assert(Tmp.is(tok::eod) && "Unexpected token!");
2843 
2844  // Finally, we're done;
2845  return;
2846  }
2847  }
2848 }
2849 
2850 /// LexEndOfFile - CurPtr points to the end of this file. Handle this
2851 /// condition, reporting diagnostics and handling other edge cases as required.
2852 /// This returns true if Result contains a token, false if PP.Lex should be
2853 /// called again.
2854 bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
2855  // If we hit the end of the file while parsing a preprocessor directive,
2856  // end the preprocessor directive first. The next token returned will
2857  // then be the end of file.
2859  // Done parsing the "line".
2861  // Update the location of token as well as BufferPtr.
2862  FormTokenWithChars(Result, CurPtr, tok::eod);
2863 
2864  // Restore comment saving mode, in case it was disabled for directive.
2865  if (PP)
2867  return true; // Have a token.
2868  }
2869 
2870  // If we are in raw mode, return this event as an EOF token. Let the caller
2871  // that put us in raw mode handle the event.
2872  if (isLexingRawMode()) {
2873  Result.startToken();
2874  BufferPtr = BufferEnd;
2875  FormTokenWithChars(Result, BufferEnd, tok::eof);
2876  return true;
2877  }
2878 
2879  if (PP->isRecordingPreamble() && PP->isInPrimaryFile()) {
2881  // If the preamble cuts off the end of a header guard, consider it guarded.
2882  // The guard is valid for the preamble content itself, and for tools the
2883  // most useful answer is "yes, this file has a header guard".
2884  if (!ConditionalStack.empty())
2886  ConditionalStack.clear();
2887  }
2888 
2889  // Issue diagnostics for unterminated #if and missing newline.
2890 
2891  // If we are in a #if directive, emit an error.
2892  while (!ConditionalStack.empty()) {
2893  if (PP->getCodeCompletionFileLoc() != FileLoc)
2894  PP->Diag(ConditionalStack.back().IfLoc,
2895  diag::err_pp_unterminated_conditional);
2896  ConditionalStack.pop_back();
2897  }
2898 
2899  SourceLocation EndLoc = getSourceLocation(BufferEnd);
2900  // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
2901  // a pedwarn.
2902  if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r')) {
2903  DiagnosticsEngine &Diags = PP->getDiagnostics();
2904  unsigned DiagID;
2905 
2906  if (LangOpts.CPlusPlus11) {
2907  // C++11 [lex.phases] 2.2 p2
2908  // Prefer the C++98 pedantic compatibility warning over the generic,
2909  // non-extension, user-requested "missing newline at EOF" warning.
2910  if (!Diags.isIgnored(diag::warn_cxx98_compat_no_newline_eof, EndLoc)) {
2911  DiagID = diag::warn_cxx98_compat_no_newline_eof;
2912  } else {
2913  DiagID = diag::warn_no_newline_eof;
2914  }
2915  } else {
2916  DiagID = diag::ext_no_newline_eof;
2917  }
2918 
2919  Diag(BufferEnd, DiagID)
2920  << FixItHint::CreateInsertion(EndLoc, "\n");
2921  }
2922 
2923  BufferPtr = CurPtr;
2924 
2925  // Finally, let the preprocessor handle this.
2926  return PP->HandleEndOfFile(Result, EndLoc, isPragmaLexer());
2927 }
2928 
2929 /// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
2930 /// the specified lexer will return a tok::l_paren token, 0 if it is something
2931 /// else and 2 if there are no more tokens in the buffer controlled by the
2932 /// lexer.
2933 unsigned Lexer::isNextPPTokenLParen() {
2934  assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
2935 
2936  // Switch to 'skipping' mode. This will ensure that we can lex a token
2937  // without emitting diagnostics, disables macro expansion, and will cause EOF
2938  // to return an EOF token instead of popping the include stack.
2939  LexingRawMode = true;
2940 
2941  // Save state that can be changed while lexing so that we can restore it.
2942  const char *TmpBufferPtr = BufferPtr;
2943  bool inPPDirectiveMode = ParsingPreprocessorDirective;
2944  bool atStartOfLine = IsAtStartOfLine;
2945  bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine;
2946  bool leadingSpace = HasLeadingSpace;
2947 
2948  Token Tok;
2949  Lex(Tok);
2950 
2951  // Restore state that may have changed.
2952  BufferPtr = TmpBufferPtr;
2953  ParsingPreprocessorDirective = inPPDirectiveMode;
2954  HasLeadingSpace = leadingSpace;
2955  IsAtStartOfLine = atStartOfLine;
2956  IsAtPhysicalStartOfLine = atPhysicalStartOfLine;
2957 
2958  // Restore the lexer back to non-skipping mode.
2959  LexingRawMode = false;
2960 
2961  if (Tok.is(tok::eof))
2962  return 2;
2963  return Tok.is(tok::l_paren);
2964 }
2965 
2966 /// Find the end of a version control conflict marker.
2967 static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd,
2968  ConflictMarkerKind CMK) {
2969  const char *Terminator = CMK == CMK_Perforce ? "<<<<\n" : ">>>>>>>";
2970  size_t TermLen = CMK == CMK_Perforce ? 5 : 7;
2971  auto RestOfBuffer = StringRef(CurPtr, BufferEnd - CurPtr).substr(TermLen);
2972  size_t Pos = RestOfBuffer.find(Terminator);
2973  while (Pos != StringRef::npos) {
2974  // Must occur at start of line.
2975  if (Pos == 0 ||
2976  (RestOfBuffer[Pos - 1] != '\r' && RestOfBuffer[Pos - 1] != '\n')) {
2977  RestOfBuffer = RestOfBuffer.substr(Pos+TermLen);
2978  Pos = RestOfBuffer.find(Terminator);
2979  continue;
2980  }
2981  return RestOfBuffer.data()+Pos;
2982  }
2983  return nullptr;
2984 }
2985 
2986 /// IsStartOfConflictMarker - If the specified pointer is the start of a version
2987 /// control conflict marker like '<<<<<<<', recognize it as such, emit an error
2988 /// and recover nicely. This returns true if it is a conflict marker and false
2989 /// if not.
2990 bool Lexer::IsStartOfConflictMarker(const char *CurPtr) {
2991  // Only a conflict marker if it starts at the beginning of a line.
2992  if (CurPtr != BufferStart &&
2993  CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2994  return false;
2995 
2996  // Check to see if we have <<<<<<< or >>>>.
2997  if (!StringRef(CurPtr, BufferEnd - CurPtr).startswith("<<<<<<<") &&
2998  !StringRef(CurPtr, BufferEnd - CurPtr).startswith(">>>> "))
2999  return false;
3000 
3001  // If we have a situation where we don't care about conflict markers, ignore
3002  // it.
3003  if (CurrentConflictMarkerState || isLexingRawMode())
3004  return false;
3005 
3006  ConflictMarkerKind Kind = *CurPtr == '<' ? CMK_Normal : CMK_Perforce;
3007 
3008  // Check to see if there is an ending marker somewhere in the buffer at the
3009  // start of a line to terminate this conflict marker.
3010  if (FindConflictEnd(CurPtr, BufferEnd, Kind)) {
3011  // We found a match. We are really in a conflict marker.
3012  // Diagnose this, and ignore to the end of line.
3013  Diag(CurPtr, diag::err_conflict_marker);
3014  CurrentConflictMarkerState = Kind;
3015 
3016  // Skip ahead to the end of line. We know this exists because the
3017  // end-of-conflict marker starts with \r or \n.
3018  while (*CurPtr != '\r' && *CurPtr != '\n') {
3019  assert(CurPtr != BufferEnd && "Didn't find end of line");
3020  ++CurPtr;
3021  }
3022  BufferPtr = CurPtr;
3023  return true;
3024  }
3025 
3026  // No end of conflict marker found.
3027  return false;
3028 }
3029 
3030 /// HandleEndOfConflictMarker - If this is a '====' or '||||' or '>>>>', or if
3031 /// it is '<<<<' and the conflict marker started with a '>>>>' marker, then it
3032 /// is the end of a conflict marker. Handle it by ignoring up until the end of
3033 /// the line. This returns true if it is a conflict marker and false if not.
3034 bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) {
3035  // Only a conflict marker if it starts at the beginning of a line.
3036  if (CurPtr != BufferStart &&
3037  CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
3038  return false;
3039 
3040  // If we have a situation where we don't care about conflict markers, ignore
3041  // it.
3042  if (!CurrentConflictMarkerState || isLexingRawMode())
3043  return false;
3044 
3045  // Check to see if we have the marker (4 characters in a row).
3046  for (unsigned i = 1; i != 4; ++i)
3047  if (CurPtr[i] != CurPtr[0])
3048  return false;
3049 
3050  // If we do have it, search for the end of the conflict marker. This could
3051  // fail if it got skipped with a '#if 0' or something. Note that CurPtr might
3052  // be the end of conflict marker.
3053  if (const char *End = FindConflictEnd(CurPtr, BufferEnd,
3054  CurrentConflictMarkerState)) {
3055  CurPtr = End;
3056 
3057  // Skip ahead to the end of line.
3058  while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n')
3059  ++CurPtr;
3060 
3061  BufferPtr = CurPtr;
3062 
3063  // No longer in the conflict marker.
3064  CurrentConflictMarkerState = CMK_None;
3065  return true;
3066  }
3067 
3068  return false;
3069 }
3070 
3071 static const char *findPlaceholderEnd(const char *CurPtr,
3072  const char *BufferEnd) {
3073  if (CurPtr == BufferEnd)
3074  return nullptr;
3075  BufferEnd -= 1; // Scan until the second last character.
3076  for (; CurPtr != BufferEnd; ++CurPtr) {
3077  if (CurPtr[0] == '#' && CurPtr[1] == '>')
3078  return CurPtr + 2;
3079  }
3080  return nullptr;
3081 }
3082 
3083 bool Lexer::lexEditorPlaceholder(Token &Result, const char *CurPtr) {
3084  assert(CurPtr[-1] == '<' && CurPtr[0] == '#' && "Not a placeholder!");
3086  return false;
3087  const char *End = findPlaceholderEnd(CurPtr + 1, BufferEnd);
3088  if (!End)
3089  return false;
3090  const char *Start = CurPtr - 1;
3091  if (!LangOpts.AllowEditorPlaceholders)
3092  Diag(Start, diag::err_placeholder_in_source);
3093  Result.startToken();
3094  FormTokenWithChars(Result, End, tok::raw_identifier);
3095  Result.setRawIdentifierData(Start);
3096  PP->LookUpIdentifierInfo(Result);
3097  Result.setFlag(Token::IsEditorPlaceholder);
3098  BufferPtr = End;
3099  return true;
3100 }
3101 
3102 bool Lexer::isCodeCompletionPoint(const char *CurPtr) const {
3103  if (PP && PP->isCodeCompletionEnabled()) {
3104  SourceLocation Loc = FileLoc.getLocWithOffset(CurPtr-BufferStart);
3105  return Loc == PP->getCodeCompletionLoc();
3106  }
3107 
3108  return false;
3109 }
3110 
3111 uint32_t Lexer::tryReadUCN(const char *&StartPtr, const char *SlashLoc,
3112  Token *Result) {
3113  unsigned CharSize;
3114  char Kind = getCharAndSize(StartPtr, CharSize);
3115  bool Delimited = false;
3116  bool FoundEndDelimiter = false;
3117  unsigned Count = 0;
3118  bool Diagnose = Result && !isLexingRawMode();
3119 
3120  unsigned NumHexDigits;
3121  if (Kind == 'u')
3122  NumHexDigits = 4;
3123  else if (Kind == 'U')
3124  NumHexDigits = 8;
3125  else
3126  return 0;
3127 
3128  if (!LangOpts.CPlusPlus && !LangOpts.C99) {
3129  if (Diagnose)
3130  Diag(SlashLoc, diag::warn_ucn_not_valid_in_c89);
3131  return 0;
3132  }
3133 
3134  const char *CurPtr = StartPtr + CharSize;
3135  const char *KindLoc = &CurPtr[-1];
3136 
3137  uint32_t CodePoint = 0;
3138  while (Count != NumHexDigits || Delimited) {
3139  char C = getCharAndSize(CurPtr, CharSize);
3140  if (!Delimited && C == '{') {
3141  Delimited = true;
3142  CurPtr += CharSize;
3143  continue;
3144  }
3145 
3146  if (Delimited && C == '}') {
3147  CurPtr += CharSize;
3148  FoundEndDelimiter = true;
3149  break;
3150  }
3151 
3152  unsigned Value = llvm::hexDigitValue(C);
3153  if (Value == -1U) {
3154  if (!Delimited)
3155  break;
3156  if (Diagnose)
3157  Diag(BufferPtr, diag::warn_delimited_ucn_incomplete)
3158  << StringRef(&C, 1);
3159  return 0;
3160  }
3161 
3162  if (CodePoint & 0xF000'0000) {
3163  if (Diagnose)
3164  Diag(KindLoc, diag::err_escape_too_large) << 0;
3165  return 0;
3166  }
3167 
3168  CodePoint <<= 4;
3169  CodePoint |= Value;
3170  CurPtr += CharSize;
3171  Count++;
3172  }
3173 
3174  if (Count == 0) {
3175  if (Diagnose)
3176  Diag(StartPtr, FoundEndDelimiter ? diag::warn_delimited_ucn_empty
3177  : diag::warn_ucn_escape_no_digits)
3178  << StringRef(KindLoc, 1);
3179  return 0;
3180  }
3181 
3182  if (!Delimited && Count != NumHexDigits) {
3183  if (Diagnose) {
3184  Diag(BufferPtr, diag::warn_ucn_escape_incomplete);
3185  // If the user wrote \U1234, suggest a fixit to \u.
3186  if (Count == 4 && NumHexDigits == 8) {
3187  CharSourceRange URange = makeCharRange(*this, KindLoc, KindLoc + 1);
3188  Diag(KindLoc, diag::note_ucn_four_not_eight)
3189  << FixItHint::CreateReplacement(URange, "u");
3190  }
3191  }
3192  return 0;
3193  }
3194 
3195  if (Delimited && PP) {
3196  Diag(BufferPtr, diag::ext_delimited_escape_sequence);
3197  }
3198 
3199  if (Result) {
3200  Result->setFlag(Token::HasUCN);
3201  if (CurPtr - StartPtr == (ptrdiff_t)(Count + 2 + (Delimited ? 2 : 0)))
3202  StartPtr = CurPtr;
3203  else
3204  while (StartPtr != CurPtr)
3205  (void)getAndAdvanceChar(StartPtr, *Result);
3206  } else {
3207  StartPtr = CurPtr;
3208  }
3209 
3210  // Don't apply C family restrictions to UCNs in assembly mode
3211  if (LangOpts.AsmPreprocessor)
3212  return CodePoint;
3213 
3214  // C99 6.4.3p2: A universal character name shall not specify a character whose
3215  // short identifier is less than 00A0 other than 0024 ($), 0040 (@), or
3216  // 0060 (`), nor one in the range D800 through DFFF inclusive.)
3217  // C++11 [lex.charset]p2: If the hexadecimal value for a
3218  // universal-character-name corresponds to a surrogate code point (in the
3219  // range 0xD800-0xDFFF, inclusive), the program is ill-formed. Additionally,
3220  // if the hexadecimal value for a universal-character-name outside the
3221  // c-char-sequence, s-char-sequence, or r-char-sequence of a character or
3222  // string literal corresponds to a control character (in either of the
3223  // ranges 0x00-0x1F or 0x7F-0x9F, both inclusive) or to a character in the
3224  // basic source character set, the program is ill-formed.
3225  if (CodePoint < 0xA0) {
3226  if (CodePoint == 0x24 || CodePoint == 0x40 || CodePoint == 0x60)
3227  return CodePoint;
3228 
3229  // We don't use isLexingRawMode() here because we need to warn about bad
3230  // UCNs even when skipping preprocessing tokens in a #if block.
3231  if (Result && PP) {
3232  if (CodePoint < 0x20 || CodePoint >= 0x7F)
3233  Diag(BufferPtr, diag::err_ucn_control_character);
3234  else {
3235  char C = static_cast<char>(CodePoint);
3236  Diag(BufferPtr, diag::err_ucn_escape_basic_scs) << StringRef(&C, 1);
3237  }
3238  }
3239 
3240  return 0;
3241  } else if (CodePoint >= 0xD800 && CodePoint <= 0xDFFF) {
3242  // C++03 allows UCNs representing surrogate characters. C99 and C++11 don't.
3243  // We don't use isLexingRawMode() here because we need to diagnose bad
3244  // UCNs even when skipping preprocessing tokens in a #if block.
3245  if (Result && PP) {
3246  if (LangOpts.CPlusPlus && !LangOpts.CPlusPlus11)
3247  Diag(BufferPtr, diag::warn_ucn_escape_surrogate);
3248  else
3249  Diag(BufferPtr, diag::err_ucn_escape_invalid);
3250  }
3251  return 0;
3252  }
3253 
3254  return CodePoint;
3255 }
3256 
3257 bool Lexer::CheckUnicodeWhitespace(Token &Result, uint32_t C,
3258  const char *CurPtr) {
3259  if (!isLexingRawMode() && !PP->isPreprocessedOutput() &&
3260  isUnicodeWhitespace(C)) {
3261  Diag(BufferPtr, diag::ext_unicode_whitespace)
3262  << makeCharRange(*this, BufferPtr, CurPtr);
3263 
3264  Result.setFlag(Token::LeadingSpace);
3265  return true;
3266  }
3267  return false;
3268 }
3269 
3270 void Lexer::PropagateLineStartLeadingSpaceInfo(Token &Result) {
3271  IsAtStartOfLine = Result.isAtStartOfLine();
3272  HasLeadingSpace = Result.hasLeadingSpace();
3273  HasLeadingEmptyMacro = Result.hasLeadingEmptyMacro();
3274  // Note that this doesn't affect IsAtPhysicalStartOfLine.
3275 }
3276 
3277 bool Lexer::Lex(Token &Result) {
3278  // Start a new token.
3279  Result.startToken();
3280 
3281  // Set up misc whitespace flags for LexTokenInternal.
3282  if (IsAtStartOfLine) {
3283  Result.setFlag(Token::StartOfLine);
3284  IsAtStartOfLine = false;
3285  }
3286 
3287  if (HasLeadingSpace) {
3288  Result.setFlag(Token::LeadingSpace);
3289  HasLeadingSpace = false;
3290  }
3291 
3292  if (HasLeadingEmptyMacro) {
3293  Result.setFlag(Token::LeadingEmptyMacro);
3294  HasLeadingEmptyMacro = false;
3295  }
3296 
3297  bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine;
3298  IsAtPhysicalStartOfLine = false;
3299  bool isRawLex = isLexingRawMode();
3300  (void) isRawLex;
3301  bool returnedToken = LexTokenInternal(Result, atPhysicalStartOfLine);
3302  // (After the LexTokenInternal call, the lexer might be destroyed.)
3303  assert((returnedToken || !isRawLex) && "Raw lex must succeed");
3304  return returnedToken;
3305 }
3306 
3307 /// LexTokenInternal - This implements a simple C family lexer. It is an
3308 /// extremely performance critical piece of code. This assumes that the buffer
3309 /// has a null character at the end of the file. This returns a preprocessing
3310 /// token, not a normal token, as such, it is an internal interface. It assumes
3311 /// that the Flags of result have been cleared before calling this.
3312 bool Lexer::LexTokenInternal(Token &Result, bool TokAtPhysicalStartOfLine) {
3313 LexNextToken:
3314  // New token, can't need cleaning yet.
3315  Result.clearFlag(Token::NeedsCleaning);
3316  Result.setIdentifierInfo(nullptr);
3317 
3318  // CurPtr - Cache BufferPtr in an automatic variable.
3319  const char *CurPtr = BufferPtr;
3320 
3321  // Small amounts of horizontal whitespace is very common between tokens.
3322  if (isHorizontalWhitespace(*CurPtr)) {
3323  do {
3324  ++CurPtr;
3325  } while (isHorizontalWhitespace(*CurPtr));
3326 
3327  // If we are keeping whitespace and other tokens, just return what we just
3328  // skipped. The next lexer invocation will return the token after the
3329  // whitespace.
3330  if (isKeepWhitespaceMode()) {
3331  FormTokenWithChars(Result, CurPtr, tok::unknown);
3332  // FIXME: The next token will not have LeadingSpace set.
3333  return true;
3334  }
3335 
3336  BufferPtr = CurPtr;
3337  Result.setFlag(Token::LeadingSpace);
3338  }
3339 
3340  unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
3341 
3342  // Read a character, advancing over it.
3343  char Char = getAndAdvanceChar(CurPtr, Result);
3345 
3346  if (!isVerticalWhitespace(Char))
3347  NewLinePtr = nullptr;
3348 
3349  switch (Char) {
3350  case 0: // Null.
3351  // Found end of file?
3352  if (CurPtr-1 == BufferEnd)
3353  return LexEndOfFile(Result, CurPtr-1);
3354 
3355  // Check if we are performing code completion.
3356  if (isCodeCompletionPoint(CurPtr-1)) {
3357  // Return the code-completion token.
3358  Result.startToken();
3359  FormTokenWithChars(Result, CurPtr, tok::code_completion);
3360  return true;
3361  }
3362 
3363  if (!isLexingRawMode())
3364  Diag(CurPtr-1, diag::null_in_file);
3365  Result.setFlag(Token::LeadingSpace);
3366  if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3367  return true; // KeepWhitespaceMode
3368 
3369  // We know the lexer hasn't changed, so just try again with this lexer.
3370  // (We manually eliminate the tail call to avoid recursion.)
3371  goto LexNextToken;
3372 
3373  case 26: // DOS & CP/M EOF: "^Z".
3374  // If we're in Microsoft extensions mode, treat this as end of file.
3375  if (LangOpts.MicrosoftExt) {
3376  if (!isLexingRawMode())
3377  Diag(CurPtr-1, diag::ext_ctrl_z_eof_microsoft);
3378  return LexEndOfFile(Result, CurPtr-1);
3379  }
3380 
3381  // If Microsoft extensions are disabled, this is just random garbage.
3382  Kind = tok::unknown;
3383  break;
3384 
3385  case '\r':
3386  if (CurPtr[0] == '\n')
3387  (void)getAndAdvanceChar(CurPtr, Result);
3388  LLVM_FALLTHROUGH;
3389  case '\n':
3390  // If we are inside a preprocessor directive and we see the end of line,
3391  // we know we are done with the directive, so return an EOD token.
3393  // Done parsing the "line".
3395 
3396  // Restore comment saving mode, in case it was disabled for directive.
3397  if (PP)
3399 
3400  // Since we consumed a newline, we are back at the start of a line.
3401  IsAtStartOfLine = true;
3402  IsAtPhysicalStartOfLine = true;
3403  NewLinePtr = CurPtr - 1;
3404 
3405  Kind = tok::eod;
3406  break;
3407  }
3408 
3409  // No leading whitespace seen so far.
3410  Result.clearFlag(Token::LeadingSpace);
3411 
3412  if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3413  return true; // KeepWhitespaceMode
3414 
3415  // We only saw whitespace, so just try again with this lexer.
3416  // (We manually eliminate the tail call to avoid recursion.)
3417  goto LexNextToken;
3418  case ' ':
3419  case '\t':
3420  case '\f':
3421  case '\v':
3422  SkipHorizontalWhitespace:
3423  Result.setFlag(Token::LeadingSpace);
3424  if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3425  return true; // KeepWhitespaceMode
3426 
3427  SkipIgnoredUnits:
3428  CurPtr = BufferPtr;
3429 
3430  // If the next token is obviously a // or /* */ comment, skip it efficiently
3431  // too (without going through the big switch stmt).
3432  if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
3433  LangOpts.LineComment &&
3434  (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP)) {
3435  if (SkipLineComment(Result, CurPtr+2, TokAtPhysicalStartOfLine))
3436  return true; // There is a token to return.
3437  goto SkipIgnoredUnits;
3438  } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
3439  if (SkipBlockComment(Result, CurPtr+2, TokAtPhysicalStartOfLine))
3440  return true; // There is a token to return.
3441  goto SkipIgnoredUnits;
3442  } else if (isHorizontalWhitespace(*CurPtr)) {
3443  goto SkipHorizontalWhitespace;
3444  }
3445  // We only saw whitespace, so just try again with this lexer.
3446  // (We manually eliminate the tail call to avoid recursion.)
3447  goto LexNextToken;
3448 
3449  // C99 6.4.4.1: Integer Constants.
3450  // C99 6.4.4.2: Floating Constants.
3451  case '0': case '1': case '2': case '3': case '4':
3452  case '5': case '6': case '7': case '8': case '9':
3453  // Notify MIOpt that we read a non-whitespace/non-comment token.
3454  MIOpt.ReadToken();
3455  return LexNumericConstant(Result, CurPtr);
3456 
3457  case 'u': // Identifier (uber) or C11/C++11 UTF-8 or UTF-16 string literal
3458  // Notify MIOpt that we read a non-whitespace/non-comment token.
3459  MIOpt.ReadToken();
3460 
3461  if (LangOpts.CPlusPlus11 || LangOpts.C11) {
3462  Char = getCharAndSize(CurPtr, SizeTmp);
3463 
3464  // UTF-16 string literal
3465  if (Char == '"')
3466  return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3467  tok::utf16_string_literal);
3468 
3469  // UTF-16 character constant
3470  if (Char == '\'')
3471  return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3472  tok::utf16_char_constant);
3473 
3474  // UTF-16 raw string literal
3475  if (Char == 'R' && LangOpts.CPlusPlus11 &&
3476  getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
3477  return LexRawStringLiteral(Result,
3478  ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3479  SizeTmp2, Result),
3480  tok::utf16_string_literal);
3481 
3482  if (Char == '8') {
3483  char Char2 = getCharAndSize(CurPtr + SizeTmp, SizeTmp2);
3484 
3485  // UTF-8 string literal
3486  if (Char2 == '"')
3487  return LexStringLiteral(Result,
3488  ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3489  SizeTmp2, Result),
3490  tok::utf8_string_literal);
3491  if (Char2 == '\'' && LangOpts.CPlusPlus17)
3492  return LexCharConstant(
3493  Result, ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3494  SizeTmp2, Result),
3495  tok::utf8_char_constant);
3496 
3497  if (Char2 == 'R' && LangOpts.CPlusPlus11) {
3498  unsigned SizeTmp3;
3499  char Char3 = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3500  // UTF-8 raw string literal
3501  if (Char3 == '"') {
3502  return LexRawStringLiteral(Result,
3503  ConsumeChar(ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3504  SizeTmp2, Result),
3505  SizeTmp3, Result),
3506  tok::utf8_string_literal);
3507  }
3508  }
3509  }
3510  }
3511 
3512  // treat u like the start of an identifier.
3513  return LexIdentifierContinue(Result, CurPtr);
3514 
3515  case 'U': // Identifier (Uber) or C11/C++11 UTF-32 string literal
3516  // Notify MIOpt that we read a non-whitespace/non-comment token.
3517  MIOpt.ReadToken();
3518 
3519  if (LangOpts.CPlusPlus11 || LangOpts.C11) {
3520  Char = getCharAndSize(CurPtr, SizeTmp);
3521 
3522  // UTF-32 string literal
3523  if (Char == '"')
3524  return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3525  tok::utf32_string_literal);
3526 
3527  // UTF-32 character constant
3528  if (Char == '\'')
3529  return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3530  tok::utf32_char_constant);
3531 
3532  // UTF-32 raw string literal
3533  if (Char == 'R' && LangOpts.CPlusPlus11 &&
3534  getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
3535  return LexRawStringLiteral(Result,
3536  ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3537  SizeTmp2, Result),
3538  tok::utf32_string_literal);
3539  }
3540 
3541  // treat U like the start of an identifier.
3542  return LexIdentifierContinue(Result, CurPtr);
3543 
3544  case 'R': // Identifier or C++0x raw string literal
3545  // Notify MIOpt that we read a non-whitespace/non-comment token.
3546  MIOpt.ReadToken();
3547 
3548  if (LangOpts.CPlusPlus11) {
3549  Char = getCharAndSize(CurPtr, SizeTmp);
3550 
3551  if (Char == '"')
3552  return LexRawStringLiteral(Result,
3553  ConsumeChar(CurPtr, SizeTmp, Result),
3554  tok::string_literal);
3555  }
3556 
3557  // treat R like the start of an identifier.
3558  return LexIdentifierContinue(Result, CurPtr);
3559 
3560  case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
3561  // Notify MIOpt that we read a non-whitespace/non-comment token.
3562  MIOpt.ReadToken();
3563  Char = getCharAndSize(CurPtr, SizeTmp);
3564 
3565  // Wide string literal.
3566  if (Char == '"')
3567  return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3568  tok::wide_string_literal);
3569 
3570  // Wide raw string literal.
3571  if (LangOpts.CPlusPlus11 && Char == 'R' &&
3572  getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
3573  return LexRawStringLiteral(Result,
3574  ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3575  SizeTmp2, Result),
3576  tok::wide_string_literal);
3577 
3578  // Wide character constant.
3579  if (Char == '\'')
3580  return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3581  tok::wide_char_constant);
3582  // FALL THROUGH, treating L like the start of an identifier.
3583  LLVM_FALLTHROUGH;
3584 
3585  // C99 6.4.2: Identifiers.
3586  case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
3587  case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
3588  case 'O': case 'P': case 'Q': /*'R'*/case 'S': case 'T': /*'U'*/
3589  case 'V': case 'W': case 'X': case 'Y': case 'Z':
3590  case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
3591  case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
3592  case 'o': case 'p': case 'q': case 'r': case 's': case 't': /*'u'*/
3593  case 'v': case 'w': case 'x': case 'y': case 'z':
3594  case '_':
3595  // Notify MIOpt that we read a non-whitespace/non-comment token.
3596  MIOpt.ReadToken();
3597  return LexIdentifierContinue(Result, CurPtr);
3598 
3599  case '$': // $ in identifiers.
3600  if (LangOpts.DollarIdents) {
3601  if (!isLexingRawMode())
3602  Diag(CurPtr-1, diag::ext_dollar_in_identifier);
3603  // Notify MIOpt that we read a non-whitespace/non-comment token.
3604  MIOpt.ReadToken();
3605  return LexIdentifierContinue(Result, CurPtr);
3606  }
3607 
3608  Kind = tok::unknown;
3609  break;
3610 
3611  // C99 6.4.4: Character Constants.
3612  case '\'':
3613  // Notify MIOpt that we read a non-whitespace/non-comment token.
3614  MIOpt.ReadToken();
3615  return LexCharConstant(Result, CurPtr, tok::char_constant);
3616 
3617  // C99 6.4.5: String Literals.
3618  case '"':
3619  // Notify MIOpt that we read a non-whitespace/non-comment token.
3620  MIOpt.ReadToken();
3621  return LexStringLiteral(Result, CurPtr,
3622  ParsingFilename ? tok::header_name
3623  : tok::string_literal);
3624 
3625  // C99 6.4.6: Punctuators.
3626  case '?':
3627  Kind = tok::question;
3628  break;
3629  case '[':
3630  Kind = tok::l_square;
3631  break;
3632  case ']':
3633  Kind = tok::r_square;
3634  break;
3635  case '(':
3636  Kind = tok::l_paren;
3637  break;
3638  case ')':
3639  Kind = tok::r_paren;
3640  break;
3641  case '{':
3642  Kind = tok::l_brace;
3643  break;
3644  case '}':
3645  Kind = tok::r_brace;
3646  break;
3647  case '.':
3648  Char = getCharAndSize(CurPtr, SizeTmp);
3649  if (Char >= '0' && Char <= '9') {
3650  // Notify MIOpt that we read a non-whitespace/non-comment token.
3651  MIOpt.ReadToken();
3652 
3653  return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
3654  } else if (LangOpts.CPlusPlus && Char == '*') {
3655  Kind = tok::periodstar;
3656  CurPtr += SizeTmp;
3657  } else if (Char == '.' &&
3658  getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
3659  Kind = tok::ellipsis;
3660  CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3661  SizeTmp2, Result);
3662  } else {
3663  Kind = tok::period;
3664  }
3665  break;
3666  case '&':
3667  Char = getCharAndSize(CurPtr, SizeTmp);
3668  if (Char == '&') {
3669  Kind = tok::ampamp;
3670  CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3671  } else if (Char == '=') {
3672  Kind = tok::ampequal;
3673  CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3674  } else {
3675  Kind = tok::amp;
3676  }
3677  break;
3678  case '*':
3679  if (getCharAndSize(CurPtr, SizeTmp) == '=') {
3680  Kind = tok::starequal;
3681  CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3682  } else {
3683  Kind = tok::star;
3684  }
3685  break;
3686  case '+':
3687  Char = getCharAndSize(CurPtr, SizeTmp);
3688  if (Char == '+') {
3689  CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3690  Kind = tok::plusplus;
3691  } else if (Char == '=') {
3692  CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3693  Kind = tok::plusequal;
3694  } else {
3695  Kind = tok::plus;
3696  }
3697  break;
3698  case '-':
3699  Char = getCharAndSize(CurPtr, SizeTmp);
3700  if (Char == '-') { // --
3701  CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3702  Kind = tok::minusminus;
3703  } else if (Char == '>' && LangOpts.CPlusPlus &&
3704  getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
3705  CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3706  SizeTmp2, Result);
3707  Kind = tok::arrowstar;
3708  } else if (Char == '>') { // ->
3709  CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3710  Kind = tok::arrow;
3711  } else if (Char == '=') { // -=
3712  CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3713  Kind = tok::minusequal;
3714  } else {
3715  Kind = tok::minus;
3716  }
3717  break;
3718  case '~':
3719  Kind = tok::tilde;
3720  break;
3721  case '!':
3722  if (getCharAndSize(CurPtr, SizeTmp) == '=') {
3723  Kind = tok::exclaimequal;
3724  CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3725  } else {
3726  Kind = tok::exclaim;
3727  }
3728  break;
3729  case '/':
3730  // 6.4.9: Comments
3731  Char = getCharAndSize(CurPtr, SizeTmp);
3732  if (Char == '/') { // Line comment.
3733  // Even if Line comments are disabled (e.g. in C89 mode), we generally
3734  // want to lex this as a comment. There is one problem with this though,
3735  // that in one particular corner case, this can change the behavior of the
3736  // resultant program. For example, In "foo //**/ bar", C89 would lex
3737  // this as "foo / bar" and languages with Line comments would lex it as
3738  // "foo". Check to see if the character after the second slash is a '*'.
3739  // If so, we will lex that as a "/" instead of the start of a comment.
3740  // However, we never do this if we are just preprocessing.
3741  bool TreatAsComment = LangOpts.LineComment &&
3742  (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP);
3743  if (!TreatAsComment)
3744  if (!(PP && PP->isPreprocessedOutput()))
3745  TreatAsComment = getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*';
3746 
3747  if (TreatAsComment) {
3748  if (SkipLineComment(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3749  TokAtPhysicalStartOfLine))
3750  return true; // There is a token to return.
3751 
3752  // It is common for the tokens immediately after a // comment to be
3753  // whitespace (indentation for the next line). Instead of going through
3754  // the big switch, handle it efficiently now.
3755  goto SkipIgnoredUnits;
3756  }
3757  }
3758 
3759  if (Char == '*') { // /**/ comment.
3760  if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3761  TokAtPhysicalStartOfLine))
3762  return true; // There is a token to return.
3763 
3764  // We only saw whitespace, so just try again with this lexer.
3765  // (We manually eliminate the tail call to avoid recursion.)
3766  goto LexNextToken;
3767  }
3768 
3769  if (Char == '=') {
3770  CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3771  Kind = tok::slashequal;
3772  } else {
3773  Kind = tok::slash;
3774  }
3775  break;
3776  case '%':
3777  Char = getCharAndSize(CurPtr, SizeTmp);
3778  if (Char == '=') {
3779  Kind = tok::percentequal;
3780  CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3781  } else if (LangOpts.Digraphs && Char == '>') {
3782  Kind = tok::r_brace; // '%>' -> '}'
3783  CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3784  } else if (LangOpts.Digraphs && Char == ':') {
3785  CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3786  Char = getCharAndSize(CurPtr, SizeTmp);
3787  if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
3788  Kind = tok::hashhash; // '%:%:' -> '##'
3789  CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3790  SizeTmp2, Result);
3791  } else if (Char == '@' && LangOpts.MicrosoftExt) {// %:@ -> #@ -> Charize
3792  CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3793  if (!isLexingRawMode())
3794  Diag(BufferPtr, diag::ext_charize_microsoft);
3795  Kind = tok::hashat;
3796  } else { // '%:' -> '#'
3797  // We parsed a # character. If this occurs at the start of the line,
3798  // it's actually the start of a preprocessing directive. Callback to
3799  // the preprocessor to handle it.
3800  // TODO: -fpreprocessed mode??
3801  if (TokAtPhysicalStartOfLine && !LexingRawMode && !Is_PragmaLexer)
3802  goto HandleDirective;
3803 
3804  Kind = tok::hash;
3805  }
3806  } else {
3807  Kind = tok::percent;
3808  }
3809  break;
3810  case '<':
3811  Char = getCharAndSize(CurPtr, SizeTmp);
3812  if (ParsingFilename) {
3813  return LexAngledStringLiteral(Result, CurPtr);
3814  } else if (Char == '<') {
3815  char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3816  if (After == '=') {
3817  Kind = tok::lesslessequal;
3818  CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3819  SizeTmp2, Result);
3820  } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) {
3821  // If this is actually a '<<<<<<<' version control conflict marker,
3822  // recognize it as such and recover nicely.
3823  goto LexNextToken;
3824  } else if (After == '<' && HandleEndOfConflictMarker(CurPtr-1)) {
3825  // If this is '<<<<' and we're in a Perforce-style conflict marker,
3826  // ignore it.
3827  goto LexNextToken;
3828  } else if (LangOpts.CUDA && After == '<') {
3829  Kind = tok::lesslessless;
3830  CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3831  SizeTmp2, Result);
3832  } else {
3833  CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3834  Kind = tok::lessless;
3835  }
3836  } else if (Char == '=') {
3837  char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3838  if (After == '>') {
3839  if (getLangOpts().CPlusPlus20) {
3840  if (!isLexingRawMode())
3841  Diag(BufferPtr, diag::warn_cxx17_compat_spaceship);
3842  CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3843  SizeTmp2, Result);
3844  Kind = tok::spaceship;
3845  break;
3846  }
3847  // Suggest adding a space between the '<=' and the '>' to avoid a
3848  // change in semantics if this turns up in C++ <=17 mode.
3849  if (getLangOpts().CPlusPlus && !isLexingRawMode()) {
3850  Diag(BufferPtr, diag::warn_cxx20_compat_spaceship)
3852  getSourceLocation(CurPtr + SizeTmp, SizeTmp2), " ");
3853  }
3854  }
3855  CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3856  Kind = tok::lessequal;
3857  } else if (LangOpts.Digraphs && Char == ':') { // '<:' -> '['
3858  if (LangOpts.CPlusPlus11 &&
3859  getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == ':') {
3860  // C++0x [lex.pptoken]p3:
3861  // Otherwise, if the next three characters are <:: and the subsequent
3862  // character is neither : nor >, the < is treated as a preprocessor
3863  // token by itself and not as the first character of the alternative
3864  // token <:.
3865  unsigned SizeTmp3;
3866  char After = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3867  if (After != ':' && After != '>') {
3868  Kind = tok::less;
3869  if (!isLexingRawMode())
3870  Diag(BufferPtr, diag::warn_cxx98_compat_less_colon_colon);
3871  break;
3872  }
3873  }
3874 
3875  CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3876  Kind = tok::l_square;
3877  } else if (LangOpts.Digraphs && Char == '%') { // '<%' -> '{'
3878  CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3879  Kind = tok::l_brace;
3880  } else if (Char == '#' && /*Not a trigraph*/ SizeTmp == 1 &&
3881  lexEditorPlaceholder(Result, CurPtr)) {
3882  return true;
3883  } else {
3884  Kind = tok::less;
3885  }
3886  break;
3887  case '>':
3888  Char = getCharAndSize(CurPtr, SizeTmp);
3889  if (Char == '=') {
3890  CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3891  Kind = tok::greaterequal;
3892  } else if (Char == '>') {
3893  char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3894  if (After == '=') {
3895  CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3896  SizeTmp2, Result);
3897  Kind = tok::greatergreaterequal;
3898  } else if (After == '>' && IsStartOfConflictMarker(CurPtr-1)) {
3899  // If this is actually a '>>>>' conflict marker, recognize it as such
3900  // and recover nicely.
3901  goto LexNextToken;
3902  } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) {
3903  // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
3904  goto LexNextToken;
3905  } else if (LangOpts.CUDA && After == '>') {
3906  Kind = tok::greatergreatergreater;
3907  CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3908  SizeTmp2, Result);
3909  } else {
3910  CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3911  Kind = tok::greatergreater;
3912  }
3913  } else {
3914  Kind = tok::greater;
3915  }
3916  break;
3917  case '^':
3918  Char = getCharAndSize(CurPtr, SizeTmp);
3919  if (Char == '=') {
3920  CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3921  Kind = tok::caretequal;
3922  } else if (LangOpts.OpenCL && Char == '^') {
3923  CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3924  Kind = tok::caretcaret;
3925  } else {
3926  Kind = tok::caret;
3927  }
3928  break;
3929  case '|':
3930  Char = getCharAndSize(CurPtr, SizeTmp);
3931  if (Char == '=') {
3932  Kind = tok::pipeequal;
3933  CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3934  } else if (Char == '|') {
3935  // If this is '|||||||' and we're in a conflict marker, ignore it.
3936  if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
3937  goto LexNextToken;
3938  Kind = tok::pipepipe;
3939  CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3940  } else {
3941  Kind = tok::pipe;
3942  }
3943  break;
3944  case ':':
3945  Char = getCharAndSize(CurPtr, SizeTmp);
3946  if (LangOpts.Digraphs && Char == '>') {
3947  Kind = tok::r_square; // ':>' -> ']'
3948  CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3949  } else if ((LangOpts.CPlusPlus ||
3950  LangOpts.DoubleSquareBracketAttributes) &&
3951  Char == ':') {
3952  Kind = tok::coloncolon;
3953  CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3954  } else {
3955  Kind = tok::colon;
3956  }
3957  break;
3958  case ';':
3959  Kind = tok::semi;
3960  break;
3961  case '=':
3962  Char = getCharAndSize(CurPtr, SizeTmp);
3963  if (Char == '=') {
3964  // If this is '====' and we're in a conflict marker, ignore it.
3965  if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
3966  goto LexNextToken;
3967 
3968  Kind = tok::equalequal;
3969  CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3970  } else {
3971  Kind = tok::equal;
3972  }
3973  break;
3974  case ',':
3975  Kind = tok::comma;
3976  break;
3977  case '#':
3978  Char = getCharAndSize(CurPtr, SizeTmp);
3979  if (Char == '#') {
3980  Kind = tok::hashhash;
3981  CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3982  } else if (Char == '@' && LangOpts.MicrosoftExt) { // #@ -> Charize
3983  Kind = tok::hashat;
3984  if (!isLexingRawMode())
3985  Diag(BufferPtr, diag::ext_charize_microsoft);
3986  CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3987  } else {
3988  // We parsed a # character. If this occurs at the start of the line,
3989  // it's actually the start of a preprocessing directive. Callback to
3990  // the preprocessor to handle it.
3991  // TODO: -fpreprocessed mode??
3992  if (TokAtPhysicalStartOfLine && !LexingRawMode && !Is_PragmaLexer)
3993  goto HandleDirective;
3994 
3995  Kind = tok::hash;
3996  }
3997  break;
3998 
3999  case '@':
4000  // Objective C support.
4001  if (CurPtr[-1] == '@' && LangOpts.ObjC)
4002  Kind = tok::at;
4003  else
4004  Kind = tok::unknown;
4005  break;
4006 
4007  // UCNs (C99 6.4.3, C++11 [lex.charset]p2)
4008  case '\\':
4009  if (!LangOpts.AsmPreprocessor) {
4010  if (uint32_t CodePoint = tryReadUCN(CurPtr, BufferPtr, &Result)) {
4011  if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) {
4012  if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
4013  return true; // KeepWhitespaceMode
4014 
4015  // We only saw whitespace, so just try again with this lexer.
4016  // (We manually eliminate the tail call to avoid recursion.)
4017  goto LexNextToken;
4018  }
4019 
4020  return LexUnicodeIdentifierStart(Result, CodePoint, CurPtr);
4021  }
4022  }
4023 
4024  Kind = tok::unknown;
4025  break;
4026 
4027  default: {
4028  if (isASCII(Char)) {
4029  Kind = tok::unknown;
4030  break;
4031  }
4032 
4033  llvm::UTF32 CodePoint;
4034 
4035  // We can't just reset CurPtr to BufferPtr because BufferPtr may point to
4036  // an escaped newline.
4037  --CurPtr;
4038  llvm::ConversionResult Status =
4039  llvm::convertUTF8Sequence((const llvm::UTF8 **)&CurPtr,
4040  (const llvm::UTF8 *)BufferEnd,
4041  &CodePoint,
4042  llvm::strictConversion);
4043  if (Status == llvm::conversionOK) {
4044  if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) {
4045  if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
4046  return true; // KeepWhitespaceMode
4047 
4048  // We only saw whitespace, so just try again with this lexer.
4049  // (We manually eliminate the tail call to avoid recursion.)
4050  goto LexNextToken;
4051  }
4052  return LexUnicodeIdentifierStart(Result, CodePoint, CurPtr);
4053  }
4054 
4056  PP->isPreprocessedOutput()) {
4057  ++CurPtr;
4058  Kind = tok::unknown;
4059  break;
4060  }
4061 
4062  // Non-ASCII characters tend to creep into source code unintentionally.
4063  // Instead of letting the parser complain about the unknown token,
4064  // just diagnose the invalid UTF-8, then drop the character.
4065  Diag(CurPtr, diag::err_invalid_utf8);
4066 
4067  BufferPtr = CurPtr+1;
4068  // We're pretending the character didn't exist, so just try again with
4069  // this lexer.
4070  // (We manually eliminate the tail call to avoid recursion.)
4071  goto LexNextToken;
4072  }
4073  }
4074 
4075  // Notify MIOpt that we read a non-whitespace/non-comment token.
4076  MIOpt.ReadToken();
4077 
4078  // Update the location of token as well as BufferPtr.
4079  FormTokenWithChars(Result, CurPtr, Kind);
4080  return true;
4081 
4082 HandleDirective:
4083  // We parsed a # character and it's the start of a preprocessing directive.
4084 
4085  FormTokenWithChars(Result, CurPtr, tok::hash);
4086  PP->HandleDirective(Result);
4087 
4089  // With a fatal failure in the module loader, we abort parsing.
4090  assert(Result.is(tok::eof) && "Preprocessor did not set tok:eof");
4091  return true;
4092  }
4093 
4094  // We parsed the directive; lex a token with the new state.
4095  return false;
4096 }
clang::Token::startToken
void startToken()
Reset all flags to cleared.
Definition: Token.h:171
clang::Lexer::isAtEndOfMacroExpansion
static bool isAtEndOfMacroExpansion(SourceLocation loc, const SourceManager &SM, const LangOptions &LangOpts, SourceLocation *MacroEnd=nullptr)
Returns true if the given MacroID location points at the last token of the macro expansion.
Definition: Lexer.cpp:827
clang::Lexer::makeFileCharRange
static CharSourceRange makeFileCharRange(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts)
Accepts a range and returns a character range with file locations.
Definition: Lexer.cpp:888
clang::Preprocessor::CreateString
void CreateString(StringRef Str, Token &Tok, SourceLocation ExpansionLocStart=SourceLocation(), SourceLocation ExpansionLocEnd=SourceLocation())
Plop the specified string into a scratch buffer and set the specified token's location and length to ...
Definition: Preprocessor.cpp:481
getBeginningOfFileToken
static SourceLocation getBeginningOfFileToken(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Definition: Lexer.cpp:509
_mm_cmpeq_epi8
static __inline__ __m128i __DEFAULT_FN_ATTRS _mm_cmpeq_epi8(__m128i __a, __m128i __b)
Compares each of the corresponding 8-bit values of the 128-bit integer vectors for equality.
Definition: emmintrin.h:3175
clang::Token::hasUCN
bool hasUCN() const
Returns true if this token contains a universal character name.
Definition: Token.h:296
clang::Lexer::SetCommentRetentionState
void SetCommentRetentionState(bool Mode)
SetCommentRetentionMode - Change the comment retention mode of the lexer to the specified mode.
Definition: Lexer.h:231
clang::DiagnosticBuilder
A little helper class used to produce diagnostics.
Definition: Diagnostic.h:1264
isInExpansionTokenRange
static bool isInExpansionTokenRange(const SourceLocation Loc, const SourceManager &SM)
Definition: Lexer.cpp:881
clang::CMK_Perforce
@ CMK_Perforce
A Perforce-style conflict marker, initiated by 4 ">"s, separated by 4 "="s, and terminated by 4 "<"s.
Definition: Lexer.h:52
clang::CharSourceRange::getBegin
SourceLocation getBegin() const
Definition: SourceLocation.h:285
clang::Preprocessor::setRecordedPreambleConditionalStack
void setRecordedPreambleConditionalStack(ArrayRef< PPConditionalInfo > s)
Definition: Preprocessor.h:2368
clang::Token::isObjCAtKeyword
bool isObjCAtKeyword(tok::ObjCKeywordKind objcKey) const
Return true if we have an ObjC keyword identifier.
Definition: Lexer.cpp:57
clang::DeclaratorContext::File
@ File
clang::SourceRange
A trivial tuple used to represent a source range.
Definition: SourceLocation.h:212
string
string(SUBSTRING ${CMAKE_CURRENT_BINARY_DIR} 0 ${PATH_LIB_START} PATH_HEAD) string(SUBSTRING $
Definition: CMakeLists.txt:22
clang::Lexer::getLangOpts
const LangOptions & getLangOpts() const
getLangOpts - Return the language features currently enabled.
Definition: Lexer.h:172
clang::Lexer::getRawToken
static bool getRawToken(SourceLocation Loc, Token &Result, const SourceManager &SM, const LangOptions &LangOpts, bool IgnoreWhiteSpace=false)
Relex the token at the specified location.
Definition: Lexer.cpp:458
clang::Lexer::isAsciiIdentifierContinueChar
static bool isAsciiIdentifierContinueChar(char c, const LangOptions &LangOpts)
Returns true if the given character could appear in an identifier.
Definition: Lexer.cpp:1065
clang::Preprocessor::setCodeCompletionTokenRange
void setCodeCompletionTokenRange(const SourceLocation Start, const SourceLocation End)
Set the code completion token range for detecting replacement range later on.
Definition: Preprocessor.h:1312
clang::FixItHint::CreateInsertion
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:96
clang::Preprocessor::HandleIdentifier
bool HandleIdentifier(Token &Identifier)
Callback invoked when the lexer reads an identifier and has filled in the tokens IdentifierInfo membe...
Definition: Preprocessor.cpp:796
clang::ConflictMarkerKind
ConflictMarkerKind
ConflictMarkerKind - Kinds of conflict marker which the lexer might be recovering from.
Definition: Lexer.h:42
clang::SrcMgr::ExpansionInfo::isMacroArgExpansion
bool isMacroArgExpansion() const
Definition: SourceManager.h:386
GetTrigraphCharForLetter
static char GetTrigraphCharForLetter(char Letter)
GetTrigraphCharForLetter - Given a character that occurs after a ?? pair, return the decoded trigraph...
Definition: Lexer.cpp:1173
clang::Token::getLiteralData
const char * getLiteralData() const
getLiteralData - For a literal token (numeric constant, string, etc), this returns a pointer to the s...
Definition: Token.h:217
clang::Lexer::getSpelling
static unsigned getSpelling(const Token &Tok, const char *&Buffer, const SourceManager &SourceMgr, const LangOptions &LangOpts, bool *Invalid=nullptr)
getSpelling - This method is used to get the spelling of a token into a preallocated buffer,...
Definition: Lexer.cpp:400
clang::IdentifierTable::get
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
Definition: IdentifierTable.h:592
clang::MultipleIncludeOpt::ReadToken
void ReadToken()
Definition: MultipleIncludeOpt.h:106
clang::if
if(T->getSizeExpr()) TRY_TO(TraverseStmt(T -> getSizeExpr()))
Definition: RecursiveASTVisitor.h:1002
clang::SourceLocation
Encodes a location in the source.
Definition: SourceLocation.h:88
clang::DiagnosticsEngine::isIgnored
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:909
clang::SourceLocation::getLocWithOffset
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
Definition: SourceLocation.h:136
clang::Preprocessor::getCommentRetentionState
bool getCommentRetentionState() const
Definition: Preprocessor.h:1005
clang::Lexer::inKeepCommentMode
bool inKeepCommentMode() const
inKeepCommentMode - Return true if the lexer should return comments as tokens.
Definition: Lexer.h:224
clang::PreprocessorLexer
Definition: PreprocessorLexer.h:31
DecodeTrigraphChar
static char DecodeTrigraphChar(const char *CP, Lexer *L)
DecodeTrigraphChar - If the specified character is a legal trigraph when prefixed with ?...
Definition: Lexer.cpp:1192
clang::Lexer::Create_PragmaLexer
static Lexer * Create_PragmaLexer(SourceLocation SpellingLoc, SourceLocation ExpansionLocStart, SourceLocation ExpansionLocEnd, unsigned TokLen, Preprocessor &PP)
Create_PragmaLexer: Lexer constructor - Create a new lexer object for _Pragma expansion.
Definition: Lexer.cpp:189
clang::PreprocessorLexer::ConditionalStack
SmallVector< PPConditionalInfo, 4 > ConditionalStack
Information about the set of #if/#ifdef/#ifndef blocks we are currently in.
Definition: PreprocessorLexer.h:77
FindConflictEnd
static const char * FindConflictEnd(const char *CurPtr, const char *BufferEnd, ConflictMarkerKind CMK)
Find the end of a version control conflict marker.
Definition: Lexer.cpp:2967
AttributeLangSupport::C
@ C
Definition: SemaDeclAttr.cpp:54
clang::Token::getIdentifierInfo
IdentifierInfo * getIdentifierInfo() const
Definition: Token.h:179
clang::PreprocessorLexer::MIOpt
MultipleIncludeOpt MIOpt
A state machine that detects the #ifndef-wrapping a file idiom for the multiple-include optimization.
Definition: PreprocessorLexer.h:73
clang::DiagnosticsEngine
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:191
memcpy
__DEVICE__ void * memcpy(void *__a, const void *__b, size_t __c)
Definition: __clang_cuda_device_functions.h:1549
int
__device__ int
Definition: __clang_hip_libdevice_declares.h:63
clang::PreprocessorLexer::ParsingFilename
bool ParsingFilename
True after #include; turns <xx> or "xxx" into a tok::header_name token.
Definition: PreprocessorLexer.h:54
clang::Token::isAtStartOfLine
bool isAtStartOfLine() const
isAtStartOfLine - Return true if this token is at the start of a line.
Definition: Token.h:268
clang::Preprocessor::CodeCompleteIncludedFile
void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled)
Hook used by the lexer to invoke the "included file" code completion point.
Definition: Preprocessor.cpp:443
llvm::Optional
Definition: LLVM.h:40
clang::Lexer::getSourceText
static StringRef getSourceText(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts, bool *Invalid=nullptr)
Returns a string for the source that the range encompasses.
Definition: Lexer.cpp:957
SourceManager.h
clang::Lexer::skipOver
bool skipOver(unsigned NumBytes)
Skip over NumBytes bytes.
Definition: Lexer.cpp:224
clang::CPlusPlus14
@ CPlusPlus14
Definition: LangStandard.h:50
XIDContinueRanges
static const llvm::sys::UnicodeCharRange XIDContinueRanges[]
Definition: UnicodeCharSets.h:239
clang::PreprocessorLexer::LexingRawMode
bool LexingRawMode
True if in raw mode.
Definition: PreprocessorLexer.h:69
clang::Token::IsEditorPlaceholder
@ IsEditorPlaceholder
Definition: Token.h:86
vec_any_eq
static __inline__ int __ATTRS_o_ai vec_any_eq(vector signed char __a, vector signed char __b)
Definition: altivec.h:15943
clang::Lexer::isKeepWhitespaceMode
bool isKeepWhitespaceMode() const
isKeepWhitespaceMode - Return true if the lexer should return tokens for every character in the file,...
Definition: Lexer.h:210
clang::Lexer::MeasureTokenLength
static unsigned MeasureTokenLength(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
MeasureTokenLength - Relex the token at the specified location and return its length in bytes in the ...
Definition: Lexer.cpp:447
clang::Lexer::LexFromRawLexer
bool LexFromRawLexer(Token &Result)
LexFromRawLexer - Lex a token from a designated raw lexer (one with no associated preprocessor object...
Definition: Lexer.h:198
clang::Token
Token - This structure provides full information about a lexed token.
Definition: Token.h:34
clang::tok::isStringLiteral
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:78
LiteralSupport.h
End
SourceLocation End
Definition: USRLocFinder.cpp:167
clang::StringLiteralParser::isValidUDSuffix
static bool isValidUDSuffix(const LangOptions &LangOpts, StringRef Suffix)
Determine whether a suffix is a valid ud-suffix.
Definition: LiteralSupport.cpp:2107
clang::Preprocessor::getIdentifierTable
IdentifierTable & getIdentifierTable()
Definition: Preprocessor.h:967
clang::isPreprocessingNumberBody
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:152
clang::SourceManager
This class handles loading and caching of source files into memory.
Definition: SourceManager.h:626
clang::Lexer::Stringify
static std::string Stringify(StringRef Str, bool Charify=false)
Stringify - Convert the specified string into a C string by i) escaping '\' and " characters and ii) ...
Definition: Lexer.cpp:258
Preprocessor.h
clang::Lexer
Lexer - This provides a simple interface that turns a text buffer into a stream of tokens.
Definition: Lexer.h:76
clang::driver::tools::arm::ReadTPMode::Invalid
@ Invalid
Offset
unsigned Offset
Definition: Format.cpp:2335
clang::CPlusPlus17
@ CPlusPlus17
Definition: LangStandard.h:51
TokenKinds.h
U
clang::CharSourceRange::getCharRange
static CharSourceRange getCharRange(SourceRange R)
Definition: SourceLocation.h:267
diagnoseInvalidUnicodeCodepointInIdentifier
static void diagnoseInvalidUnicodeCodepointInIdentifier(DiagnosticsEngine &Diags, const LangOptions &LangOpts, uint32_t CodePoint, CharSourceRange Range, bool IsFirst)
Definition: Lexer.cpp:1616
clang::CMK_Normal
@ CMK_Normal
A normal or diff3 conflict marker, initiated by at least 7 "<"s, separated by at least 7 "="s or "|"s...
Definition: Lexer.h:48
clang::Lexer::Diag
DiagnosticBuilder Diag(const char *Loc, unsigned DiagID) const
Diag - Forwarding function for diagnostics.
Definition: Lexer.cpp:1163
isAllowedIDChar
static bool isAllowedIDChar(uint32_t C, const LangOptions &LangOpts)
Definition: Lexer.cpp:1455
clang::SrcMgr::ExpansionInfo
Each ExpansionInfo encodes the expansion location - where the token was ultimately expanded,...
Definition: SourceManager.h:347
MultipleIncludeOpt.h
clang::Token::getKind
tok::TokenKind getKind() const
Definition: Token.h:92
clang::CPlusPlus
@ CPlusPlus
Definition: LangStandard.h:48
LangOptions.h
clang::Lexer::isNewLineEscaped
static bool isNewLineEscaped(const char *BufferStart, const char *Str)
Checks whether new line pointed by Str is preceded by escape sequence.
Definition: Lexer.cpp:1069
makeRangeFromFileLocs
static CharSourceRange makeRangeFromFileLocs(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts)
Definition: Lexer.cpp:853
Diagnostic.h
LexDiagnostic.h
_mm_set1_epi8
static __inline__ __m128i __DEFAULT_FN_ATTRS _mm_set1_epi8(char __b)
Initializes all values in a 128-bit vector of [16 x i8] with the specified 8-bit value.
Definition: emmintrin.h:3846
intptr_t
__INTPTR_TYPE__ intptr_t
A signed integer type with the property that any valid pointer to void can be converted to this type,...
Definition: opencl-c-base.h:117
clang::Preprocessor::Diag
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) const
Forwarding function for diagnostics.
Definition: Preprocessor.h:1744
GetMappedTokenLoc
static LLVM_ATTRIBUTE_NOINLINE SourceLocation GetMappedTokenLoc(Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen)
GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the lexer buffer was all exp...
Definition: Lexer.cpp:1120
clang::Token::is
bool is(tok::TokenKind K) const
is/isNot - Predicates to check if this token is a specific kind, as in "if (Tok.is(tok::l_brace)) {....
Definition: Token.h:97
IdentifierTable.h
clang::SrcMgr::ExpansionInfo::getSpellingLoc
SourceLocation getSpellingLoc() const
Definition: SourceManager.h:365
clang::CPlusPlus20
@ CPlusPlus20
Definition: LangStandard.h:52
clang::Lexer::getTokenPrefixLength
static unsigned getTokenPrefixLength(SourceLocation TokStart, unsigned CharNo, const SourceManager &SM, const LangOptions &LangOpts)
Get the physical length (including trigraphs and escaped newlines) of the first Characters characters...
Definition: Lexer.cpp:723
llvm::SmallString
Definition: LLVM.h:37
clang::Token::needsCleaning
bool needsCleaning() const
Return true if this token has trigraphs or escaped newlines in it.
Definition: Token.h:285
clang::Lexer::getIndentationForLine
static StringRef getIndentationForLine(SourceLocation Loc, const SourceManager &SM)
Returns the leading whitespace for line that corresponds to the given location Loc.
Definition: Lexer.cpp:1089
clang::Token::LeadingEmptyMacro
@ LeadingEmptyMacro
Definition: Token.h:79
clang::PreprocessorLexer::ParsingPreprocessorDirective
bool ParsingPreprocessorDirective
True when parsing #XXX; turns '\n' into a tok::eod token.
Definition: PreprocessorLexer.h:51
clang::isRawStringDelimBody
LLVM_READONLY bool isRawStringDelimBody(unsigned char c)
Return true if this is the body character of a C++ raw string delimiter.
Definition: CharInfo.h:159
clang::PreambleBounds
Describes the bounds (start, size) of the preamble and a flag required by PreprocessorOptions::Precom...
Definition: Lexer.h:58
clang::PreprocessorLexer::FID
const FileID FID
The SourceManager FileID corresponding to the file being lexed.
Definition: PreprocessorLexer.h:41
C11DisallowedInitialIDCharRanges
static const llvm::sys::UnicodeCharRange C11DisallowedInitialIDCharRanges[]
Definition: UnicodeCharSets.h:612
clang::SourceLocation::isFileID
bool isFileID() const
Definition: SourceLocation.h:104
clang::tok::ObjCKeywordKind
ObjCKeywordKind
Provides a namespace for Objective-C keywords which start with an '@'.
Definition: TokenKinds.h:41
clang::Lexer::ReadToEndOfLine
void ReadToEndOfLine(SmallVectorImpl< char > *Result=nullptr)
ReadToEndOfLine - Read the rest of the current preprocessor line as an uninterpreted string.
Definition: Lexer.cpp:2798
clang::PreprocessorLexer::PP
Preprocessor * PP
Definition: PreprocessorLexer.h:38
length
float __ovld __cnfn length(float p)
Return the length of vector p, i.e., sqrt(p.x2 + p.y 2 + ...)
getSpellingSlow
static size_t getSpellingSlow(const Token &Tok, const char *BufPtr, const LangOptions &LangOpts, char *Spelling)
Slow case of getSpelling.
Definition: Lexer.cpp:273
clang::Lexer::findNextToken
static Optional< Token > findNextToken(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Finds the token that comes right after the given location.
Definition: Lexer.cpp:1255
altivec.h
clang::Lexer::getImmediateMacroName
static StringRef getImmediateMacroName(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
Definition: Lexer.cpp:993
clang::IdentifierInfo::getObjCKeywordID
tok::ObjCKeywordKind getObjCKeywordID() const
Return the Objective-C keyword ID for the this identifier.
Definition: IdentifierTable.h:291
Line
const AnnotatedLine * Line
Definition: UsingDeclarationsSorter.cpp:68
clang::PreprocessorLexer::isLexingRawMode
bool isLexingRawMode() const
Return true if this lexer is in raw mode or not.
Definition: PreprocessorLexer.h:150
clang::Lexer::getSourceLocation
SourceLocation getSourceLocation(const char *Loc, unsigned TokLen=1) const
getSourceLocation - Return a source location identifier for the specified offset in the current file.
Definition: Lexer.cpp:1144
findPlaceholderEnd
static const char * findPlaceholderEnd(const char *CurPtr, const char *BufferEnd)
Definition: Lexer.cpp:3071
clang::Token::getRawIdentifier
StringRef getRawIdentifier() const
getRawIdentifier - For a raw identifier token (i.e., an identifier lexed in raw mode),...
Definition: Token.h:205
clang::Token::isLiteral
bool isLiteral() const
Return true if this is a "literal", like a numeric constant, string, etc.
Definition: Token.h:115
clang::isAsciiIdentifierContinue
LLVM_READONLY bool isAsciiIdentifierContinue(unsigned char c, bool AllowDollar=false)
Returns true if this is a body character of a C identifier, which is [a-zA-Z0-9_].
Definition: CharInfo.h:63
clang::Token::getLength
unsigned getLength() const
Definition: Token.h:129
clang::Token::LeadingSpace
@ LeadingSpace
Definition: Token.h:75
makeCharRange
static CharSourceRange makeCharRange(Lexer &L, const char *Begin, const char *End)
Definition: Lexer.cpp:1501
clang::Preprocessor::getSourceManager
SourceManager & getSourceManager() const
Definition: Preprocessor.h:964
clang::Preprocessor::HandleComment
bool HandleComment(Token &result, SourceRange Comment)
Definition: Preprocessor.cpp:1398
clang::Preprocessor::getSpelling
StringRef getSpelling(SourceLocation loc, SmallVectorImpl< char > &buffer, bool *invalid=nullptr) const
Return the 'spelling' of the token at the given location; does not go up to the spelling location or ...
Definition: Preprocessor.h:1759
clang::isWhitespace
LLVM_READONLY bool isWhitespace(unsigned char c)
Return true if this character is horizontal or vertical ASCII whitespace: ' ', '\t',...
Definition: CharInfo.h:92
UnicodeWhitespaceCharRanges
static const llvm::sys::UnicodeCharRange UnicodeWhitespaceCharRanges[]
Definition: UnicodeCharSets.h:629
clang::SrcMgr::SLocEntry::getExpansion
const ExpansionInfo & getExpansion() const
Definition: SourceManager.h:489
SourceLocation.h
clang::tok::TokenKind
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition: TokenKinds.h:25
clang::Token::HasUDSuffix
@ HasUDSuffix
Definition: Token.h:80
clang::Preprocessor::CodeCompleteNaturalLanguage
void CodeCompleteNaturalLanguage()
Hook used by the lexer to invoke the "natural language" code completion point.
Definition: Preprocessor.cpp:450
P
StringRef P
Definition: ASTMatchersInternal.cpp:563
clang::Preprocessor::HandleDirective
void HandleDirective(Token &Result)
Callback invoked when the lexer sees a # token at the start of a line.
Definition: PPDirectives.cpp:999
CharInfo.h
clang::Lexer::getBufferLocation
const char * getBufferLocation() const
Return the current location in the buffer.
Definition: Lexer.h:270
clang::syntax::NodeRole::Size
@ Size
clang::Preprocessor::hadModuleLoaderFatalFailure
bool hadModuleLoaderFatalFailure() const
Definition: Preprocessor.h:984
clang::Preprocessor::getCodeCompletionFileLoc
SourceLocation getCodeCompletionFileLoc() const
Returns the start location of the file of code-completion point.
Definition: Preprocessor.h:1678
StringifyImpl
static void StringifyImpl(T &Str, char Quote)
Definition: Lexer.cpp:233
clang::Preprocessor::isCodeCompletionEnabled
bool isCodeCompletionEnabled() const
Determine if we are performing code completion.
Definition: Preprocessor.h:1666
isEndOfBlockCommentWithEscapedNewLine
static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr, Lexer *L)
isBlockCommentEndOfEscapedNewLine - Return true if the specified newline character (either \n or \r) ...
Definition: Lexer.cpp:2542
clang::SrcMgr::ExpansionInfo::getExpansionLocStart
SourceLocation getExpansionLocStart() const
Definition: SourceManager.h:369
clang::C2x
@ C2x
Definition: LangStandard.h:47
Begin
SourceLocation Begin
Definition: USRLocFinder.cpp:165
Lexer.h
Value
Value
Definition: UninitializedValues.cpp:102
clang::Preprocessor::setCodeCompletionIdentifierInfo
void setCodeCompletionIdentifierInfo(IdentifierInfo *Filter)
Set the code completion token for filtering purposes.
Definition: Preprocessor.h:1306
clang::SourceManager::getCharacterData
const char * getCharacterData(SourceLocation SL, bool *Invalid=nullptr) const
Return a pointer to the start of the specified location in the appropriate spelling MemoryBuffer.
Definition: SourceManager.cpp:1157
isAllowedInitiallyIDChar
static bool isAllowedInitiallyIDChar(uint32_t C, const LangOptions &LangOpts)
Definition: Lexer.cpp:1480
clang::frontend::After
@ After
Like System, but searched after the system directories.
Definition: HeaderSearchOptions.h:61
clang::CharSourceRange
Represents a character-granular source range.
Definition: SourceLocation.h:255
findBeginningOfLine
static const char * findBeginningOfLine(StringRef Buffer, unsigned Offset)
Returns the pointer that points to the beginning of line that contains the given offset,...
Definition: Lexer.cpp:492
LLVM.h
clang::Token::StartOfLine
@ StartOfLine
Definition: Token.h:73
clang::Preprocessor::HandleEndOfFile
bool HandleEndOfFile(Token &Result, SourceLocation Loc, bool isEndOfMacro=false)
Callback invoked when the lexer hits the end of the current file.
Definition: PPLexerChange.cpp:342
clang::Lexer::Lexer
Lexer(FileID FID, const llvm::MemoryBufferRef &InputFile, Preprocessor &PP)
Lexer constructor - Create a new lexer object for the specified buffer with the specified preprocesso...
Definition: Lexer.cpp:135
C99DisallowedInitialIDCharRanges
static const llvm::sys::UnicodeCharRange C99DisallowedInitialIDCharRanges[]
Definition: UnicodeCharSets.h:620
clang::CharSourceRange::getEnd
SourceLocation getEnd() const
Definition: SourceLocation.h:286
clang::Preprocessor::isPreprocessedOutput
bool isPreprocessedOutput() const
Returns true if the preprocessor is responsible for generating output, false if it is producing token...
Definition: Preprocessor.h:1026
clang::IdentifierInfo
One of these records is kept for each identifier that is lexed.
Definition: IdentifierTable.h:84
clang::Token::getLocation
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file.
Definition: Token.h:126
clang::SourceLocation::getFromRawEncoding
static SourceLocation getFromRawEncoding(UIntTy Encoding)
Turn a raw encoding of a SourceLocation object into a real SourceLocation.
Definition: SourceLocation.h:154
clang::SourceLocation::isMacroID
bool isMacroID() const
Definition: SourceLocation.h:105
clang::IdentifierInfo::isHandleIdentifierCase
bool isHandleIdentifierCase() const
Return true if the Preprocessor::HandleIdentifier must be called on a token of this identifier.
Definition: IdentifierTable.h:380
clang::LangOptions
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:58
clang::Lexer::SetKeepWhitespaceMode
void SetKeepWhitespaceMode(bool Val)
SetKeepWhitespaceMode - This method lets clients enable or disable whitespace retention mode.
Definition: Lexer.h:216
clang::ObjCPropertyAttribute::Kind
Kind
Definition: DeclObjCCommon.h:22
clang::Lexer::getImmediateMacroNameForDiagnostics
static StringRef getImmediateMacroNameForDiagnostics(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
Definition: Lexer.cpp:1040
clang::Token::isAnnotation
bool isAnnotation() const
Return true if this is any of tok::annot_* kind tokens.
Definition: Token.h:120
clang::Preprocessor::getPreprocessorOpts
PreprocessorOptions & getPreprocessorOpts() const
Retrieve the preprocessor options used to initialize this preprocessor.
Definition: Preprocessor.h:955
maybeDiagnoseUTF8Homoglyph
static void maybeDiagnoseUTF8Homoglyph(DiagnosticsEngine &Diags, uint32_t C, CharSourceRange Range)
After encountering UTF-8 character C and interpreting it as an identifier character,...
Definition: Lexer.cpp:1536
clang::SourceLocation::isInvalid
bool isInvalid() const
Definition: SourceLocation.h:113
clang::Preprocessor::getCodeCompletionLoc
SourceLocation getCodeCompletionLoc() const
Returns the location of the code-completion point.
Definition: Preprocessor.h:1672
clang::isVerticalWhitespace
LLVM_READONLY bool isVerticalWhitespace(unsigned char c)
Returns true if this character is vertical ASCII whitespace: '\n', '\r'.
Definition: CharInfo.h:83
clang
Definition: CalledOnceCheck.h:17
clang::Lexer::isAtStartOfMacroExpansion
static bool isAtStartOfMacroExpansion(SourceLocation loc, const SourceManager &SM, const LangOptions &LangOpts, SourceLocation *MacroBegin=nullptr)
Returns true if the given MacroID location points at the first token of the macro expansion.
Definition: Lexer.cpp:805
clang::PreprocessorOptions::LexEditorPlaceholders
bool LexEditorPlaceholders
When enabled, the preprocessor will construct editor placeholder tokens.
Definition: PreprocessorOptions.h:147
clang::Preprocessor::LookUpIdentifierInfo
IdentifierInfo * LookUpIdentifierInfo(Token &Identifier) const
Given a tok::raw_identifier token, look up the identifier information for the token and install it in...
Definition: Preprocessor.cpp:696
_mm_movemask_epi8
static __inline__ int __DEFAULT_FN_ATTRS _mm_movemask_epi8(__m128i __a)
Copies the values of the most significant bits from each 8-bit element in a 128-bit integer vector of...
Definition: emmintrin.h:4403
maybeDiagnoseIDCharCompat
static void maybeDiagnoseIDCharCompat(DiagnosticsEngine &Diags, uint32_t C, CharSourceRange Range, bool IsFirst)
Definition: Lexer.cpp:1507
isUnicodeWhitespace
static bool isUnicodeWhitespace(uint32_t Codepoint)
Definition: Lexer.cpp:1449
clang::Preprocessor::getDiagnostics
DiagnosticsEngine & getDiagnostics() const
Definition: Preprocessor.h:957
clang::Lexer::GetBeginningOfToken
static SourceLocation GetBeginningOfToken(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Given a location any where in a source buffer, find the location that corresponds to the beginning of...
Definition: Lexer.cpp:557
clang::Lexer::isPragmaLexer
bool isPragmaLexer() const
isPragmaLexer - Returns true if this Lexer is being used to lex a pragma.
Definition: Lexer.h:187
clang::operator<
bool operator<(DeclarationName LHS, DeclarationName RHS)
Ordering on two declaration names.
Definition: DeclarationName.h:540
clang::FileID
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
Definition: SourceLocation.h:40
C99AllowedIDCharRanges
static const llvm::sys::UnicodeCharRange C99AllowedIDCharRanges[]
Definition: UnicodeCharSets.h:393
clang::SourceLocation::isValid
bool isValid() const
Return true if this is a valid SourceLocation object.
Definition: SourceLocation.h:112
clang::FileID::isInvalid
bool isInvalid() const
Definition: SourceLocation.h:47
clang::FixItHint::CreateRemoval
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:122
clang::Preprocessor::isInPrimaryFile
bool isInPrimaryFile() const
Return true if we're in the top-level file, not in a #include.
Definition: PPLexerChange.cpp:35
clang::Token::NeedsCleaning
@ NeedsCleaning
Definition: Token.h:78
UnicodeCharSets.h
clang::MultipleIncludeOpt::ExitTopLevelConditional
void ExitTopLevelConditional()
Called when the lexer exits the top-level conditional.
Definition: MultipleIncludeOpt.h:149
clang::Lexer::resetExtendedTokenMode
void resetExtendedTokenMode()
Sets the extended token mode back to its initial value, according to the language options and preproc...
Definition: Lexer.cpp:166
c
__device__ __2f16 float c
Definition: __clang_hip_libdevice_declares.h:315
clang::isHorizontalWhitespace
LLVM_READONLY bool isHorizontalWhitespace(unsigned char c)
Returns true if this character is horizontal ASCII whitespace: ' ', '\t', '\f', '\v'.
Definition: CharInfo.h:75
clang::CPlusPlus11
@ CPlusPlus11
Definition: LangStandard.h:49
clang::Token::setFlag
void setFlag(TokenFlags Flag)
Set the specified flag.
Definition: Token.h:236
clang::Lexer::getLocForEndOfToken
static SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset, const SourceManager &SM, const LangOptions &LangOpts)
Computes the source location just past the end of the token at this source location.
Definition: Lexer.cpp:783
clang::comments::tok::eof
@ eof
Definition: CommentLexer.h:33
clang::Lexer::ComputePreamble
static PreambleBounds ComputePreamble(StringRef Buffer, const LangOptions &LangOpts, unsigned MaxLines=0)
Compute the preamble of the given file.
Definition: Lexer.cpp:585
llvm::SmallVectorImpl< char >
clang::Token::HasUCN
@ HasUCN
Definition: Token.h:81
clang::Lexer::findLocationAfterToken
static SourceLocation findLocationAfterToken(SourceLocation loc, tok::TokenKind TKind, const SourceManager &SM, const LangOptions &LangOpts, bool SkipTrailingWhitespaceAndNewLine)
Checks that the given token is the first token that occurs after the given location (this excludes co...
Definition: Lexer.cpp:1288
clang::Lexer::getCharAndSizeNoWarn
static char getCharAndSizeNoWarn(const char *Ptr, unsigned &Size, const LangOptions &LangOpts)
getCharAndSizeNoWarn - Like the getCharAndSize method, but does not ever emit a warning.
Definition: Lexer.h:548
PreprocessorOptions.h
clang::Preprocessor
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:130
clang::Preprocessor::isRecordingPreamble
bool isRecordingPreamble() const
Definition: Preprocessor.h:2356
clang::Token::getObjCKeywordID
tok::ObjCKeywordKind getObjCKeywordID() const
Return the ObjC keyword kind.
Definition: Lexer.cpp:66
SM
#define SM(sm)
Definition: Cuda.cpp:78
C11AllowedIDCharRanges
static const llvm::sys::UnicodeCharRange C11AllowedIDCharRanges[]
Definition: UnicodeCharSets.h:363
clang::Lexer::getSourceLocation
SourceLocation getSourceLocation() override
getSourceLocation - Return a source location for the next character in the current file.
Definition: Lexer.h:265
Token.h
clang::Preprocessor::getEmptylineHandler
EmptylineHandler * getEmptylineHandler() const
Definition: Preprocessor.h:1272
XIDStartRanges
static const llvm::sys::UnicodeCharRange XIDStartRanges[]
Definition: UnicodeCharSets.h:14
clang::isAsciiIdentifierStart
LLVM_READONLY bool isAsciiIdentifierStart(unsigned char c, bool AllowDollar=false)
Returns true if this is a valid first character of a C identifier, which is [a-zA-Z_].
Definition: CharInfo.h:53
clang::Decl::getLocation
SourceLocation getLocation() const
Definition: DeclBase.h:430
clang::SourceLocation::UIntTy
uint32_t UIntTy
Definition: SourceLocation.h:95
clang::isASCII
LLVM_READNONE bool isASCII(char c)
Returns true if this is an ASCII character.
Definition: CharInfo.h:42
clang::SourceLocation::getRawEncoding
UIntTy getRawEncoding() const
When a SourceLocation itself cannot be used, this returns an (opaque) 32-bit integer encoding for it.
Definition: SourceLocation.h:148
clang::DiagnosticsEngine::Report
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1523
clang::CMK_None
@ CMK_None
Not within a conflict marker.
Definition: Lexer.h:44
clang::SrcMgr::SLocEntry
This is a discriminated union of FileInfo and ExpansionInfo.
Definition: SourceManager.h:467