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