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