blob: da68495663a239099f80b4fb5e61f4860a87dddf [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- Lexer.cpp - C Language Family Lexer ------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
Chris Lattnerd2177732007-07-20 16:59:19 +000010// This file implements the Lexer and Token interfaces.
Reid Spencer5f016e22007-07-11 17:01:13 +000011//
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"
Chris Lattner500d3292009-01-29 05:15:15 +000029#include "clang/Lex/LexDiagnostic.h"
Douglas Gregor55817af2010-08-25 17:04:25 +000030#include "clang/Lex/CodeCompletionHandler.h"
Chris Lattner9dc1f532007-07-20 16:37:10 +000031#include "clang/Basic/SourceManager.h"
Douglas Gregorf033f1d2010-07-20 20:18:03 +000032#include "llvm/ADT/StringSwitch.h"
Chris Lattner409a0362007-07-22 18:38:25 +000033#include "llvm/Support/Compiler.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000034#include "llvm/Support/MemoryBuffer.h"
35#include <cctype>
36using namespace clang;
37
Chris Lattnera2bf1052009-12-17 05:29:40 +000038static void InitCharacterInfo();
Reid Spencer5f016e22007-07-11 17:01:13 +000039
Chris Lattnerdbf388b2007-10-07 08:47:24 +000040//===----------------------------------------------------------------------===//
41// Token Class Implementation
42//===----------------------------------------------------------------------===//
43
Mike Stump1eb44332009-09-09 15:08:12 +000044/// isObjCAtKeyword - Return true if we have an ObjC keyword identifier.
Chris Lattnerdbf388b2007-10-07 08:47:24 +000045bool Token::isObjCAtKeyword(tok::ObjCKeywordKind objcKey) const {
Douglas Gregorbec1c9d2008-12-01 21:46:47 +000046 if (IdentifierInfo *II = getIdentifierInfo())
47 return II->getObjCKeywordID() == objcKey;
48 return false;
Chris Lattnerdbf388b2007-10-07 08:47:24 +000049}
50
51/// getObjCKeywordID - Return the ObjC keyword kind.
52tok::ObjCKeywordKind Token::getObjCKeywordID() const {
53 IdentifierInfo *specId = getIdentifierInfo();
54 return specId ? specId->getObjCKeywordID() : tok::objc_not_keyword;
55}
56
Chris Lattner53702cd2007-12-13 01:59:49 +000057
Chris Lattnerdbf388b2007-10-07 08:47:24 +000058//===----------------------------------------------------------------------===//
59// Lexer Class Implementation
60//===----------------------------------------------------------------------===//
61
Mike Stump1eb44332009-09-09 15:08:12 +000062void Lexer::InitLexer(const char *BufStart, const char *BufPtr,
Chris Lattner22d91ca2009-01-17 06:55:17 +000063 const char *BufEnd) {
Chris Lattnera2bf1052009-12-17 05:29:40 +000064 InitCharacterInfo();
Mike Stump1eb44332009-09-09 15:08:12 +000065
Chris Lattner22d91ca2009-01-17 06:55:17 +000066 BufferStart = BufStart;
67 BufferPtr = BufPtr;
68 BufferEnd = BufEnd;
Mike Stump1eb44332009-09-09 15:08:12 +000069
Chris Lattner22d91ca2009-01-17 06:55:17 +000070 assert(BufEnd[0] == 0 &&
71 "We assume that the input buffer has a null character at the end"
72 " to simplify lexing!");
Mike Stump1eb44332009-09-09 15:08:12 +000073
Chris Lattner22d91ca2009-01-17 06:55:17 +000074 Is_PragmaLexer = false;
Chris Lattner34f349d2009-12-14 06:16:57 +000075 IsInConflictMarker = false;
Douglas Gregor81b747b2009-09-17 21:32:03 +000076
Chris Lattner22d91ca2009-01-17 06:55:17 +000077 // Start of the file is a start of line.
78 IsAtStartOfLine = true;
Mike Stump1eb44332009-09-09 15:08:12 +000079
Chris Lattner22d91ca2009-01-17 06:55:17 +000080 // We are not after parsing a #.
81 ParsingPreprocessorDirective = false;
Mike Stump1eb44332009-09-09 15:08:12 +000082
Chris Lattner22d91ca2009-01-17 06:55:17 +000083 // We are not after parsing #include.
84 ParsingFilename = false;
Mike Stump1eb44332009-09-09 15:08:12 +000085
Chris Lattner22d91ca2009-01-17 06:55:17 +000086 // We are not in raw mode. Raw mode disables diagnostics and interpretation
87 // of tokens (e.g. identifiers, thus disabling macro expansion). It is used
88 // to quickly lex the tokens of the buffer, e.g. when handling a "#if 0" block
89 // or otherwise skipping over tokens.
90 LexingRawMode = false;
Mike Stump1eb44332009-09-09 15:08:12 +000091
Chris Lattner22d91ca2009-01-17 06:55:17 +000092 // Default to not keeping comments.
93 ExtendedTokenMode = 0;
94}
95
Chris Lattner0770dab2009-01-17 07:56:59 +000096/// Lexer constructor - Create a new lexer object for the specified buffer
97/// with the specified preprocessor managing the lexing process. This lexer
98/// assumes that the associated file buffer and Preprocessor objects will
99/// outlive it, so it doesn't take ownership of either of them.
Chris Lattner6e290142009-11-30 04:18:44 +0000100Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *InputFile, Preprocessor &PP)
Chris Lattner88d3ac12009-01-17 08:03:42 +0000101 : PreprocessorLexer(&PP, FID),
102 FileLoc(PP.getSourceManager().getLocForStartOfFile(FID)),
103 Features(PP.getLangOptions()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000104
Chris Lattner0770dab2009-01-17 07:56:59 +0000105 InitLexer(InputFile->getBufferStart(), InputFile->getBufferStart(),
106 InputFile->getBufferEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000107
Chris Lattner0770dab2009-01-17 07:56:59 +0000108 // Default to keeping comments if the preprocessor wants them.
109 SetCommentRetentionState(PP.getCommentRetentionState());
110}
Chris Lattnerdbf388b2007-10-07 08:47:24 +0000111
Chris Lattner168ae2d2007-10-17 20:41:00 +0000112/// Lexer constructor - Create a new raw lexer object. This object is only
Chris Lattner590f0cc2008-10-12 01:15:46 +0000113/// suitable for calls to 'LexRawToken'. This lexer assumes that the text
114/// range will outlive it, so it doesn't take ownership of it.
Chris Lattner168ae2d2007-10-17 20:41:00 +0000115Lexer::Lexer(SourceLocation fileloc, const LangOptions &features,
Chris Lattnerde96c0f2009-01-17 07:42:27 +0000116 const char *BufStart, const char *BufPtr, const char *BufEnd)
Chris Lattnerc6fe32a2009-01-17 03:48:08 +0000117 : FileLoc(fileloc), Features(features) {
Chris Lattner22d91ca2009-01-17 06:55:17 +0000118
Chris Lattner22d91ca2009-01-17 06:55:17 +0000119 InitLexer(BufStart, BufPtr, BufEnd);
Mike Stump1eb44332009-09-09 15:08:12 +0000120
Chris Lattner168ae2d2007-10-17 20:41:00 +0000121 // We *are* in raw mode.
122 LexingRawMode = true;
Chris Lattner168ae2d2007-10-17 20:41:00 +0000123}
124
Chris Lattner025c3a62009-01-17 07:35:14 +0000125/// Lexer constructor - Create a new raw lexer object. This object is only
126/// suitable for calls to 'LexRawToken'. This lexer assumes that the text
127/// range will outlive it, so it doesn't take ownership of it.
Chris Lattner6e290142009-11-30 04:18:44 +0000128Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *FromFile,
129 const SourceManager &SM, const LangOptions &features)
Chris Lattner025c3a62009-01-17 07:35:14 +0000130 : FileLoc(SM.getLocForStartOfFile(FID)), Features(features) {
Chris Lattner025c3a62009-01-17 07:35:14 +0000131
Mike Stump1eb44332009-09-09 15:08:12 +0000132 InitLexer(FromFile->getBufferStart(), FromFile->getBufferStart(),
Chris Lattner025c3a62009-01-17 07:35:14 +0000133 FromFile->getBufferEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000134
Chris Lattner025c3a62009-01-17 07:35:14 +0000135 // We *are* in raw mode.
136 LexingRawMode = true;
137}
138
Chris Lattner42e00d12009-01-17 08:27:52 +0000139/// Create_PragmaLexer: Lexer constructor - Create a new lexer object for
140/// _Pragma expansion. This has a variety of magic semantics that this method
141/// sets up. It returns a new'd Lexer that must be delete'd when done.
142///
143/// On entrance to this routine, TokStartLoc is a macro location which has a
144/// spelling loc that indicates the bytes to be lexed for the token and an
145/// instantiation location that indicates where all lexed tokens should be
146/// "expanded from".
147///
148/// FIXME: It would really be nice to make _Pragma just be a wrapper around a
149/// normal lexer that remaps tokens as they fly by. This would require making
150/// Preprocessor::Lex virtual. Given that, we could just dump in a magic lexer
151/// interface that could handle this stuff. This would pull GetMappedTokenLoc
152/// out of the critical path of the lexer!
153///
Mike Stump1eb44332009-09-09 15:08:12 +0000154Lexer *Lexer::Create_PragmaLexer(SourceLocation SpellingLoc,
Chris Lattnere7fb4842009-02-15 20:52:18 +0000155 SourceLocation InstantiationLocStart,
156 SourceLocation InstantiationLocEnd,
Chris Lattnerbcc2a672009-01-19 06:46:35 +0000157 unsigned TokLen, Preprocessor &PP) {
Chris Lattner42e00d12009-01-17 08:27:52 +0000158 SourceManager &SM = PP.getSourceManager();
Chris Lattner42e00d12009-01-17 08:27:52 +0000159
160 // Create the lexer as if we were going to lex the file normally.
Chris Lattnera11d6172009-01-19 07:46:45 +0000161 FileID SpellingFID = SM.getFileID(SpellingLoc);
Chris Lattner6e290142009-11-30 04:18:44 +0000162 const llvm::MemoryBuffer *InputFile = SM.getBuffer(SpellingFID);
163 Lexer *L = new Lexer(SpellingFID, InputFile, PP);
Mike Stump1eb44332009-09-09 15:08:12 +0000164
Chris Lattner42e00d12009-01-17 08:27:52 +0000165 // Now that the lexer is created, change the start/end locations so that we
166 // just lex the subsection of the file that we want. This is lexing from a
167 // scratch buffer.
168 const char *StrData = SM.getCharacterData(SpellingLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000169
Chris Lattner42e00d12009-01-17 08:27:52 +0000170 L->BufferPtr = StrData;
171 L->BufferEnd = StrData+TokLen;
Chris Lattner1fa49532009-03-08 08:08:45 +0000172 assert(L->BufferEnd[0] == 0 && "Buffer is not nul terminated!");
Chris Lattner42e00d12009-01-17 08:27:52 +0000173
174 // Set the SourceLocation with the remapping information. This ensures that
175 // GetMappedTokenLoc will remap the tokens as they are lexed.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000176 L->FileLoc = SM.createInstantiationLoc(SM.getLocForStartOfFile(SpellingFID),
Chris Lattnere7fb4842009-02-15 20:52:18 +0000177 InstantiationLocStart,
178 InstantiationLocEnd, TokLen);
Mike Stump1eb44332009-09-09 15:08:12 +0000179
Chris Lattner42e00d12009-01-17 08:27:52 +0000180 // Ensure that the lexer thinks it is inside a directive, so that end \n will
181 // return an EOM token.
182 L->ParsingPreprocessorDirective = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000183
Chris Lattner42e00d12009-01-17 08:27:52 +0000184 // This lexer really is for _Pragma.
185 L->Is_PragmaLexer = true;
186 return L;
187}
188
Chris Lattner168ae2d2007-10-17 20:41:00 +0000189
Reid Spencer5f016e22007-07-11 17:01:13 +0000190/// Stringify - Convert the specified string into a C string, with surrounding
191/// ""'s, and with escaped \ and " characters.
192std::string Lexer::Stringify(const std::string &Str, bool Charify) {
193 std::string Result = Str;
194 char Quote = Charify ? '\'' : '"';
195 for (unsigned i = 0, e = Result.size(); i != e; ++i) {
196 if (Result[i] == '\\' || Result[i] == Quote) {
197 Result.insert(Result.begin()+i, '\\');
198 ++i; ++e;
199 }
200 }
201 return Result;
202}
203
Chris Lattnerd8e30832007-07-24 06:57:14 +0000204/// Stringify - Convert the specified string into a C string by escaping '\'
205/// and " characters. This does not add surrounding ""'s to the string.
206void Lexer::Stringify(llvm::SmallVectorImpl<char> &Str) {
207 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
208 if (Str[i] == '\\' || Str[i] == '"') {
209 Str.insert(Str.begin()+i, '\\');
210 ++i; ++e;
211 }
212 }
213}
214
Chris Lattnerb0607272010-11-17 07:26:20 +0000215//===----------------------------------------------------------------------===//
216// Token Spelling
217//===----------------------------------------------------------------------===//
218
219/// getSpelling() - Return the 'spelling' of this token. The spelling of a
220/// token are the characters used to represent the token in the source file
221/// after trigraph expansion and escaped-newline folding. In particular, this
222/// wants to get the true, uncanonicalized, spelling of things like digraphs
223/// UCNs, etc.
224std::string Lexer::getSpelling(const Token &Tok, const SourceManager &SourceMgr,
225 const LangOptions &Features, bool *Invalid) {
226 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
227
228 // If this token contains nothing interesting, return it directly.
229 bool CharDataInvalid = false;
230 const char* TokStart = SourceMgr.getCharacterData(Tok.getLocation(),
231 &CharDataInvalid);
232 if (Invalid)
233 *Invalid = CharDataInvalid;
234 if (CharDataInvalid)
235 return std::string();
236
237 if (!Tok.needsCleaning())
238 return std::string(TokStart, TokStart+Tok.getLength());
239
240 std::string Result;
241 Result.reserve(Tok.getLength());
242
243 // Otherwise, hard case, relex the characters into the string.
244 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
245 Ptr != End; ) {
246 unsigned CharSize;
247 Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features));
248 Ptr += CharSize;
249 }
250 assert(Result.size() != unsigned(Tok.getLength()) &&
251 "NeedsCleaning flag set on something that didn't need cleaning!");
252 return Result;
253}
254
255/// getSpelling - This method is used to get the spelling of a token into a
256/// preallocated buffer, instead of as an std::string. The caller is required
257/// to allocate enough space for the token, which is guaranteed to be at least
258/// Tok.getLength() bytes long. The actual length of the token is returned.
259///
260/// Note that this method may do two possible things: it may either fill in
261/// the buffer specified with characters, or it may *change the input pointer*
262/// to point to a constant buffer with the data already in it (avoiding a
263/// copy). The caller is not allowed to modify the returned buffer pointer
264/// if an internal buffer is returned.
265unsigned Lexer::getSpelling(const Token &Tok, const char *&Buffer,
266 const SourceManager &SourceMgr,
267 const LangOptions &Features, bool *Invalid) {
268 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
269
270 // If this token is an identifier, just return the string from the identifier
271 // table, which is very quick.
272 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
273 Buffer = II->getNameStart();
274 return II->getLength();
275 }
276
277 // Otherwise, compute the start of the token in the input lexer buffer.
278 const char *TokStart = 0;
279
280 if (Tok.isLiteral())
281 TokStart = Tok.getLiteralData();
282
283 if (TokStart == 0) {
284 bool CharDataInvalid = false;
285 TokStart = SourceMgr.getCharacterData(Tok.getLocation(), &CharDataInvalid);
286 if (Invalid)
287 *Invalid = CharDataInvalid;
288 if (CharDataInvalid) {
289 Buffer = "";
290 return 0;
291 }
292 }
293
294 // If this token contains nothing interesting, return it directly.
295 if (!Tok.needsCleaning()) {
296 Buffer = TokStart;
297 return Tok.getLength();
298 }
299
300 // Otherwise, hard case, relex the characters into the string.
301 char *OutBuf = const_cast<char*>(Buffer);
302 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
303 Ptr != End; ) {
304 unsigned CharSize;
305 *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features);
306 Ptr += CharSize;
307 }
308 assert(unsigned(OutBuf-Buffer) != Tok.getLength() &&
309 "NeedsCleaning flag set on something that didn't need cleaning!");
310
311 return OutBuf-Buffer;
312}
313
314
315
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000316static bool isWhitespace(unsigned char c);
Reid Spencer5f016e22007-07-11 17:01:13 +0000317
Chris Lattner9a611942007-10-17 21:18:47 +0000318/// MeasureTokenLength - Relex the token at the specified location and return
319/// its length in bytes in the input file. If the token needs cleaning (e.g.
320/// includes a trigraph or an escaped newline) then this count includes bytes
321/// that are part of that.
322unsigned Lexer::MeasureTokenLength(SourceLocation Loc,
Chris Lattner2c78b872009-04-14 23:22:57 +0000323 const SourceManager &SM,
324 const LangOptions &LangOpts) {
Chris Lattner9a611942007-10-17 21:18:47 +0000325 // TODO: this could be special cased for common tokens like identifiers, ')',
326 // etc to make this faster, if it mattered. Just look at StrData[0] to handle
Mike Stump1eb44332009-09-09 15:08:12 +0000327 // all obviously single-char tokens. This could use
Chris Lattner9a611942007-10-17 21:18:47 +0000328 // Lexer::isObviouslySimpleCharacter for example to handle identifiers or
329 // something.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000330
331 // If this comes from a macro expansion, we really do want the macro name, not
332 // the token this macro expanded to.
Chris Lattner363fdc22009-01-26 22:24:27 +0000333 Loc = SM.getInstantiationLoc(Loc);
334 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +0000335 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000336 llvm::StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Douglas Gregorf715ca12010-03-16 00:06:06 +0000337 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +0000338 return 0;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000339
340 const char *StrData = Buffer.data()+LocInfo.second;
Chris Lattner83503942009-01-17 08:30:10 +0000341
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000342 if (isWhitespace(StrData[0]))
343 return 0;
344
Chris Lattner9a611942007-10-17 21:18:47 +0000345 // Create a lexer starting at the beginning of this token.
Sebastian Redlc3526d82010-09-30 01:03:03 +0000346 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts,
347 Buffer.begin(), StrData, Buffer.end());
Chris Lattner39de7402009-10-14 15:04:18 +0000348 TheLexer.SetCommentRetentionState(true);
Chris Lattner9a611942007-10-17 21:18:47 +0000349 Token TheTok;
Chris Lattner590f0cc2008-10-12 01:15:46 +0000350 TheLexer.LexFromRawLexer(TheTok);
Chris Lattner9a611942007-10-17 21:18:47 +0000351 return TheTok.getLength();
352}
353
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000354SourceLocation Lexer::GetBeginningOfToken(SourceLocation Loc,
355 const SourceManager &SM,
356 const LangOptions &LangOpts) {
357 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
358 bool Invalid = false;
359 llvm::StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
360 if (Invalid)
361 return Loc;
362
363 // Back up from the current location until we hit the beginning of a line
364 // (or the buffer). We'll relex from that point.
365 const char *BufStart = Buffer.data();
366 const char *StrData = BufStart+LocInfo.second;
367 if (StrData[0] == '\n' || StrData[0] == '\r')
368 return Loc;
369
370 const char *LexStart = StrData;
371 while (LexStart != BufStart) {
372 if (LexStart[0] == '\n' || LexStart[0] == '\r') {
373 ++LexStart;
374 break;
375 }
376
377 --LexStart;
378 }
379
380 // Create a lexer starting at the beginning of this token.
381 SourceLocation LexerStartLoc = Loc.getFileLocWithOffset(-LocInfo.second);
382 Lexer TheLexer(LexerStartLoc, LangOpts, BufStart, LexStart, Buffer.end());
383 TheLexer.SetCommentRetentionState(true);
384
385 // Lex tokens until we find the token that contains the source location.
386 Token TheTok;
387 do {
388 TheLexer.LexFromRawLexer(TheTok);
389
390 if (TheLexer.getBufferLocation() > StrData) {
391 // Lexing this token has taken the lexer past the source location we're
392 // looking for. If the current token encompasses our source location,
393 // return the beginning of that token.
394 if (TheLexer.getBufferLocation() - TheTok.getLength() <= StrData)
395 return TheTok.getLocation();
396
397 // We ended up skipping over the source location entirely, which means
398 // that it points into whitespace. We're done here.
399 break;
400 }
401 } while (TheTok.getKind() != tok::eof);
402
403 // We've passed our source location; just return the original source location.
404 return Loc;
405}
406
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000407namespace {
408 enum PreambleDirectiveKind {
409 PDK_Skipped,
410 PDK_StartIf,
411 PDK_EndIf,
412 PDK_Unknown
413 };
414}
415
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000416std::pair<unsigned, bool>
Douglas Gregordf95a132010-08-09 20:45:32 +0000417Lexer::ComputePreamble(const llvm::MemoryBuffer *Buffer, unsigned MaxLines) {
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000418 // Create a lexer starting at the beginning of the file. Note that we use a
419 // "fake" file source location at offset 1 so that the lexer will track our
420 // position within the file.
421 const unsigned StartOffset = 1;
422 SourceLocation StartLoc = SourceLocation::getFromRawEncoding(StartOffset);
423 LangOptions LangOpts;
424 Lexer TheLexer(StartLoc, LangOpts, Buffer->getBufferStart(),
425 Buffer->getBufferStart(), Buffer->getBufferEnd());
426
427 bool InPreprocessorDirective = false;
428 Token TheTok;
429 Token IfStartTok;
430 unsigned IfCount = 0;
Douglas Gregordf95a132010-08-09 20:45:32 +0000431 unsigned Line = 0;
432
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000433 do {
434 TheLexer.LexFromRawLexer(TheTok);
435
436 if (InPreprocessorDirective) {
437 // If we've hit the end of the file, we're done.
438 if (TheTok.getKind() == tok::eof) {
439 InPreprocessorDirective = false;
440 break;
441 }
442
443 // If we haven't hit the end of the preprocessor directive, skip this
444 // token.
445 if (!TheTok.isAtStartOfLine())
446 continue;
447
448 // We've passed the end of the preprocessor directive, and will look
449 // at this token again below.
450 InPreprocessorDirective = false;
451 }
452
Douglas Gregordf95a132010-08-09 20:45:32 +0000453 // Keep track of the # of lines in the preamble.
454 if (TheTok.isAtStartOfLine()) {
455 ++Line;
456
457 // If we were asked to limit the number of lines in the preamble,
458 // and we're about to exceed that limit, we're done.
459 if (MaxLines && Line >= MaxLines)
460 break;
461 }
462
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000463 // Comments are okay; skip over them.
464 if (TheTok.getKind() == tok::comment)
465 continue;
466
467 if (TheTok.isAtStartOfLine() && TheTok.getKind() == tok::hash) {
468 // This is the start of a preprocessor directive.
469 Token HashTok = TheTok;
470 InPreprocessorDirective = true;
471
472 // Figure out which direective this is. Since we're lexing raw tokens,
473 // we don't have an identifier table available. Instead, just look at
474 // the raw identifier to recognize and categorize preprocessor directives.
475 TheLexer.LexFromRawLexer(TheTok);
476 if (TheTok.getKind() == tok::identifier && !TheTok.needsCleaning()) {
477 const char *IdStart = Buffer->getBufferStart()
478 + TheTok.getLocation().getRawEncoding() - 1;
479 llvm::StringRef Keyword(IdStart, TheTok.getLength());
480 PreambleDirectiveKind PDK
481 = llvm::StringSwitch<PreambleDirectiveKind>(Keyword)
482 .Case("include", PDK_Skipped)
483 .Case("__include_macros", PDK_Skipped)
484 .Case("define", PDK_Skipped)
485 .Case("undef", PDK_Skipped)
486 .Case("line", PDK_Skipped)
487 .Case("error", PDK_Skipped)
488 .Case("pragma", PDK_Skipped)
489 .Case("import", PDK_Skipped)
490 .Case("include_next", PDK_Skipped)
491 .Case("warning", PDK_Skipped)
492 .Case("ident", PDK_Skipped)
493 .Case("sccs", PDK_Skipped)
494 .Case("assert", PDK_Skipped)
495 .Case("unassert", PDK_Skipped)
496 .Case("if", PDK_StartIf)
497 .Case("ifdef", PDK_StartIf)
498 .Case("ifndef", PDK_StartIf)
499 .Case("elif", PDK_Skipped)
500 .Case("else", PDK_Skipped)
501 .Case("endif", PDK_EndIf)
502 .Default(PDK_Unknown);
503
504 switch (PDK) {
505 case PDK_Skipped:
506 continue;
507
508 case PDK_StartIf:
509 if (IfCount == 0)
510 IfStartTok = HashTok;
511
512 ++IfCount;
513 continue;
514
515 case PDK_EndIf:
516 // Mismatched #endif. The preamble ends here.
517 if (IfCount == 0)
518 break;
519
520 --IfCount;
521 continue;
522
523 case PDK_Unknown:
524 // We don't know what this directive is; stop at the '#'.
525 break;
526 }
527 }
528
529 // We only end up here if we didn't recognize the preprocessor
530 // directive or it was one that can't occur in the preamble at this
531 // point. Roll back the current token to the location of the '#'.
532 InPreprocessorDirective = false;
533 TheTok = HashTok;
534 }
535
Douglas Gregordf95a132010-08-09 20:45:32 +0000536 // We hit a token that we don't recognize as being in the
537 // "preprocessing only" part of the file, so we're no longer in
538 // the preamble.
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000539 break;
540 } while (true);
541
542 SourceLocation End = IfCount? IfStartTok.getLocation() : TheTok.getLocation();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000543 return std::make_pair(End.getRawEncoding() - StartLoc.getRawEncoding(),
544 IfCount? IfStartTok.isAtStartOfLine()
545 : TheTok.isAtStartOfLine());
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000546}
547
Chris Lattner7ef5c272010-11-17 07:05:50 +0000548
549/// AdvanceToTokenCharacter - Given a location that specifies the start of a
550/// token, return a new location that specifies a character within the token.
551SourceLocation Lexer::AdvanceToTokenCharacter(SourceLocation TokStart,
552 unsigned CharNo,
553 const SourceManager &SM,
554 const LangOptions &Features) {
555 // Figure out how many physical characters away the specified instantiation
556 // character is. This needs to take into consideration newlines and
557 // trigraphs.
558 bool Invalid = false;
559 const char *TokPtr = SM.getCharacterData(TokStart, &Invalid);
560
561 // If they request the first char of the token, we're trivially done.
562 if (Invalid || (CharNo == 0 && Lexer::isObviouslySimpleCharacter(*TokPtr)))
563 return TokStart;
564
565 unsigned PhysOffset = 0;
566
567 // The usual case is that tokens don't contain anything interesting. Skip
568 // over the uninteresting characters. If a token only consists of simple
569 // chars, this method is extremely fast.
570 while (Lexer::isObviouslySimpleCharacter(*TokPtr)) {
571 if (CharNo == 0)
572 return TokStart.getFileLocWithOffset(PhysOffset);
573 ++TokPtr, --CharNo, ++PhysOffset;
574 }
575
576 // If we have a character that may be a trigraph or escaped newline, use a
577 // lexer to parse it correctly.
578 for (; CharNo; --CharNo) {
579 unsigned Size;
580 Lexer::getCharAndSizeNoWarn(TokPtr, Size, Features);
581 TokPtr += Size;
582 PhysOffset += Size;
583 }
584
585 // Final detail: if we end up on an escaped newline, we want to return the
586 // location of the actual byte of the token. For example foo\<newline>bar
587 // advanced by 3 should return the location of b, not of \\. One compounding
588 // detail of this is that the escape may be made by a trigraph.
589 if (!Lexer::isObviouslySimpleCharacter(*TokPtr))
590 PhysOffset += Lexer::SkipEscapedNewLines(TokPtr)-TokPtr;
591
592 return TokStart.getFileLocWithOffset(PhysOffset);
593}
594
595/// \brief Computes the source location just past the end of the
596/// token at this source location.
597///
598/// This routine can be used to produce a source location that
599/// points just past the end of the token referenced by \p Loc, and
600/// is generally used when a diagnostic needs to point just after a
601/// token where it expected something different that it received. If
602/// the returned source location would not be meaningful (e.g., if
603/// it points into a macro), this routine returns an invalid
604/// source location.
605///
606/// \param Offset an offset from the end of the token, where the source
607/// location should refer to. The default offset (0) produces a source
608/// location pointing just past the end of the token; an offset of 1 produces
609/// a source location pointing to the last character in the token, etc.
610SourceLocation Lexer::getLocForEndOfToken(SourceLocation Loc, unsigned Offset,
611 const SourceManager &SM,
612 const LangOptions &Features) {
613 if (Loc.isInvalid() || !Loc.isFileID())
614 return SourceLocation();
615
616 unsigned Len = Lexer::MeasureTokenLength(Loc, SM, Features);
617 if (Len > Offset)
618 Len = Len - Offset;
619 else
620 return Loc;
621
622 return AdvanceToTokenCharacter(Loc, Len, SM, Features);
623}
624
Reid Spencer5f016e22007-07-11 17:01:13 +0000625//===----------------------------------------------------------------------===//
626// Character information.
627//===----------------------------------------------------------------------===//
628
Reid Spencer5f016e22007-07-11 17:01:13 +0000629enum {
630 CHAR_HORZ_WS = 0x01, // ' ', '\t', '\f', '\v'. Note, no '\0'
631 CHAR_VERT_WS = 0x02, // '\r', '\n'
632 CHAR_LETTER = 0x04, // a-z,A-Z
633 CHAR_NUMBER = 0x08, // 0-9
634 CHAR_UNDER = 0x10, // _
635 CHAR_PERIOD = 0x20 // .
636};
637
Chris Lattner03b98662009-07-07 17:09:54 +0000638// Statically initialize CharInfo table based on ASCII character set
639// Reference: FreeBSD 7.2 /usr/share/misc/ascii
Chris Lattnera2bf1052009-12-17 05:29:40 +0000640static const unsigned char CharInfo[256] =
Chris Lattner03b98662009-07-07 17:09:54 +0000641{
642// 0 NUL 1 SOH 2 STX 3 ETX
643// 4 EOT 5 ENQ 6 ACK 7 BEL
644 0 , 0 , 0 , 0 ,
645 0 , 0 , 0 , 0 ,
646// 8 BS 9 HT 10 NL 11 VT
647//12 NP 13 CR 14 SO 15 SI
648 0 , CHAR_HORZ_WS, CHAR_VERT_WS, CHAR_HORZ_WS,
649 CHAR_HORZ_WS, CHAR_VERT_WS, 0 , 0 ,
650//16 DLE 17 DC1 18 DC2 19 DC3
651//20 DC4 21 NAK 22 SYN 23 ETB
652 0 , 0 , 0 , 0 ,
653 0 , 0 , 0 , 0 ,
654//24 CAN 25 EM 26 SUB 27 ESC
655//28 FS 29 GS 30 RS 31 US
656 0 , 0 , 0 , 0 ,
657 0 , 0 , 0 , 0 ,
658//32 SP 33 ! 34 " 35 #
659//36 $ 37 % 38 & 39 '
660 CHAR_HORZ_WS, 0 , 0 , 0 ,
661 0 , 0 , 0 , 0 ,
662//40 ( 41 ) 42 * 43 +
663//44 , 45 - 46 . 47 /
664 0 , 0 , 0 , 0 ,
665 0 , 0 , CHAR_PERIOD , 0 ,
666//48 0 49 1 50 2 51 3
667//52 4 53 5 54 6 55 7
668 CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER ,
669 CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER ,
670//56 8 57 9 58 : 59 ;
671//60 < 61 = 62 > 63 ?
672 CHAR_NUMBER , CHAR_NUMBER , 0 , 0 ,
673 0 , 0 , 0 , 0 ,
674//64 @ 65 A 66 B 67 C
675//68 D 69 E 70 F 71 G
676 0 , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
677 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
678//72 H 73 I 74 J 75 K
679//76 L 77 M 78 N 79 O
680 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
681 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
682//80 P 81 Q 82 R 83 S
683//84 T 85 U 86 V 87 W
684 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
685 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
686//88 X 89 Y 90 Z 91 [
687//92 \ 93 ] 94 ^ 95 _
688 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , 0 ,
689 0 , 0 , 0 , CHAR_UNDER ,
690//96 ` 97 a 98 b 99 c
691//100 d 101 e 102 f 103 g
692 0 , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
693 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
694//104 h 105 i 106 j 107 k
695//108 l 109 m 110 n 111 o
696 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
697 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
698//112 p 113 q 114 r 115 s
699//116 t 117 u 118 v 119 w
700 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
701 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
702//120 x 121 y 122 z 123 {
703//124 | 125 } 126 ~ 127 DEL
704 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , 0 ,
705 0 , 0 , 0 , 0
706};
707
Chris Lattnera2bf1052009-12-17 05:29:40 +0000708static void InitCharacterInfo() {
Reid Spencer5f016e22007-07-11 17:01:13 +0000709 static bool isInited = false;
710 if (isInited) return;
Chris Lattner03b98662009-07-07 17:09:54 +0000711 // check the statically-initialized CharInfo table
712 assert(CHAR_HORZ_WS == CharInfo[(int)' ']);
713 assert(CHAR_HORZ_WS == CharInfo[(int)'\t']);
714 assert(CHAR_HORZ_WS == CharInfo[(int)'\f']);
715 assert(CHAR_HORZ_WS == CharInfo[(int)'\v']);
716 assert(CHAR_VERT_WS == CharInfo[(int)'\n']);
717 assert(CHAR_VERT_WS == CharInfo[(int)'\r']);
718 assert(CHAR_UNDER == CharInfo[(int)'_']);
719 assert(CHAR_PERIOD == CharInfo[(int)'.']);
720 for (unsigned i = 'a'; i <= 'z'; ++i) {
721 assert(CHAR_LETTER == CharInfo[i]);
722 assert(CHAR_LETTER == CharInfo[i+'A'-'a']);
723 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000724 for (unsigned i = '0'; i <= '9'; ++i)
Chris Lattner03b98662009-07-07 17:09:54 +0000725 assert(CHAR_NUMBER == CharInfo[i]);
Steve Naroff7b682652009-12-08 16:38:12 +0000726
Chris Lattner03b98662009-07-07 17:09:54 +0000727 isInited = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000728}
729
Chris Lattner03b98662009-07-07 17:09:54 +0000730
Reid Spencer5f016e22007-07-11 17:01:13 +0000731/// isIdentifierBody - Return true if this is the body character of an
732/// identifier, which is [a-zA-Z0-9_].
733static inline bool isIdentifierBody(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000734 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER)) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000735}
736
737/// isHorizontalWhitespace - Return true if this character is horizontal
738/// whitespace: ' ', '\t', '\f', '\v'. Note that this returns false for '\0'.
739static inline bool isHorizontalWhitespace(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000740 return (CharInfo[c] & CHAR_HORZ_WS) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000741}
742
743/// isWhitespace - Return true if this character is horizontal or vertical
744/// whitespace: ' ', '\t', '\f', '\v', '\n', '\r'. Note that this returns false
745/// for '\0'.
746static inline bool isWhitespace(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000747 return (CharInfo[c] & (CHAR_HORZ_WS|CHAR_VERT_WS)) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000748}
749
750/// isNumberBody - Return true if this is the body character of an
751/// preprocessing number, which is [a-zA-Z0-9_.].
752static inline bool isNumberBody(unsigned char c) {
Mike Stump1eb44332009-09-09 15:08:12 +0000753 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER|CHAR_PERIOD)) ?
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000754 true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000755}
756
757
758//===----------------------------------------------------------------------===//
759// Diagnostics forwarding code.
760//===----------------------------------------------------------------------===//
761
Chris Lattner409a0362007-07-22 18:38:25 +0000762/// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
763/// lexer buffer was all instantiated at a single point, perform the mapping.
764/// This is currently only used for _Pragma implementation, so it is the slow
765/// path of the hot getSourceLocation method. Do not allow it to be inlined.
Chandler Carruth14bd9652010-10-23 08:44:57 +0000766static LLVM_ATTRIBUTE_NOINLINE SourceLocation GetMappedTokenLoc(
767 Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen);
Chris Lattner409a0362007-07-22 18:38:25 +0000768static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
769 SourceLocation FileLoc,
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000770 unsigned CharNo, unsigned TokLen) {
Chris Lattnere7fb4842009-02-15 20:52:18 +0000771 assert(FileLoc.isMacroID() && "Must be an instantiation");
Mike Stump1eb44332009-09-09 15:08:12 +0000772
Chris Lattner409a0362007-07-22 18:38:25 +0000773 // Otherwise, we're lexing "mapped tokens". This is used for things like
774 // _Pragma handling. Combine the instantiation location of FileLoc with the
Chris Lattnerdf7c17a2009-01-16 07:00:02 +0000775 // spelling location.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000776 SourceManager &SM = PP.getSourceManager();
Mike Stump1eb44332009-09-09 15:08:12 +0000777
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000778 // Create a new SLoc which is expanded from Instantiation(FileLoc) but whose
Chris Lattnerdf7c17a2009-01-16 07:00:02 +0000779 // characters come from spelling(FileLoc)+Offset.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000780 SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc);
Chris Lattnerbcc2a672009-01-19 06:46:35 +0000781 SpellingLoc = SpellingLoc.getFileLocWithOffset(CharNo);
Mike Stump1eb44332009-09-09 15:08:12 +0000782
Chris Lattnere7fb4842009-02-15 20:52:18 +0000783 // Figure out the expansion loc range, which is the range covered by the
784 // original _Pragma(...) sequence.
785 std::pair<SourceLocation,SourceLocation> II =
786 SM.getImmediateInstantiationRange(FileLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000787
Chris Lattnere7fb4842009-02-15 20:52:18 +0000788 return SM.createInstantiationLoc(SpellingLoc, II.first, II.second, TokLen);
Chris Lattner409a0362007-07-22 18:38:25 +0000789}
790
Reid Spencer5f016e22007-07-11 17:01:13 +0000791/// getSourceLocation - Return a source location identifier for the specified
792/// offset in the current file.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000793SourceLocation Lexer::getSourceLocation(const char *Loc,
794 unsigned TokLen) const {
Chris Lattner448cec42007-07-22 18:44:36 +0000795 assert(Loc >= BufferStart && Loc <= BufferEnd &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000796 "Location out of range for this buffer!");
Chris Lattner9dc1f532007-07-20 16:37:10 +0000797
798 // In the normal case, we're just lexing from a simple file buffer, return
799 // the file id from FileLoc with the offset specified.
Chris Lattner448cec42007-07-22 18:44:36 +0000800 unsigned CharNo = Loc-BufferStart;
Chris Lattner9dc1f532007-07-20 16:37:10 +0000801 if (FileLoc.isFileID())
Chris Lattnerbcc2a672009-01-19 06:46:35 +0000802 return FileLoc.getFileLocWithOffset(CharNo);
Mike Stump1eb44332009-09-09 15:08:12 +0000803
Chris Lattner2b2453a2009-01-17 06:22:33 +0000804 // Otherwise, this is the _Pragma lexer case, which pretends that all of the
805 // tokens are lexed from where the _Pragma was defined.
Chris Lattner168ae2d2007-10-17 20:41:00 +0000806 assert(PP && "This doesn't work on raw lexers");
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000807 return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen);
Reid Spencer5f016e22007-07-11 17:01:13 +0000808}
809
Reid Spencer5f016e22007-07-11 17:01:13 +0000810/// Diag - Forwarding function for diagnostics. This translate a source
811/// position in the current buffer into a SourceLocation object for rendering.
Chris Lattner3cbfe2c2008-11-22 00:59:29 +0000812DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
Chris Lattner3692b092008-11-18 07:59:24 +0000813 return PP->Diag(getSourceLocation(Loc), DiagID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000814}
Reid Spencer5f016e22007-07-11 17:01:13 +0000815
816//===----------------------------------------------------------------------===//
817// Trigraph and Escaped Newline Handling Code.
818//===----------------------------------------------------------------------===//
819
820/// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
821/// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
822static char GetTrigraphCharForLetter(char Letter) {
823 switch (Letter) {
824 default: return 0;
825 case '=': return '#';
826 case ')': return ']';
827 case '(': return '[';
828 case '!': return '|';
829 case '\'': return '^';
830 case '>': return '}';
831 case '/': return '\\';
832 case '<': return '{';
833 case '-': return '~';
834 }
835}
836
837/// DecodeTrigraphChar - If the specified character is a legal trigraph when
838/// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
839/// return the result character. Finally, emit a warning about trigraph use
840/// whether trigraphs are enabled or not.
841static char DecodeTrigraphChar(const char *CP, Lexer *L) {
842 char Res = GetTrigraphCharForLetter(*CP);
Chris Lattner3692b092008-11-18 07:59:24 +0000843 if (!Res || !L) return Res;
Mike Stump1eb44332009-09-09 15:08:12 +0000844
Chris Lattner3692b092008-11-18 07:59:24 +0000845 if (!L->getFeatures().Trigraphs) {
Chris Lattner74d15df2008-11-22 02:02:22 +0000846 if (!L->isLexingRawMode())
847 L->Diag(CP-2, diag::trigraph_ignored);
Chris Lattner3692b092008-11-18 07:59:24 +0000848 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000849 }
Mike Stump1eb44332009-09-09 15:08:12 +0000850
Chris Lattner74d15df2008-11-22 02:02:22 +0000851 if (!L->isLexingRawMode())
Benjamin Kramer476d8b82010-08-11 14:47:12 +0000852 L->Diag(CP-2, diag::trigraph_converted) << llvm::StringRef(&Res, 1);
Reid Spencer5f016e22007-07-11 17:01:13 +0000853 return Res;
854}
855
Chris Lattner24f0e482009-04-18 22:05:41 +0000856/// getEscapedNewLineSize - Return the size of the specified escaped newline,
857/// or 0 if it is not an escaped newline. P[-1] is known to be a "\" or a
Mike Stump1eb44332009-09-09 15:08:12 +0000858/// trigraph equivalent on entry to this function.
Chris Lattner24f0e482009-04-18 22:05:41 +0000859unsigned Lexer::getEscapedNewLineSize(const char *Ptr) {
860 unsigned Size = 0;
861 while (isWhitespace(Ptr[Size])) {
862 ++Size;
Mike Stump1eb44332009-09-09 15:08:12 +0000863
Chris Lattner24f0e482009-04-18 22:05:41 +0000864 if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r')
865 continue;
866
867 // If this is a \r\n or \n\r, skip the other half.
868 if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') &&
869 Ptr[Size-1] != Ptr[Size])
870 ++Size;
Mike Stump1eb44332009-09-09 15:08:12 +0000871
Chris Lattner24f0e482009-04-18 22:05:41 +0000872 return Size;
Mike Stump1eb44332009-09-09 15:08:12 +0000873 }
874
Chris Lattner24f0e482009-04-18 22:05:41 +0000875 // Not an escaped newline, must be a \t or something else.
876 return 0;
877}
878
Chris Lattner03374952009-04-18 22:27:02 +0000879/// SkipEscapedNewLines - If P points to an escaped newline (or a series of
880/// them), skip over them and return the first non-escaped-newline found,
881/// otherwise return P.
882const char *Lexer::SkipEscapedNewLines(const char *P) {
883 while (1) {
884 const char *AfterEscape;
885 if (*P == '\\') {
886 AfterEscape = P+1;
887 } else if (*P == '?') {
888 // If not a trigraph for escape, bail out.
889 if (P[1] != '?' || P[2] != '/')
890 return P;
891 AfterEscape = P+3;
892 } else {
893 return P;
894 }
Mike Stump1eb44332009-09-09 15:08:12 +0000895
Chris Lattner03374952009-04-18 22:27:02 +0000896 unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape);
897 if (NewLineSize == 0) return P;
898 P = AfterEscape+NewLineSize;
899 }
900}
901
Chris Lattner24f0e482009-04-18 22:05:41 +0000902
Reid Spencer5f016e22007-07-11 17:01:13 +0000903/// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
904/// get its size, and return it. This is tricky in several cases:
905/// 1. If currently at the start of a trigraph, we warn about the trigraph,
906/// then either return the trigraph (skipping 3 chars) or the '?',
907/// depending on whether trigraphs are enabled or not.
908/// 2. If this is an escaped newline (potentially with whitespace between
909/// the backslash and newline), implicitly skip the newline and return
910/// the char after it.
911/// 3. If this is a UCN, return it. FIXME: C++ UCN's?
912///
913/// This handles the slow/uncommon case of the getCharAndSize method. Here we
914/// know that we can accumulate into Size, and that we have already incremented
915/// Ptr by Size bytes.
916///
917/// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
918/// be updated to match.
919///
920char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
Chris Lattnerd2177732007-07-20 16:59:19 +0000921 Token *Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000922 // If we have a slash, look for an escaped newline.
923 if (Ptr[0] == '\\') {
924 ++Size;
925 ++Ptr;
926Slash:
927 // Common case, backslash-char where the char is not whitespace.
928 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump1eb44332009-09-09 15:08:12 +0000929
Chris Lattner5636a3b2009-06-23 05:15:06 +0000930 // See if we have optional whitespace characters between the slash and
931 // newline.
Chris Lattner24f0e482009-04-18 22:05:41 +0000932 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
933 // Remember that this token needs to be cleaned.
934 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +0000935
Chris Lattner24f0e482009-04-18 22:05:41 +0000936 // Warn if there was whitespace between the backslash and newline.
Chris Lattner5636a3b2009-06-23 05:15:06 +0000937 if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode())
Chris Lattner24f0e482009-04-18 22:05:41 +0000938 Diag(Ptr, diag::backslash_newline_space);
Mike Stump1eb44332009-09-09 15:08:12 +0000939
Chris Lattner24f0e482009-04-18 22:05:41 +0000940 // Found backslash<whitespace><newline>. Parse the char after it.
941 Size += EscapedNewLineSize;
942 Ptr += EscapedNewLineSize;
943 // Use slow version to accumulate a correct size field.
944 return getCharAndSizeSlow(Ptr, Size, Tok);
945 }
Mike Stump1eb44332009-09-09 15:08:12 +0000946
Reid Spencer5f016e22007-07-11 17:01:13 +0000947 // Otherwise, this is not an escaped newline, just return the slash.
948 return '\\';
949 }
Mike Stump1eb44332009-09-09 15:08:12 +0000950
Reid Spencer5f016e22007-07-11 17:01:13 +0000951 // If this is a trigraph, process it.
952 if (Ptr[0] == '?' && Ptr[1] == '?') {
953 // If this is actually a legal trigraph (not something like "??x"), emit
954 // a trigraph warning. If so, and if trigraphs are enabled, return it.
955 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : 0)) {
956 // Remember that this token needs to be cleaned.
Chris Lattnerd2177732007-07-20 16:59:19 +0000957 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +0000958
959 Ptr += 3;
960 Size += 3;
961 if (C == '\\') goto Slash;
962 return C;
963 }
964 }
Mike Stump1eb44332009-09-09 15:08:12 +0000965
Reid Spencer5f016e22007-07-11 17:01:13 +0000966 // If this is neither, return a single character.
967 ++Size;
968 return *Ptr;
969}
970
971
972/// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
973/// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
974/// and that we have already incremented Ptr by Size bytes.
975///
976/// NOTE: When this method is updated, getCharAndSizeSlow (above) should
977/// be updated to match.
978char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
979 const LangOptions &Features) {
980 // If we have a slash, look for an escaped newline.
981 if (Ptr[0] == '\\') {
982 ++Size;
983 ++Ptr;
984Slash:
985 // Common case, backslash-char where the char is not whitespace.
986 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump1eb44332009-09-09 15:08:12 +0000987
Reid Spencer5f016e22007-07-11 17:01:13 +0000988 // See if we have optional whitespace characters followed by a newline.
Chris Lattner24f0e482009-04-18 22:05:41 +0000989 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
990 // Found backslash<whitespace><newline>. Parse the char after it.
991 Size += EscapedNewLineSize;
992 Ptr += EscapedNewLineSize;
Mike Stump1eb44332009-09-09 15:08:12 +0000993
Chris Lattner24f0e482009-04-18 22:05:41 +0000994 // Use slow version to accumulate a correct size field.
995 return getCharAndSizeSlowNoWarn(Ptr, Size, Features);
996 }
Mike Stump1eb44332009-09-09 15:08:12 +0000997
Reid Spencer5f016e22007-07-11 17:01:13 +0000998 // Otherwise, this is not an escaped newline, just return the slash.
999 return '\\';
1000 }
Mike Stump1eb44332009-09-09 15:08:12 +00001001
Reid Spencer5f016e22007-07-11 17:01:13 +00001002 // If this is a trigraph, process it.
1003 if (Features.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
1004 // If this is actually a legal trigraph (not something like "??x"), return
1005 // it.
1006 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
1007 Ptr += 3;
1008 Size += 3;
1009 if (C == '\\') goto Slash;
1010 return C;
1011 }
1012 }
Mike Stump1eb44332009-09-09 15:08:12 +00001013
Reid Spencer5f016e22007-07-11 17:01:13 +00001014 // If this is neither, return a single character.
1015 ++Size;
1016 return *Ptr;
1017}
1018
1019//===----------------------------------------------------------------------===//
1020// Helper methods for lexing.
1021//===----------------------------------------------------------------------===//
1022
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001023/// \brief Routine that indiscriminately skips bytes in the source file.
1024void Lexer::SkipBytes(unsigned Bytes, bool StartOfLine) {
1025 BufferPtr += Bytes;
1026 if (BufferPtr > BufferEnd)
1027 BufferPtr = BufferEnd;
1028 IsAtStartOfLine = StartOfLine;
1029}
1030
Chris Lattnerd2177732007-07-20 16:59:19 +00001031void Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001032 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
1033 unsigned Size;
1034 unsigned char C = *CurPtr++;
Chris Lattnercd991db2010-01-11 02:38:50 +00001035 while (isIdentifierBody(C))
Reid Spencer5f016e22007-07-11 17:01:13 +00001036 C = *CurPtr++;
Chris Lattnercd991db2010-01-11 02:38:50 +00001037
Reid Spencer5f016e22007-07-11 17:01:13 +00001038 --CurPtr; // Back up over the skipped character.
1039
1040 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
1041 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
1042 // FIXME: UCNs.
Chris Lattnercd991db2010-01-11 02:38:50 +00001043 //
1044 // TODO: Could merge these checks into a CharInfo flag to make the comparison
1045 // cheaper
Reid Spencer5f016e22007-07-11 17:01:13 +00001046 if (C != '\\' && C != '?' && (C != '$' || !Features.DollarIdents)) {
1047FinishIdentifier:
1048 const char *IdStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001049 FormTokenWithChars(Result, CurPtr, tok::identifier);
Mike Stump1eb44332009-09-09 15:08:12 +00001050
Reid Spencer5f016e22007-07-11 17:01:13 +00001051 // If we are in raw mode, return this identifier raw. There is no need to
1052 // look up identifier information or attempt to macro expand it.
1053 if (LexingRawMode) return;
Mike Stump1eb44332009-09-09 15:08:12 +00001054
Reid Spencer5f016e22007-07-11 17:01:13 +00001055 // Fill in Result.IdentifierInfo, looking up the identifier in the
1056 // identifier table.
Chris Lattnerd1186fa2009-01-21 07:45:14 +00001057 IdentifierInfo *II = PP->LookUpIdentifierInfo(Result, IdStart);
Mike Stump1eb44332009-09-09 15:08:12 +00001058
Chris Lattner863c4862009-01-23 18:35:48 +00001059 // Change the kind of this identifier to the appropriate token kind, e.g.
1060 // turning "for" into a keyword.
1061 Result.setKind(II->getTokenID());
Mike Stump1eb44332009-09-09 15:08:12 +00001062
Reid Spencer5f016e22007-07-11 17:01:13 +00001063 // Finally, now that we know we have an identifier, pass this off to the
1064 // preprocessor, which may macro expand it or something.
Chris Lattnerd1186fa2009-01-21 07:45:14 +00001065 if (II->isHandleIdentifierCase())
Chris Lattner6a170eb2009-01-21 07:43:11 +00001066 PP->HandleIdentifier(Result);
1067 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00001068 }
Mike Stump1eb44332009-09-09 15:08:12 +00001069
Reid Spencer5f016e22007-07-11 17:01:13 +00001070 // Otherwise, $,\,? in identifier found. Enter slower path.
Mike Stump1eb44332009-09-09 15:08:12 +00001071
Reid Spencer5f016e22007-07-11 17:01:13 +00001072 C = getCharAndSize(CurPtr, Size);
1073 while (1) {
1074 if (C == '$') {
1075 // If we hit a $ and they are not supported in identifiers, we are done.
1076 if (!Features.DollarIdents) goto FinishIdentifier;
Mike Stump1eb44332009-09-09 15:08:12 +00001077
Reid Spencer5f016e22007-07-11 17:01:13 +00001078 // Otherwise, emit a diagnostic and continue.
Chris Lattner74d15df2008-11-22 02:02:22 +00001079 if (!isLexingRawMode())
1080 Diag(CurPtr, diag::ext_dollar_in_identifier);
Reid Spencer5f016e22007-07-11 17:01:13 +00001081 CurPtr = ConsumeChar(CurPtr, Size, Result);
1082 C = getCharAndSize(CurPtr, Size);
1083 continue;
1084 } else if (!isIdentifierBody(C)) { // FIXME: UCNs.
1085 // Found end of identifier.
1086 goto FinishIdentifier;
1087 }
1088
1089 // Otherwise, this character is good, consume it.
1090 CurPtr = ConsumeChar(CurPtr, Size, Result);
1091
1092 C = getCharAndSize(CurPtr, Size);
1093 while (isIdentifierBody(C)) { // FIXME: UCNs.
1094 CurPtr = ConsumeChar(CurPtr, Size, Result);
1095 C = getCharAndSize(CurPtr, Size);
1096 }
1097 }
1098}
1099
Douglas Gregora75ec432010-08-30 14:50:47 +00001100/// isHexaLiteral - Return true if Start points to a hex constant.
Chris Lattner4a551002010-08-30 17:11:14 +00001101/// in microsoft mode (where this is supposed to be several different tokens).
Chris Lattner6ab55eb2010-08-31 16:42:00 +00001102static bool isHexaLiteral(const char *Start, const LangOptions &Features) {
1103 unsigned Size;
1104 char C1 = Lexer::getCharAndSizeNoWarn(Start, Size, Features);
1105 if (C1 != '0')
1106 return false;
1107 char C2 = Lexer::getCharAndSizeNoWarn(Start + Size, Size, Features);
1108 return (C2 == 'x' || C2 == 'X');
Douglas Gregora75ec432010-08-30 14:50:47 +00001109}
Reid Spencer5f016e22007-07-11 17:01:13 +00001110
Nate Begeman5253c7f2008-04-14 02:26:39 +00001111/// LexNumericConstant - Lex the remainder of a integer or floating point
Reid Spencer5f016e22007-07-11 17:01:13 +00001112/// constant. From[-1] is the first character lexed. Return the end of the
1113/// constant.
Chris Lattnerd2177732007-07-20 16:59:19 +00001114void Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001115 unsigned Size;
1116 char C = getCharAndSize(CurPtr, Size);
1117 char PrevCh = 0;
1118 while (isNumberBody(C)) { // FIXME: UCNs?
1119 CurPtr = ConsumeChar(CurPtr, Size, Result);
1120 PrevCh = C;
1121 C = getCharAndSize(CurPtr, Size);
1122 }
Mike Stump1eb44332009-09-09 15:08:12 +00001123
Reid Spencer5f016e22007-07-11 17:01:13 +00001124 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
Chris Lattnerb2f4a202010-08-30 17:09:08 +00001125 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) {
1126 // If we are in Microsoft mode, don't continue if the constant is hex.
1127 // For example, MSVC will accept the following as 3 tokens: 0x1234567e+1
Chris Lattner6ab55eb2010-08-31 16:42:00 +00001128 if (!Features.Microsoft || !isHexaLiteral(BufferPtr, Features))
Chris Lattnerb2f4a202010-08-30 17:09:08 +00001129 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1130 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001131
1132 // If we have a hex FP constant, continue.
Sean Hunt8c723402010-01-10 23:37:56 +00001133 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p') &&
Chris Lattnerb2f4a202010-08-30 17:09:08 +00001134 !Features.CPlusPlus0x)
Reid Spencer5f016e22007-07-11 17:01:13 +00001135 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
Mike Stump1eb44332009-09-09 15:08:12 +00001136
Reid Spencer5f016e22007-07-11 17:01:13 +00001137 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001138 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001139 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
Chris Lattner47246be2009-01-26 19:29:26 +00001140 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001141}
1142
1143/// LexStringLiteral - Lex the remainder of a string literal, after having lexed
1144/// either " or L".
Chris Lattnerd88dc482008-10-12 04:05:48 +00001145void Lexer::LexStringLiteral(Token &Result, const char *CurPtr, bool Wide) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001146 const char *NulCharacter = 0; // Does this string contain the \0 character?
Mike Stump1eb44332009-09-09 15:08:12 +00001147
Reid Spencer5f016e22007-07-11 17:01:13 +00001148 char C = getAndAdvanceChar(CurPtr, Result);
1149 while (C != '"') {
Chris Lattner571339c2010-05-30 23:27:38 +00001150 // Skip escaped characters. Escaped newlines will already be processed by
1151 // getAndAdvanceChar.
1152 if (C == '\\')
Reid Spencer5f016e22007-07-11 17:01:13 +00001153 C = getAndAdvanceChar(CurPtr, Result);
Douglas Gregor33611e02010-05-30 22:59:50 +00001154
Chris Lattner571339c2010-05-30 23:27:38 +00001155 if (C == '\n' || C == '\r' || // Newline.
Douglas Gregor33611e02010-05-30 22:59:50 +00001156 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Douglas Gregor55817af2010-08-25 17:04:25 +00001157 if (C == 0 && PP && PP->isCodeCompletionFile(FileLoc))
1158 PP->CodeCompleteNaturalLanguage();
1159 else if (!isLexingRawMode() && !Features.AsmPreprocessor)
Chris Lattner74d15df2008-11-22 02:02:22 +00001160 Diag(BufferPtr, diag::err_unterminated_string);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001161 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Reid Spencer5f016e22007-07-11 17:01:13 +00001162 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00001163 }
Chris Lattner571339c2010-05-30 23:27:38 +00001164
1165 if (C == 0)
1166 NulCharacter = CurPtr-1;
Reid Spencer5f016e22007-07-11 17:01:13 +00001167 C = getAndAdvanceChar(CurPtr, Result);
1168 }
Mike Stump1eb44332009-09-09 15:08:12 +00001169
Reid Spencer5f016e22007-07-11 17:01:13 +00001170 // If a nul character existed in the string, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001171 if (NulCharacter && !isLexingRawMode())
1172 Diag(NulCharacter, diag::null_in_string);
Reid Spencer5f016e22007-07-11 17:01:13 +00001173
Reid Spencer5f016e22007-07-11 17:01:13 +00001174 // Update the location of the token as well as the BufferPtr instance var.
Chris Lattner47246be2009-01-26 19:29:26 +00001175 const char *TokStart = BufferPtr;
Sean Hunt6cf75022010-08-30 17:47:05 +00001176 FormTokenWithChars(Result, CurPtr,
1177 Wide ? tok::wide_string_literal : tok::string_literal);
Chris Lattner47246be2009-01-26 19:29:26 +00001178 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001179}
1180
1181/// LexAngledStringLiteral - Lex the remainder of an angled string literal,
1182/// after having lexed the '<' character. This is used for #include filenames.
Chris Lattnerd2177732007-07-20 16:59:19 +00001183void Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001184 const char *NulCharacter = 0; // Does this string contain the \0 character?
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001185 const char *AfterLessPos = CurPtr;
Reid Spencer5f016e22007-07-11 17:01:13 +00001186 char C = getAndAdvanceChar(CurPtr, Result);
1187 while (C != '>') {
1188 // Skip escaped characters.
1189 if (C == '\\') {
1190 // Skip the escaped character.
1191 C = getAndAdvanceChar(CurPtr, Result);
1192 } else if (C == '\n' || C == '\r' || // Newline.
1193 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001194 // If the filename is unterminated, then it must just be a lone <
1195 // character. Return this as such.
1196 FormTokenWithChars(Result, AfterLessPos, tok::less);
Reid Spencer5f016e22007-07-11 17:01:13 +00001197 return;
1198 } else if (C == 0) {
1199 NulCharacter = CurPtr-1;
1200 }
1201 C = getAndAdvanceChar(CurPtr, Result);
1202 }
Mike Stump1eb44332009-09-09 15:08:12 +00001203
Reid Spencer5f016e22007-07-11 17:01:13 +00001204 // If a nul character existed in the string, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001205 if (NulCharacter && !isLexingRawMode())
1206 Diag(NulCharacter, diag::null_in_string);
Mike Stump1eb44332009-09-09 15:08:12 +00001207
Reid Spencer5f016e22007-07-11 17:01:13 +00001208 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001209 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001210 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
Chris Lattner47246be2009-01-26 19:29:26 +00001211 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001212}
1213
1214
1215/// LexCharConstant - Lex the remainder of a character constant, after having
1216/// lexed either ' or L'.
Chris Lattnerd2177732007-07-20 16:59:19 +00001217void Lexer::LexCharConstant(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001218 const char *NulCharacter = 0; // Does this character contain the \0 character?
1219
Reid Spencer5f016e22007-07-11 17:01:13 +00001220 char C = getAndAdvanceChar(CurPtr, Result);
1221 if (C == '\'') {
Chris Lattner33ab3f62009-03-18 21:10:12 +00001222 if (!isLexingRawMode() && !Features.AsmPreprocessor)
Chris Lattner74d15df2008-11-22 02:02:22 +00001223 Diag(BufferPtr, diag::err_empty_character);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001224 FormTokenWithChars(Result, CurPtr, tok::unknown);
Reid Spencer5f016e22007-07-11 17:01:13 +00001225 return;
Chris Lattnerd80f7862010-07-07 23:24:27 +00001226 }
1227
1228 while (C != '\'') {
1229 // Skip escaped characters.
1230 if (C == '\\') {
1231 // Skip the escaped character.
1232 // FIXME: UCN's
1233 C = getAndAdvanceChar(CurPtr, Result);
1234 } else if (C == '\n' || C == '\r' || // Newline.
1235 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Douglas Gregor55817af2010-08-25 17:04:25 +00001236 if (C == 0 && PP && PP->isCodeCompletionFile(FileLoc))
1237 PP->CodeCompleteNaturalLanguage();
1238 else if (!isLexingRawMode() && !Features.AsmPreprocessor)
Chris Lattnerd80f7862010-07-07 23:24:27 +00001239 Diag(BufferPtr, diag::err_unterminated_char);
1240 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1241 return;
1242 } else if (C == 0) {
1243 NulCharacter = CurPtr-1;
1244 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001245 C = getAndAdvanceChar(CurPtr, Result);
1246 }
Mike Stump1eb44332009-09-09 15:08:12 +00001247
Chris Lattnerd80f7862010-07-07 23:24:27 +00001248 // If a nul character existed in the character, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001249 if (NulCharacter && !isLexingRawMode())
1250 Diag(NulCharacter, diag::null_in_char);
Reid Spencer5f016e22007-07-11 17:01:13 +00001251
Reid Spencer5f016e22007-07-11 17:01:13 +00001252 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001253 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001254 FormTokenWithChars(Result, CurPtr, tok::char_constant);
Chris Lattner47246be2009-01-26 19:29:26 +00001255 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001256}
1257
1258/// SkipWhitespace - Efficiently skip over a series of whitespace characters.
1259/// Update BufferPtr to point to the next non-whitespace character and return.
Chris Lattnerd88dc482008-10-12 04:05:48 +00001260///
1261/// This method forms a token and returns true if KeepWhitespaceMode is enabled.
1262///
1263bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001264 // Whitespace - Skip it, then return the token after the whitespace.
1265 unsigned char Char = *CurPtr; // Skip consequtive spaces efficiently.
1266 while (1) {
1267 // Skip horizontal whitespace very aggressively.
1268 while (isHorizontalWhitespace(Char))
1269 Char = *++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001270
Daniel Dunbarddd3e8b2008-11-25 00:20:22 +00001271 // Otherwise if we have something other than whitespace, we're done.
Reid Spencer5f016e22007-07-11 17:01:13 +00001272 if (Char != '\n' && Char != '\r')
1273 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001274
Reid Spencer5f016e22007-07-11 17:01:13 +00001275 if (ParsingPreprocessorDirective) {
1276 // End of preprocessor directive line, let LexTokenInternal handle this.
1277 BufferPtr = CurPtr;
Chris Lattnerd88dc482008-10-12 04:05:48 +00001278 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001279 }
Mike Stump1eb44332009-09-09 15:08:12 +00001280
Reid Spencer5f016e22007-07-11 17:01:13 +00001281 // ok, but handle newline.
1282 // The returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00001283 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00001284 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00001285 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001286 Char = *++CurPtr;
1287 }
1288
1289 // If this isn't immediately after a newline, there is leading space.
1290 char PrevChar = CurPtr[-1];
1291 if (PrevChar != '\n' && PrevChar != '\r')
Chris Lattnerd2177732007-07-20 16:59:19 +00001292 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001293
Chris Lattnerd88dc482008-10-12 04:05:48 +00001294 // If the client wants us to return whitespace, return it now.
1295 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001296 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd88dc482008-10-12 04:05:48 +00001297 return true;
1298 }
Mike Stump1eb44332009-09-09 15:08:12 +00001299
Reid Spencer5f016e22007-07-11 17:01:13 +00001300 BufferPtr = CurPtr;
Chris Lattnerd88dc482008-10-12 04:05:48 +00001301 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001302}
1303
1304// SkipBCPLComment - We have just read the // characters from input. Skip until
1305// we find the newline character thats terminate the comment. Then update
Chris Lattner046c2272010-01-18 22:35:47 +00001306/// BufferPtr and return.
1307///
1308/// If we're in KeepCommentMode or any CommentHandler has inserted
1309/// some tokens, this will store the first token and return true.
Chris Lattnerd2177732007-07-20 16:59:19 +00001310bool Lexer::SkipBCPLComment(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001311 // If BCPL comments aren't explicitly enabled for this language, emit an
1312 // extension warning.
Chris Lattner74d15df2008-11-22 02:02:22 +00001313 if (!Features.BCPLComment && !isLexingRawMode()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001314 Diag(BufferPtr, diag::ext_bcpl_comment);
Mike Stump1eb44332009-09-09 15:08:12 +00001315
Reid Spencer5f016e22007-07-11 17:01:13 +00001316 // Mark them enabled so we only emit one warning for this translation
1317 // unit.
1318 Features.BCPLComment = true;
1319 }
Mike Stump1eb44332009-09-09 15:08:12 +00001320
Reid Spencer5f016e22007-07-11 17:01:13 +00001321 // Scan over the body of the comment. The common case, when scanning, is that
1322 // the comment contains normal ascii characters with nothing interesting in
1323 // them. As such, optimize for this case with the inner loop.
1324 char C;
1325 do {
1326 C = *CurPtr;
1327 // FIXME: Speedup BCPL comment lexing. Just scan for a \n or \r character.
1328 // If we find a \n character, scan backwards, checking to see if it's an
1329 // escaped newline, like we do for block comments.
Mike Stump1eb44332009-09-09 15:08:12 +00001330
Reid Spencer5f016e22007-07-11 17:01:13 +00001331 // Skip over characters in the fast loop.
1332 while (C != 0 && // Potentially EOF.
1333 C != '\\' && // Potentially escaped newline.
1334 C != '?' && // Potentially trigraph.
1335 C != '\n' && C != '\r') // Newline or DOS-style newline.
1336 C = *++CurPtr;
1337
1338 // If this is a newline, we're done.
1339 if (C == '\n' || C == '\r')
1340 break; // Found the newline? Break out!
Mike Stump1eb44332009-09-09 15:08:12 +00001341
Reid Spencer5f016e22007-07-11 17:01:13 +00001342 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001343 // properly decode the character. Read it in raw mode to avoid emitting
1344 // diagnostics about things like trigraphs. If we see an escaped newline,
1345 // we'll handle it below.
Reid Spencer5f016e22007-07-11 17:01:13 +00001346 const char *OldPtr = CurPtr;
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001347 bool OldRawMode = isLexingRawMode();
1348 LexingRawMode = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001349 C = getAndAdvanceChar(CurPtr, Result);
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001350 LexingRawMode = OldRawMode;
Chris Lattneread616c2009-04-05 00:26:41 +00001351
1352 // If the char that we finally got was a \n, then we must have had something
1353 // like \<newline><newline>. We don't want to have consumed the second
1354 // newline, we want CurPtr, to end up pointing to it down below.
1355 if (C == '\n' || C == '\r') {
1356 --CurPtr;
1357 C = 'x'; // doesn't matter what this is.
1358 }
Mike Stump1eb44332009-09-09 15:08:12 +00001359
Reid Spencer5f016e22007-07-11 17:01:13 +00001360 // If we read multiple characters, and one of those characters was a \r or
1361 // \n, then we had an escaped newline within the comment. Emit diagnostic
1362 // unless the next line is also a // comment.
1363 if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') {
1364 for (; OldPtr != CurPtr; ++OldPtr)
1365 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
1366 // Okay, we found a // comment that ends in a newline, if the next
1367 // line is also a // comment, but has spaces, don't emit a diagnostic.
1368 if (isspace(C)) {
1369 const char *ForwardPtr = CurPtr;
1370 while (isspace(*ForwardPtr)) // Skip whitespace.
1371 ++ForwardPtr;
1372 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
1373 break;
1374 }
Mike Stump1eb44332009-09-09 15:08:12 +00001375
Chris Lattner74d15df2008-11-22 02:02:22 +00001376 if (!isLexingRawMode())
1377 Diag(OldPtr-1, diag::ext_multi_line_bcpl_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001378 break;
1379 }
1380 }
Mike Stump1eb44332009-09-09 15:08:12 +00001381
Douglas Gregor55817af2010-08-25 17:04:25 +00001382 if (CurPtr == BufferEnd+1) {
1383 if (PP && PP->isCodeCompletionFile(FileLoc))
1384 PP->CodeCompleteNaturalLanguage();
1385
1386 --CurPtr;
1387 break;
1388 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001389 } while (C != '\n' && C != '\r');
1390
Chris Lattner3d0ad582010-02-03 21:06:21 +00001391 // Found but did not consume the newline. Notify comment handlers about the
1392 // comment unless we're in a #if 0 block.
1393 if (PP && !isLexingRawMode() &&
1394 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
1395 getSourceLocation(CurPtr)))) {
Chris Lattner046c2272010-01-18 22:35:47 +00001396 BufferPtr = CurPtr;
1397 return true; // A token has to be returned.
1398 }
Mike Stump1eb44332009-09-09 15:08:12 +00001399
Reid Spencer5f016e22007-07-11 17:01:13 +00001400 // If we are returning comments as tokens, return this comment as a token.
Chris Lattnerfa95a012008-10-12 03:22:02 +00001401 if (inKeepCommentMode())
Reid Spencer5f016e22007-07-11 17:01:13 +00001402 return SaveBCPLComment(Result, CurPtr);
1403
1404 // If we are inside a preprocessor directive and we see the end of line,
1405 // return immediately, so that the lexer can return this as an EOM token.
1406 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
1407 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001408 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001409 }
Mike Stump1eb44332009-09-09 15:08:12 +00001410
Reid Spencer5f016e22007-07-11 17:01:13 +00001411 // Otherwise, eat the \n character. We don't care if this is a \n\r or
Chris Lattner7a4f0042008-10-12 00:23:07 +00001412 // \r\n sequence. This is an efficiency hack (because we know the \n can't
Chris Lattnerd88dc482008-10-12 04:05:48 +00001413 // contribute to another token), it isn't needed for correctness. Note that
1414 // this is ok even in KeepWhitespaceMode, because we would have returned the
1415 /// comment above in that mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00001416 ++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001417
Reid Spencer5f016e22007-07-11 17:01:13 +00001418 // The next returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00001419 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00001420 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00001421 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001422 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001423 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001424}
1425
1426/// SaveBCPLComment - If in save-comment mode, package up this BCPL comment in
1427/// an appropriate way and return it.
Chris Lattnerd2177732007-07-20 16:59:19 +00001428bool Lexer::SaveBCPLComment(Token &Result, const char *CurPtr) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001429 // If we're not in a preprocessor directive, just return the // comment
1430 // directly.
1431 FormTokenWithChars(Result, CurPtr, tok::comment);
Mike Stump1eb44332009-09-09 15:08:12 +00001432
Chris Lattner9e6293d2008-10-12 04:51:35 +00001433 if (!ParsingPreprocessorDirective)
1434 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001435
Chris Lattner9e6293d2008-10-12 04:51:35 +00001436 // If this BCPL-style comment is in a macro definition, transmogrify it into
1437 // a C-style block comment.
Douglas Gregor453091c2010-03-16 22:30:13 +00001438 bool Invalid = false;
1439 std::string Spelling = PP->getSpelling(Result, &Invalid);
1440 if (Invalid)
1441 return true;
1442
Chris Lattner9e6293d2008-10-12 04:51:35 +00001443 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not bcpl comment?");
1444 Spelling[1] = '*'; // Change prefix to "/*".
1445 Spelling += "*/"; // add suffix.
Mike Stump1eb44332009-09-09 15:08:12 +00001446
Chris Lattner9e6293d2008-10-12 04:51:35 +00001447 Result.setKind(tok::comment);
Chris Lattner47246be2009-01-26 19:29:26 +00001448 PP->CreateString(&Spelling[0], Spelling.size(), Result,
1449 Result.getLocation());
Chris Lattner2d381892008-10-12 04:15:42 +00001450 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001451}
1452
1453/// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
1454/// character (either \n or \r) is part of an escaped newline sequence. Issue a
Chris Lattner47a2b402008-12-12 07:14:34 +00001455/// diagnostic if so. We know that the newline is inside of a block comment.
Mike Stump1eb44332009-09-09 15:08:12 +00001456static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
Reid Spencer5f016e22007-07-11 17:01:13 +00001457 Lexer *L) {
1458 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
Mike Stump1eb44332009-09-09 15:08:12 +00001459
Reid Spencer5f016e22007-07-11 17:01:13 +00001460 // Back up off the newline.
1461 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001462
Reid Spencer5f016e22007-07-11 17:01:13 +00001463 // If this is a two-character newline sequence, skip the other character.
1464 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
1465 // \n\n or \r\r -> not escaped newline.
1466 if (CurPtr[0] == CurPtr[1])
1467 return false;
1468 // \n\r or \r\n -> skip the newline.
1469 --CurPtr;
1470 }
Mike Stump1eb44332009-09-09 15:08:12 +00001471
Reid Spencer5f016e22007-07-11 17:01:13 +00001472 // If we have horizontal whitespace, skip over it. We allow whitespace
1473 // between the slash and newline.
1474 bool HasSpace = false;
1475 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
1476 --CurPtr;
1477 HasSpace = true;
1478 }
Mike Stump1eb44332009-09-09 15:08:12 +00001479
Reid Spencer5f016e22007-07-11 17:01:13 +00001480 // If we have a slash, we know this is an escaped newline.
1481 if (*CurPtr == '\\') {
1482 if (CurPtr[-1] != '*') return false;
1483 } else {
1484 // It isn't a slash, is it the ?? / trigraph?
1485 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
1486 CurPtr[-3] != '*')
1487 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001488
Reid Spencer5f016e22007-07-11 17:01:13 +00001489 // This is the trigraph ending the comment. Emit a stern warning!
1490 CurPtr -= 2;
1491
1492 // If no trigraphs are enabled, warn that we ignored this trigraph and
1493 // ignore this * character.
1494 if (!L->getFeatures().Trigraphs) {
Chris Lattner74d15df2008-11-22 02:02:22 +00001495 if (!L->isLexingRawMode())
1496 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001497 return false;
1498 }
Chris Lattner74d15df2008-11-22 02:02:22 +00001499 if (!L->isLexingRawMode())
1500 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001501 }
Mike Stump1eb44332009-09-09 15:08:12 +00001502
Reid Spencer5f016e22007-07-11 17:01:13 +00001503 // Warn about having an escaped newline between the */ characters.
Chris Lattner74d15df2008-11-22 02:02:22 +00001504 if (!L->isLexingRawMode())
1505 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
Mike Stump1eb44332009-09-09 15:08:12 +00001506
Reid Spencer5f016e22007-07-11 17:01:13 +00001507 // If there was space between the backslash and newline, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001508 if (HasSpace && !L->isLexingRawMode())
1509 L->Diag(CurPtr, diag::backslash_newline_space);
Mike Stump1eb44332009-09-09 15:08:12 +00001510
Reid Spencer5f016e22007-07-11 17:01:13 +00001511 return true;
1512}
1513
1514#ifdef __SSE2__
1515#include <emmintrin.h>
1516#elif __ALTIVEC__
1517#include <altivec.h>
1518#undef bool
1519#endif
1520
1521/// SkipBlockComment - We have just read the /* characters from input. Read
1522/// until we find the */ characters that terminate the comment. Note that we
1523/// don't bother decoding trigraphs or escaped newlines in block comments,
1524/// because they cannot cause the comment to end. The only thing that can
1525/// happen is the comment could end with an escaped newline between the */ end
1526/// of comment.
Chris Lattner2d381892008-10-12 04:15:42 +00001527///
Chris Lattner046c2272010-01-18 22:35:47 +00001528/// If we're in KeepCommentMode or any CommentHandler has inserted
1529/// some tokens, this will store the first token and return true.
Chris Lattnerd2177732007-07-20 16:59:19 +00001530bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001531 // Scan one character past where we should, looking for a '/' character. Once
1532 // we find it, check to see if it was preceeded by a *. This common
1533 // optimization helps people who like to put a lot of * characters in their
1534 // comments.
Chris Lattner8146b682007-07-21 23:43:37 +00001535
1536 // The first character we get with newlines and trigraphs skipped to handle
1537 // the degenerate /*/ case below correctly if the * has an escaped newline
1538 // after it.
1539 unsigned CharSize;
1540 unsigned char C = getCharAndSize(CurPtr, CharSize);
1541 CurPtr += CharSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001542 if (C == 0 && CurPtr == BufferEnd+1) {
Chris Lattner150fcd52010-05-16 19:54:05 +00001543 if (!isLexingRawMode() &&
1544 !PP->isCodeCompletionFile(FileLoc))
Chris Lattner0af57422008-10-12 01:31:51 +00001545 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner31f0eca2008-10-12 04:19:49 +00001546 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001547
Chris Lattner31f0eca2008-10-12 04:19:49 +00001548 // KeepWhitespaceMode should return this broken comment as a token. Since
1549 // it isn't a well formed comment, just return it as an 'unknown' token.
1550 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001551 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner31f0eca2008-10-12 04:19:49 +00001552 return true;
1553 }
Mike Stump1eb44332009-09-09 15:08:12 +00001554
Chris Lattner31f0eca2008-10-12 04:19:49 +00001555 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001556 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001557 }
Mike Stump1eb44332009-09-09 15:08:12 +00001558
Chris Lattner8146b682007-07-21 23:43:37 +00001559 // Check to see if the first character after the '/*' is another /. If so,
1560 // then this slash does not end the block comment, it is part of it.
1561 if (C == '/')
1562 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00001563
Reid Spencer5f016e22007-07-11 17:01:13 +00001564 while (1) {
1565 // Skip over all non-interesting characters until we find end of buffer or a
1566 // (probably ending) '/' character.
1567 if (CurPtr + 24 < BufferEnd) {
1568 // While not aligned to a 16-byte boundary.
1569 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
1570 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00001571
Reid Spencer5f016e22007-07-11 17:01:13 +00001572 if (C == '/') goto FoundSlash;
1573
1574#ifdef __SSE2__
1575 __m128i Slashes = _mm_set_epi8('/', '/', '/', '/', '/', '/', '/', '/',
1576 '/', '/', '/', '/', '/', '/', '/', '/');
1577 while (CurPtr+16 <= BufferEnd &&
1578 _mm_movemask_epi8(_mm_cmpeq_epi8(*(__m128i*)CurPtr, Slashes)) == 0)
1579 CurPtr += 16;
1580#elif __ALTIVEC__
1581 __vector unsigned char Slashes = {
Mike Stump1eb44332009-09-09 15:08:12 +00001582 '/', '/', '/', '/', '/', '/', '/', '/',
Reid Spencer5f016e22007-07-11 17:01:13 +00001583 '/', '/', '/', '/', '/', '/', '/', '/'
1584 };
1585 while (CurPtr+16 <= BufferEnd &&
1586 !vec_any_eq(*(vector unsigned char*)CurPtr, Slashes))
1587 CurPtr += 16;
Mike Stump1eb44332009-09-09 15:08:12 +00001588#else
Reid Spencer5f016e22007-07-11 17:01:13 +00001589 // Scan for '/' quickly. Many block comments are very large.
1590 while (CurPtr[0] != '/' &&
1591 CurPtr[1] != '/' &&
1592 CurPtr[2] != '/' &&
1593 CurPtr[3] != '/' &&
1594 CurPtr+4 < BufferEnd) {
1595 CurPtr += 4;
1596 }
1597#endif
Mike Stump1eb44332009-09-09 15:08:12 +00001598
Reid Spencer5f016e22007-07-11 17:01:13 +00001599 // It has to be one of the bytes scanned, increment to it and read one.
1600 C = *CurPtr++;
1601 }
Mike Stump1eb44332009-09-09 15:08:12 +00001602
Reid Spencer5f016e22007-07-11 17:01:13 +00001603 // Loop to scan the remainder.
1604 while (C != '/' && C != '\0')
1605 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00001606
Reid Spencer5f016e22007-07-11 17:01:13 +00001607 FoundSlash:
1608 if (C == '/') {
1609 if (CurPtr[-2] == '*') // We found the final */. We're done!
1610 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001611
Reid Spencer5f016e22007-07-11 17:01:13 +00001612 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
1613 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
1614 // We found the final */, though it had an escaped newline between the
1615 // * and /. We're done!
1616 break;
1617 }
1618 }
1619 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
1620 // If this is a /* inside of the comment, emit a warning. Don't do this
1621 // if this is a /*/, which will end the comment. This misses cases with
1622 // embedded escaped newlines, but oh well.
Chris Lattner74d15df2008-11-22 02:02:22 +00001623 if (!isLexingRawMode())
1624 Diag(CurPtr-1, diag::warn_nested_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001625 }
1626 } else if (C == 0 && CurPtr == BufferEnd+1) {
Douglas Gregor55817af2010-08-25 17:04:25 +00001627 if (PP && PP->isCodeCompletionFile(FileLoc))
1628 PP->CodeCompleteNaturalLanguage();
1629 else if (!isLexingRawMode())
Chris Lattner74d15df2008-11-22 02:02:22 +00001630 Diag(BufferPtr, diag::err_unterminated_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001631 // Note: the user probably forgot a */. We could continue immediately
1632 // after the /*, but this would involve lexing a lot of what really is the
1633 // comment, which surely would confuse the parser.
Chris Lattner31f0eca2008-10-12 04:19:49 +00001634 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001635
Chris Lattner31f0eca2008-10-12 04:19:49 +00001636 // KeepWhitespaceMode should return this broken comment as a token. Since
1637 // it isn't a well formed comment, just return it as an 'unknown' token.
1638 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001639 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner31f0eca2008-10-12 04:19:49 +00001640 return true;
1641 }
Mike Stump1eb44332009-09-09 15:08:12 +00001642
Chris Lattner31f0eca2008-10-12 04:19:49 +00001643 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001644 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001645 }
1646 C = *CurPtr++;
1647 }
Mike Stump1eb44332009-09-09 15:08:12 +00001648
Chris Lattner3d0ad582010-02-03 21:06:21 +00001649 // Notify comment handlers about the comment unless we're in a #if 0 block.
1650 if (PP && !isLexingRawMode() &&
1651 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
1652 getSourceLocation(CurPtr)))) {
Chris Lattner046c2272010-01-18 22:35:47 +00001653 BufferPtr = CurPtr;
1654 return true; // A token has to be returned.
1655 }
Douglas Gregor2e222532009-07-02 17:08:52 +00001656
Reid Spencer5f016e22007-07-11 17:01:13 +00001657 // If we are returning comments as tokens, return this comment as a token.
Chris Lattnerfa95a012008-10-12 03:22:02 +00001658 if (inKeepCommentMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001659 FormTokenWithChars(Result, CurPtr, tok::comment);
Chris Lattner2d381892008-10-12 04:15:42 +00001660 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001661 }
1662
1663 // It is common for the tokens immediately after a /**/ comment to be
1664 // whitespace. Instead of going through the big switch, handle it
Chris Lattnerd88dc482008-10-12 04:05:48 +00001665 // efficiently now. This is safe even in KeepWhitespaceMode because we would
1666 // have already returned above with the comment as a token.
Reid Spencer5f016e22007-07-11 17:01:13 +00001667 if (isHorizontalWhitespace(*CurPtr)) {
Chris Lattnerd2177732007-07-20 16:59:19 +00001668 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001669 SkipWhitespace(Result, CurPtr+1);
Chris Lattner2d381892008-10-12 04:15:42 +00001670 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001671 }
1672
1673 // Otherwise, just return so that the next character will be lexed as a token.
1674 BufferPtr = CurPtr;
Chris Lattnerd2177732007-07-20 16:59:19 +00001675 Result.setFlag(Token::LeadingSpace);
Chris Lattner2d381892008-10-12 04:15:42 +00001676 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001677}
1678
1679//===----------------------------------------------------------------------===//
1680// Primary Lexing Entry Points
1681//===----------------------------------------------------------------------===//
1682
Reid Spencer5f016e22007-07-11 17:01:13 +00001683/// ReadToEndOfLine - Read the rest of the current preprocessor line as an
1684/// uninterpreted string. This switches the lexer out of directive mode.
1685std::string Lexer::ReadToEndOfLine() {
1686 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
1687 "Must be in a preprocessing directive!");
1688 std::string Result;
Chris Lattnerd2177732007-07-20 16:59:19 +00001689 Token Tmp;
Reid Spencer5f016e22007-07-11 17:01:13 +00001690
1691 // CurPtr - Cache BufferPtr in an automatic variable.
1692 const char *CurPtr = BufferPtr;
1693 while (1) {
1694 char Char = getAndAdvanceChar(CurPtr, Tmp);
1695 switch (Char) {
1696 default:
1697 Result += Char;
1698 break;
1699 case 0: // Null.
1700 // Found end of file?
1701 if (CurPtr-1 != BufferEnd) {
1702 // Nope, normal character, continue.
1703 Result += Char;
1704 break;
1705 }
1706 // FALL THROUGH.
1707 case '\r':
1708 case '\n':
1709 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
1710 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
1711 BufferPtr = CurPtr-1;
Mike Stump1eb44332009-09-09 15:08:12 +00001712
Reid Spencer5f016e22007-07-11 17:01:13 +00001713 // Next, lex the character, which should handle the EOM transition.
1714 Lex(Tmp);
Douglas Gregor55817af2010-08-25 17:04:25 +00001715 if (Tmp.is(tok::code_completion)) {
1716 if (PP && PP->getCodeCompletionHandler())
1717 PP->getCodeCompletionHandler()->CodeCompleteNaturalLanguage();
1718 Lex(Tmp);
1719 }
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001720 assert(Tmp.is(tok::eom) && "Unexpected token!");
Mike Stump1eb44332009-09-09 15:08:12 +00001721
Reid Spencer5f016e22007-07-11 17:01:13 +00001722 // Finally, we're done, return the string we found.
1723 return Result;
1724 }
1725 }
1726}
1727
1728/// LexEndOfFile - CurPtr points to the end of this file. Handle this
1729/// condition, reporting diagnostics and handling other edge cases as required.
1730/// This returns true if Result contains a token, false if PP.Lex should be
1731/// called again.
Chris Lattnerd2177732007-07-20 16:59:19 +00001732bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
Douglas Gregorf44e8542010-08-24 19:08:16 +00001733 // Check if we are performing code completion.
1734 if (PP && PP->isCodeCompletionFile(FileLoc)) {
1735 // We're at the end of the file, but we've been asked to consider the
1736 // end of the file to be a code-completion token. Return the
1737 // code-completion token.
1738 Result.startToken();
1739 FormTokenWithChars(Result, CurPtr, tok::code_completion);
1740
1741 // Only do the eof -> code_completion translation once.
1742 PP->SetCodeCompletionPoint(0, 0, 0);
1743
1744 // Silence any diagnostics that occur once we hit the code-completion point.
1745 PP->getDiagnostics().setSuppressAllDiagnostics(true);
1746 return true;
1747 }
1748
Reid Spencer5f016e22007-07-11 17:01:13 +00001749 // If we hit the end of the file while parsing a preprocessor directive,
1750 // end the preprocessor directive first. The next token returned will
1751 // then be the end of file.
1752 if (ParsingPreprocessorDirective) {
1753 // Done parsing the "line".
1754 ParsingPreprocessorDirective = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001755 // Update the location of token as well as BufferPtr.
Chris Lattner9e6293d2008-10-12 04:51:35 +00001756 FormTokenWithChars(Result, CurPtr, tok::eom);
Mike Stump1eb44332009-09-09 15:08:12 +00001757
Reid Spencer5f016e22007-07-11 17:01:13 +00001758 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattnerf744d132008-10-12 03:27:19 +00001759 SetCommentRetentionState(PP->getCommentRetentionState());
Reid Spencer5f016e22007-07-11 17:01:13 +00001760 return true; // Have a token.
Mike Stump1eb44332009-09-09 15:08:12 +00001761 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00001762
Reid Spencer5f016e22007-07-11 17:01:13 +00001763 // If we are in raw mode, return this event as an EOF token. Let the caller
1764 // that put us in raw mode handle the event.
Chris Lattner74d15df2008-11-22 02:02:22 +00001765 if (isLexingRawMode()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001766 Result.startToken();
1767 BufferPtr = BufferEnd;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001768 FormTokenWithChars(Result, BufferEnd, tok::eof);
Reid Spencer5f016e22007-07-11 17:01:13 +00001769 return true;
1770 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00001771
Douglas Gregorf44e8542010-08-24 19:08:16 +00001772 // Issue diagnostics for unterminated #if and missing newline.
1773
Reid Spencer5f016e22007-07-11 17:01:13 +00001774 // If we are in a #if directive, emit an error.
1775 while (!ConditionalStack.empty()) {
Douglas Gregor2d474ba2010-08-12 17:04:55 +00001776 if (!PP->isCodeCompletionFile(FileLoc))
1777 PP->Diag(ConditionalStack.back().IfLoc,
1778 diag::err_pp_unterminated_conditional);
Reid Spencer5f016e22007-07-11 17:01:13 +00001779 ConditionalStack.pop_back();
1780 }
Mike Stump1eb44332009-09-09 15:08:12 +00001781
Chris Lattnerb25e5d72008-04-12 05:54:25 +00001782 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
1783 // a pedwarn.
1784 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r'))
Mike Stump20d0ee52009-04-02 02:29:42 +00001785 Diag(BufferEnd, diag::ext_no_newline_eof)
Douglas Gregor849b2432010-03-31 17:46:05 +00001786 << FixItHint::CreateInsertion(getSourceLocation(BufferEnd), "\n");
Mike Stump1eb44332009-09-09 15:08:12 +00001787
Reid Spencer5f016e22007-07-11 17:01:13 +00001788 BufferPtr = CurPtr;
1789
1790 // Finally, let the preprocessor handle this.
Chris Lattner168ae2d2007-10-17 20:41:00 +00001791 return PP->HandleEndOfFile(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001792}
1793
1794/// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
1795/// the specified lexer will return a tok::l_paren token, 0 if it is something
1796/// else and 2 if there are no more tokens in the buffer controlled by the
1797/// lexer.
1798unsigned Lexer::isNextPPTokenLParen() {
1799 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
Mike Stump1eb44332009-09-09 15:08:12 +00001800
Reid Spencer5f016e22007-07-11 17:01:13 +00001801 // Switch to 'skipping' mode. This will ensure that we can lex a token
1802 // without emitting diagnostics, disables macro expansion, and will cause EOF
1803 // to return an EOF token instead of popping the include stack.
1804 LexingRawMode = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001805
Reid Spencer5f016e22007-07-11 17:01:13 +00001806 // Save state that can be changed while lexing so that we can restore it.
1807 const char *TmpBufferPtr = BufferPtr;
Chris Lattnera864cf72009-04-24 07:15:46 +00001808 bool inPPDirectiveMode = ParsingPreprocessorDirective;
Mike Stump1eb44332009-09-09 15:08:12 +00001809
Chris Lattnerd2177732007-07-20 16:59:19 +00001810 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001811 Tok.startToken();
1812 LexTokenInternal(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001813
Reid Spencer5f016e22007-07-11 17:01:13 +00001814 // Restore state that may have changed.
1815 BufferPtr = TmpBufferPtr;
Chris Lattnera864cf72009-04-24 07:15:46 +00001816 ParsingPreprocessorDirective = inPPDirectiveMode;
Mike Stump1eb44332009-09-09 15:08:12 +00001817
Reid Spencer5f016e22007-07-11 17:01:13 +00001818 // Restore the lexer back to non-skipping mode.
1819 LexingRawMode = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001820
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001821 if (Tok.is(tok::eof))
Reid Spencer5f016e22007-07-11 17:01:13 +00001822 return 2;
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001823 return Tok.is(tok::l_paren);
Reid Spencer5f016e22007-07-11 17:01:13 +00001824}
1825
Chris Lattner34f349d2009-12-14 06:16:57 +00001826/// FindConflictEnd - Find the end of a version control conflict marker.
1827static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd) {
1828 llvm::StringRef RestOfBuffer(CurPtr+7, BufferEnd-CurPtr-7);
1829 size_t Pos = RestOfBuffer.find(">>>>>>>");
1830 while (Pos != llvm::StringRef::npos) {
1831 // Must occur at start of line.
1832 if (RestOfBuffer[Pos-1] != '\r' &&
1833 RestOfBuffer[Pos-1] != '\n') {
1834 RestOfBuffer = RestOfBuffer.substr(Pos+7);
Chris Lattner3d488992010-05-17 20:27:25 +00001835 Pos = RestOfBuffer.find(">>>>>>>");
Chris Lattner34f349d2009-12-14 06:16:57 +00001836 continue;
1837 }
1838 return RestOfBuffer.data()+Pos;
1839 }
1840 return 0;
1841}
1842
1843/// IsStartOfConflictMarker - If the specified pointer is the start of a version
1844/// control conflict marker like '<<<<<<<', recognize it as such, emit an error
1845/// and recover nicely. This returns true if it is a conflict marker and false
1846/// if not.
1847bool Lexer::IsStartOfConflictMarker(const char *CurPtr) {
1848 // Only a conflict marker if it starts at the beginning of a line.
1849 if (CurPtr != BufferStart &&
1850 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
1851 return false;
1852
1853 // Check to see if we have <<<<<<<.
1854 if (BufferEnd-CurPtr < 8 ||
1855 llvm::StringRef(CurPtr, 7) != "<<<<<<<")
1856 return false;
1857
1858 // If we have a situation where we don't care about conflict markers, ignore
1859 // it.
1860 if (IsInConflictMarker || isLexingRawMode())
1861 return false;
1862
1863 // Check to see if there is a >>>>>>> somewhere in the buffer at the start of
1864 // a line to terminate this conflict marker.
Chris Lattner3d488992010-05-17 20:27:25 +00001865 if (FindConflictEnd(CurPtr, BufferEnd)) {
Chris Lattner34f349d2009-12-14 06:16:57 +00001866 // We found a match. We are really in a conflict marker.
1867 // Diagnose this, and ignore to the end of line.
1868 Diag(CurPtr, diag::err_conflict_marker);
1869 IsInConflictMarker = true;
1870
1871 // Skip ahead to the end of line. We know this exists because the
1872 // end-of-conflict marker starts with \r or \n.
1873 while (*CurPtr != '\r' && *CurPtr != '\n') {
1874 assert(CurPtr != BufferEnd && "Didn't find end of line");
1875 ++CurPtr;
1876 }
1877 BufferPtr = CurPtr;
1878 return true;
1879 }
1880
1881 // No end of conflict marker found.
1882 return false;
1883}
1884
1885
1886/// HandleEndOfConflictMarker - If this is a '=======' or '|||||||' or '>>>>>>>'
1887/// marker, then it is the end of a conflict marker. Handle it by ignoring up
1888/// until the end of the line. This returns true if it is a conflict marker and
1889/// false if not.
1890bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) {
1891 // Only a conflict marker if it starts at the beginning of a line.
1892 if (CurPtr != BufferStart &&
1893 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
1894 return false;
1895
1896 // If we have a situation where we don't care about conflict markers, ignore
1897 // it.
1898 if (!IsInConflictMarker || isLexingRawMode())
1899 return false;
1900
1901 // Check to see if we have the marker (7 characters in a row).
1902 for (unsigned i = 1; i != 7; ++i)
1903 if (CurPtr[i] != CurPtr[0])
1904 return false;
1905
1906 // If we do have it, search for the end of the conflict marker. This could
1907 // fail if it got skipped with a '#if 0' or something. Note that CurPtr might
1908 // be the end of conflict marker.
1909 if (const char *End = FindConflictEnd(CurPtr, BufferEnd)) {
1910 CurPtr = End;
1911
1912 // Skip ahead to the end of line.
1913 while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n')
1914 ++CurPtr;
1915
1916 BufferPtr = CurPtr;
1917
1918 // No longer in the conflict marker.
1919 IsInConflictMarker = false;
1920 return true;
1921 }
1922
1923 return false;
1924}
1925
Reid Spencer5f016e22007-07-11 17:01:13 +00001926
1927/// LexTokenInternal - This implements a simple C family lexer. It is an
1928/// extremely performance critical piece of code. This assumes that the buffer
Chris Lattnerefb173d2009-07-07 05:05:42 +00001929/// has a null character at the end of the file. This returns a preprocessing
1930/// token, not a normal token, as such, it is an internal interface. It assumes
1931/// that the Flags of result have been cleared before calling this.
Chris Lattnerd2177732007-07-20 16:59:19 +00001932void Lexer::LexTokenInternal(Token &Result) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001933LexNextToken:
1934 // New token, can't need cleaning yet.
Chris Lattnerd2177732007-07-20 16:59:19 +00001935 Result.clearFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00001936 Result.setIdentifierInfo(0);
Mike Stump1eb44332009-09-09 15:08:12 +00001937
Reid Spencer5f016e22007-07-11 17:01:13 +00001938 // CurPtr - Cache BufferPtr in an automatic variable.
1939 const char *CurPtr = BufferPtr;
1940
1941 // Small amounts of horizontal whitespace is very common between tokens.
1942 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
1943 ++CurPtr;
1944 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
1945 ++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001946
Chris Lattnerd88dc482008-10-12 04:05:48 +00001947 // If we are keeping whitespace and other tokens, just return what we just
1948 // skipped. The next lexer invocation will return the token after the
1949 // whitespace.
1950 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001951 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd88dc482008-10-12 04:05:48 +00001952 return;
1953 }
Mike Stump1eb44332009-09-09 15:08:12 +00001954
Reid Spencer5f016e22007-07-11 17:01:13 +00001955 BufferPtr = CurPtr;
Chris Lattnerd2177732007-07-20 16:59:19 +00001956 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001957 }
Mike Stump1eb44332009-09-09 15:08:12 +00001958
Reid Spencer5f016e22007-07-11 17:01:13 +00001959 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
Mike Stump1eb44332009-09-09 15:08:12 +00001960
Reid Spencer5f016e22007-07-11 17:01:13 +00001961 // Read a character, advancing over it.
1962 char Char = getAndAdvanceChar(CurPtr, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001963 tok::TokenKind Kind;
Mike Stump1eb44332009-09-09 15:08:12 +00001964
Reid Spencer5f016e22007-07-11 17:01:13 +00001965 switch (Char) {
1966 case 0: // Null.
1967 // Found end of file?
1968 if (CurPtr-1 == BufferEnd) {
1969 // Read the PP instance variable into an automatic variable, because
1970 // LexEndOfFile will often delete 'this'.
Chris Lattner168ae2d2007-10-17 20:41:00 +00001971 Preprocessor *PPCache = PP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001972 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
1973 return; // Got a token to return.
Chris Lattner168ae2d2007-10-17 20:41:00 +00001974 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
1975 return PPCache->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001976 }
Mike Stump1eb44332009-09-09 15:08:12 +00001977
Chris Lattner74d15df2008-11-22 02:02:22 +00001978 if (!isLexingRawMode())
1979 Diag(CurPtr-1, diag::null_in_file);
Chris Lattnerd2177732007-07-20 16:59:19 +00001980 Result.setFlag(Token::LeadingSpace);
Chris Lattnerd88dc482008-10-12 04:05:48 +00001981 if (SkipWhitespace(Result, CurPtr))
1982 return; // KeepWhitespaceMode
Mike Stump1eb44332009-09-09 15:08:12 +00001983
Reid Spencer5f016e22007-07-11 17:01:13 +00001984 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattnera2bf1052009-12-17 05:29:40 +00001985
1986 case 26: // DOS & CP/M EOF: "^Z".
1987 // If we're in Microsoft extensions mode, treat this as end of file.
1988 if (Features.Microsoft) {
1989 // Read the PP instance variable into an automatic variable, because
1990 // LexEndOfFile will often delete 'this'.
1991 Preprocessor *PPCache = PP;
1992 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
1993 return; // Got a token to return.
1994 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
1995 return PPCache->Lex(Result);
1996 }
1997 // If Microsoft extensions are disabled, this is just random garbage.
1998 Kind = tok::unknown;
1999 break;
2000
Reid Spencer5f016e22007-07-11 17:01:13 +00002001 case '\n':
2002 case '\r':
2003 // If we are inside a preprocessor directive and we see the end of line,
2004 // we know we are done with the directive, so return an EOM token.
2005 if (ParsingPreprocessorDirective) {
2006 // Done parsing the "line".
2007 ParsingPreprocessorDirective = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002008
Reid Spencer5f016e22007-07-11 17:01:13 +00002009 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattnerf744d132008-10-12 03:27:19 +00002010 SetCommentRetentionState(PP->getCommentRetentionState());
Mike Stump1eb44332009-09-09 15:08:12 +00002011
Reid Spencer5f016e22007-07-11 17:01:13 +00002012 // Since we consumed a newline, we are back at the start of a line.
2013 IsAtStartOfLine = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002014
Chris Lattner9e6293d2008-10-12 04:51:35 +00002015 Kind = tok::eom;
Reid Spencer5f016e22007-07-11 17:01:13 +00002016 break;
2017 }
2018 // The returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00002019 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00002020 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00002021 Result.clearFlag(Token::LeadingSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00002022
Chris Lattnerd88dc482008-10-12 04:05:48 +00002023 if (SkipWhitespace(Result, CurPtr))
2024 return; // KeepWhitespaceMode
Reid Spencer5f016e22007-07-11 17:01:13 +00002025 goto LexNextToken; // GCC isn't tail call eliminating.
2026 case ' ':
2027 case '\t':
2028 case '\f':
2029 case '\v':
Chris Lattner8133cfc2007-07-22 06:29:05 +00002030 SkipHorizontalWhitespace:
Chris Lattnerd2177732007-07-20 16:59:19 +00002031 Result.setFlag(Token::LeadingSpace);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002032 if (SkipWhitespace(Result, CurPtr))
2033 return; // KeepWhitespaceMode
Chris Lattner8133cfc2007-07-22 06:29:05 +00002034
2035 SkipIgnoredUnits:
2036 CurPtr = BufferPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002037
Chris Lattner8133cfc2007-07-22 06:29:05 +00002038 // If the next token is obviously a // or /* */ comment, skip it efficiently
2039 // too (without going through the big switch stmt).
Chris Lattner8402c732009-01-16 22:39:25 +00002040 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
2041 Features.BCPLComment) {
Chris Lattner046c2272010-01-18 22:35:47 +00002042 if (SkipBCPLComment(Result, CurPtr+2))
2043 return; // There is a token to return.
Chris Lattner8133cfc2007-07-22 06:29:05 +00002044 goto SkipIgnoredUnits;
Chris Lattnerfa95a012008-10-12 03:22:02 +00002045 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
Chris Lattner046c2272010-01-18 22:35:47 +00002046 if (SkipBlockComment(Result, CurPtr+2))
2047 return; // There is a token to return.
Chris Lattner8133cfc2007-07-22 06:29:05 +00002048 goto SkipIgnoredUnits;
2049 } else if (isHorizontalWhitespace(*CurPtr)) {
2050 goto SkipHorizontalWhitespace;
2051 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002052 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattnera2bf1052009-12-17 05:29:40 +00002053
Chris Lattner3a570772008-01-03 17:58:54 +00002054 // C99 6.4.4.1: Integer Constants.
2055 // C99 6.4.4.2: Floating Constants.
2056 case '0': case '1': case '2': case '3': case '4':
2057 case '5': case '6': case '7': case '8': case '9':
2058 // Notify MIOpt that we read a non-whitespace/non-comment token.
2059 MIOpt.ReadToken();
2060 return LexNumericConstant(Result, CurPtr);
Mike Stump1eb44332009-09-09 15:08:12 +00002061
Chris Lattner3a570772008-01-03 17:58:54 +00002062 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
Reid Spencer5f016e22007-07-11 17:01:13 +00002063 // Notify MIOpt that we read a non-whitespace/non-comment token.
2064 MIOpt.ReadToken();
2065 Char = getCharAndSize(CurPtr, SizeTmp);
2066
2067 // Wide string literal.
2068 if (Char == '"')
2069 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2070 true);
2071
2072 // Wide character constant.
2073 if (Char == '\'')
2074 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
2075 // FALL THROUGH, treating L like the start of an identifier.
Mike Stump1eb44332009-09-09 15:08:12 +00002076
Reid Spencer5f016e22007-07-11 17:01:13 +00002077 // C99 6.4.2: Identifiers.
2078 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
2079 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
2080 case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U':
2081 case 'V': case 'W': case 'X': case 'Y': case 'Z':
2082 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
2083 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
2084 case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u':
2085 case 'v': case 'w': case 'x': case 'y': case 'z':
2086 case '_':
2087 // Notify MIOpt that we read a non-whitespace/non-comment token.
2088 MIOpt.ReadToken();
2089 return LexIdentifier(Result, CurPtr);
Chris Lattner3a570772008-01-03 17:58:54 +00002090
2091 case '$': // $ in identifiers.
2092 if (Features.DollarIdents) {
Chris Lattner74d15df2008-11-22 02:02:22 +00002093 if (!isLexingRawMode())
2094 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
Chris Lattner3a570772008-01-03 17:58:54 +00002095 // Notify MIOpt that we read a non-whitespace/non-comment token.
2096 MIOpt.ReadToken();
2097 return LexIdentifier(Result, CurPtr);
2098 }
Mike Stump1eb44332009-09-09 15:08:12 +00002099
Chris Lattner9e6293d2008-10-12 04:51:35 +00002100 Kind = tok::unknown;
Chris Lattner3a570772008-01-03 17:58:54 +00002101 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002102
Reid Spencer5f016e22007-07-11 17:01:13 +00002103 // C99 6.4.4: Character Constants.
2104 case '\'':
2105 // Notify MIOpt that we read a non-whitespace/non-comment token.
2106 MIOpt.ReadToken();
2107 return LexCharConstant(Result, CurPtr);
2108
2109 // C99 6.4.5: String Literals.
2110 case '"':
2111 // Notify MIOpt that we read a non-whitespace/non-comment token.
2112 MIOpt.ReadToken();
2113 return LexStringLiteral(Result, CurPtr, false);
2114
2115 // C99 6.4.6: Punctuators.
2116 case '?':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002117 Kind = tok::question;
Reid Spencer5f016e22007-07-11 17:01:13 +00002118 break;
2119 case '[':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002120 Kind = tok::l_square;
Reid Spencer5f016e22007-07-11 17:01:13 +00002121 break;
2122 case ']':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002123 Kind = tok::r_square;
Reid Spencer5f016e22007-07-11 17:01:13 +00002124 break;
2125 case '(':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002126 Kind = tok::l_paren;
Reid Spencer5f016e22007-07-11 17:01:13 +00002127 break;
2128 case ')':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002129 Kind = tok::r_paren;
Reid Spencer5f016e22007-07-11 17:01:13 +00002130 break;
2131 case '{':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002132 Kind = tok::l_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00002133 break;
2134 case '}':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002135 Kind = tok::r_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00002136 break;
2137 case '.':
2138 Char = getCharAndSize(CurPtr, SizeTmp);
2139 if (Char >= '0' && Char <= '9') {
2140 // Notify MIOpt that we read a non-whitespace/non-comment token.
2141 MIOpt.ReadToken();
2142
2143 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
2144 } else if (Features.CPlusPlus && Char == '*') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002145 Kind = tok::periodstar;
Reid Spencer5f016e22007-07-11 17:01:13 +00002146 CurPtr += SizeTmp;
2147 } else if (Char == '.' &&
2148 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002149 Kind = tok::ellipsis;
Reid Spencer5f016e22007-07-11 17:01:13 +00002150 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2151 SizeTmp2, Result);
2152 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002153 Kind = tok::period;
Reid Spencer5f016e22007-07-11 17:01:13 +00002154 }
2155 break;
2156 case '&':
2157 Char = getCharAndSize(CurPtr, SizeTmp);
2158 if (Char == '&') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002159 Kind = tok::ampamp;
Reid Spencer5f016e22007-07-11 17:01:13 +00002160 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2161 } else if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002162 Kind = tok::ampequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002163 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2164 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002165 Kind = tok::amp;
Reid Spencer5f016e22007-07-11 17:01:13 +00002166 }
2167 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002168 case '*':
Reid Spencer5f016e22007-07-11 17:01:13 +00002169 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002170 Kind = tok::starequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002171 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2172 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002173 Kind = tok::star;
Reid Spencer5f016e22007-07-11 17:01:13 +00002174 }
2175 break;
2176 case '+':
2177 Char = getCharAndSize(CurPtr, SizeTmp);
2178 if (Char == '+') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002179 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002180 Kind = tok::plusplus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002181 } else if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002182 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002183 Kind = tok::plusequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002184 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002185 Kind = tok::plus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002186 }
2187 break;
2188 case '-':
2189 Char = getCharAndSize(CurPtr, SizeTmp);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002190 if (Char == '-') { // --
Reid Spencer5f016e22007-07-11 17:01:13 +00002191 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002192 Kind = tok::minusminus;
Mike Stump1eb44332009-09-09 15:08:12 +00002193 } else if (Char == '>' && Features.CPlusPlus &&
Chris Lattner9e6293d2008-10-12 04:51:35 +00002194 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
Reid Spencer5f016e22007-07-11 17:01:13 +00002195 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2196 SizeTmp2, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002197 Kind = tok::arrowstar;
2198 } else if (Char == '>') { // ->
Reid Spencer5f016e22007-07-11 17:01:13 +00002199 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002200 Kind = tok::arrow;
2201 } else if (Char == '=') { // -=
Reid Spencer5f016e22007-07-11 17:01:13 +00002202 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002203 Kind = tok::minusequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002204 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002205 Kind = tok::minus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002206 }
2207 break;
2208 case '~':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002209 Kind = tok::tilde;
Reid Spencer5f016e22007-07-11 17:01:13 +00002210 break;
2211 case '!':
2212 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002213 Kind = tok::exclaimequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002214 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2215 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002216 Kind = tok::exclaim;
Reid Spencer5f016e22007-07-11 17:01:13 +00002217 }
2218 break;
2219 case '/':
2220 // 6.4.9: Comments
2221 Char = getCharAndSize(CurPtr, SizeTmp);
2222 if (Char == '/') { // BCPL comment.
Chris Lattner8402c732009-01-16 22:39:25 +00002223 // Even if BCPL comments are disabled (e.g. in C89 mode), we generally
2224 // want to lex this as a comment. There is one problem with this though,
2225 // that in one particular corner case, this can change the behavior of the
2226 // resultant program. For example, In "foo //**/ bar", C89 would lex
2227 // this as "foo / bar" and langauges with BCPL comments would lex it as
2228 // "foo". Check to see if the character after the second slash is a '*'.
2229 // If so, we will lex that as a "/" instead of the start of a comment.
2230 if (Features.BCPLComment ||
2231 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*') {
2232 if (SkipBCPLComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattner046c2272010-01-18 22:35:47 +00002233 return; // There is a token to return.
Mike Stump1eb44332009-09-09 15:08:12 +00002234
Chris Lattner8402c732009-01-16 22:39:25 +00002235 // It is common for the tokens immediately after a // comment to be
2236 // whitespace (indentation for the next line). Instead of going through
2237 // the big switch, handle it efficiently now.
2238 goto SkipIgnoredUnits;
2239 }
2240 }
Mike Stump1eb44332009-09-09 15:08:12 +00002241
Chris Lattner8402c732009-01-16 22:39:25 +00002242 if (Char == '*') { // /**/ comment.
Reid Spencer5f016e22007-07-11 17:01:13 +00002243 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattner046c2272010-01-18 22:35:47 +00002244 return; // There is a token to return.
Chris Lattner2d381892008-10-12 04:15:42 +00002245 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattner8402c732009-01-16 22:39:25 +00002246 }
Mike Stump1eb44332009-09-09 15:08:12 +00002247
Chris Lattner8402c732009-01-16 22:39:25 +00002248 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002249 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002250 Kind = tok::slashequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002251 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002252 Kind = tok::slash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002253 }
2254 break;
2255 case '%':
2256 Char = getCharAndSize(CurPtr, SizeTmp);
2257 if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002258 Kind = tok::percentequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002259 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2260 } else if (Features.Digraphs && Char == '>') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002261 Kind = tok::r_brace; // '%>' -> '}'
Reid Spencer5f016e22007-07-11 17:01:13 +00002262 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2263 } else if (Features.Digraphs && Char == ':') {
2264 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2265 Char = getCharAndSize(CurPtr, SizeTmp);
2266 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002267 Kind = tok::hashhash; // '%:%:' -> '##'
Reid Spencer5f016e22007-07-11 17:01:13 +00002268 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2269 SizeTmp2, Result);
2270 } else if (Char == '@' && Features.Microsoft) { // %:@ -> #@ -> Charize
Reid Spencer5f016e22007-07-11 17:01:13 +00002271 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner74d15df2008-11-22 02:02:22 +00002272 if (!isLexingRawMode())
2273 Diag(BufferPtr, diag::charize_microsoft_ext);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002274 Kind = tok::hashat;
Chris Lattnere91e9322009-03-18 20:58:27 +00002275 } else { // '%:' -> '#'
Reid Spencer5f016e22007-07-11 17:01:13 +00002276 // We parsed a # character. If this occurs at the start of the line,
2277 // it's actually the start of a preprocessing directive. Callback to
2278 // the preprocessor to handle it.
2279 // FIXME: -fpreprocessed mode??
Chris Lattner766703b2009-05-13 06:10:29 +00002280 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer) {
Chris Lattnere91e9322009-03-18 20:58:27 +00002281 FormTokenWithChars(Result, CurPtr, tok::hash);
Chris Lattner168ae2d2007-10-17 20:41:00 +00002282 PP->HandleDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00002283
Reid Spencer5f016e22007-07-11 17:01:13 +00002284 // As an optimization, if the preprocessor didn't switch lexers, tail
2285 // recurse.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002286 if (PP->isCurrentLexer(this)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002287 // Start a new token. If this is a #include or something, the PP may
2288 // want us starting at the beginning of the line again. If so, set
Chris Lattner515f43f2010-04-12 23:04:41 +00002289 // the StartOfLine flag and clear LeadingSpace.
Reid Spencer5f016e22007-07-11 17:01:13 +00002290 if (IsAtStartOfLine) {
Chris Lattnerd2177732007-07-20 16:59:19 +00002291 Result.setFlag(Token::StartOfLine);
Chris Lattner515f43f2010-04-12 23:04:41 +00002292 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002293 IsAtStartOfLine = false;
2294 }
2295 goto LexNextToken; // GCC isn't tail call eliminating.
2296 }
Mike Stump1eb44332009-09-09 15:08:12 +00002297
Chris Lattner168ae2d2007-10-17 20:41:00 +00002298 return PP->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002299 }
Mike Stump1eb44332009-09-09 15:08:12 +00002300
Chris Lattnere91e9322009-03-18 20:58:27 +00002301 Kind = tok::hash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002302 }
2303 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002304 Kind = tok::percent;
Reid Spencer5f016e22007-07-11 17:01:13 +00002305 }
2306 break;
2307 case '<':
2308 Char = getCharAndSize(CurPtr, SizeTmp);
2309 if (ParsingFilename) {
Chris Lattner9cb51ce2009-04-17 23:56:52 +00002310 return LexAngledStringLiteral(Result, CurPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +00002311 } else if (Char == '<') {
Chris Lattner34f349d2009-12-14 06:16:57 +00002312 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
2313 if (After == '=') {
2314 Kind = tok::lesslessequal;
2315 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2316 SizeTmp2, Result);
2317 } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) {
2318 // If this is actually a '<<<<<<<' version control conflict marker,
2319 // recognize it as such and recover nicely.
2320 goto LexNextToken;
2321 } else {
2322 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2323 Kind = tok::lessless;
2324 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002325 } else if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002326 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002327 Kind = tok::lessequal;
2328 } else if (Features.Digraphs && Char == ':') { // '<:' -> '['
Reid Spencer5f016e22007-07-11 17:01:13 +00002329 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002330 Kind = tok::l_square;
2331 } else if (Features.Digraphs && Char == '%') { // '<%' -> '{'
Reid Spencer5f016e22007-07-11 17:01:13 +00002332 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002333 Kind = tok::l_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00002334 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002335 Kind = tok::less;
Reid Spencer5f016e22007-07-11 17:01:13 +00002336 }
2337 break;
2338 case '>':
2339 Char = getCharAndSize(CurPtr, SizeTmp);
2340 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002341 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002342 Kind = tok::greaterequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002343 } else if (Char == '>') {
Chris Lattner34f349d2009-12-14 06:16:57 +00002344 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
2345 if (After == '=') {
2346 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2347 SizeTmp2, Result);
2348 Kind = tok::greatergreaterequal;
2349 } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) {
2350 // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
2351 goto LexNextToken;
2352 } else {
2353 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2354 Kind = tok::greatergreater;
2355 }
2356
Reid Spencer5f016e22007-07-11 17:01:13 +00002357 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002358 Kind = tok::greater;
Reid Spencer5f016e22007-07-11 17:01:13 +00002359 }
2360 break;
2361 case '^':
2362 Char = getCharAndSize(CurPtr, SizeTmp);
2363 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002364 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002365 Kind = tok::caretequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002366 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002367 Kind = tok::caret;
Reid Spencer5f016e22007-07-11 17:01:13 +00002368 }
2369 break;
2370 case '|':
2371 Char = getCharAndSize(CurPtr, SizeTmp);
2372 if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002373 Kind = tok::pipeequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002374 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2375 } else if (Char == '|') {
Chris Lattner34f349d2009-12-14 06:16:57 +00002376 // If this is '|||||||' and we're in a conflict marker, ignore it.
2377 if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
2378 goto LexNextToken;
Chris Lattner9e6293d2008-10-12 04:51:35 +00002379 Kind = tok::pipepipe;
Reid Spencer5f016e22007-07-11 17:01:13 +00002380 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2381 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002382 Kind = tok::pipe;
Reid Spencer5f016e22007-07-11 17:01:13 +00002383 }
2384 break;
2385 case ':':
2386 Char = getCharAndSize(CurPtr, SizeTmp);
2387 if (Features.Digraphs && Char == '>') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002388 Kind = tok::r_square; // ':>' -> ']'
Reid Spencer5f016e22007-07-11 17:01:13 +00002389 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2390 } else if (Features.CPlusPlus && Char == ':') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002391 Kind = tok::coloncolon;
Reid Spencer5f016e22007-07-11 17:01:13 +00002392 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump1eb44332009-09-09 15:08:12 +00002393 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002394 Kind = tok::colon;
Reid Spencer5f016e22007-07-11 17:01:13 +00002395 }
2396 break;
2397 case ';':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002398 Kind = tok::semi;
Reid Spencer5f016e22007-07-11 17:01:13 +00002399 break;
2400 case '=':
2401 Char = getCharAndSize(CurPtr, SizeTmp);
2402 if (Char == '=') {
Chris Lattner34f349d2009-12-14 06:16:57 +00002403 // If this is '=======' and we're in a conflict marker, ignore it.
2404 if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
2405 goto LexNextToken;
2406
Chris Lattner9e6293d2008-10-12 04:51:35 +00002407 Kind = tok::equalequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002408 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump1eb44332009-09-09 15:08:12 +00002409 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002410 Kind = tok::equal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002411 }
2412 break;
2413 case ',':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002414 Kind = tok::comma;
Reid Spencer5f016e22007-07-11 17:01:13 +00002415 break;
2416 case '#':
2417 Char = getCharAndSize(CurPtr, SizeTmp);
2418 if (Char == '#') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002419 Kind = tok::hashhash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002420 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2421 } else if (Char == '@' && Features.Microsoft) { // #@ -> Charize
Chris Lattner9e6293d2008-10-12 04:51:35 +00002422 Kind = tok::hashat;
Chris Lattner74d15df2008-11-22 02:02:22 +00002423 if (!isLexingRawMode())
2424 Diag(BufferPtr, diag::charize_microsoft_ext);
Reid Spencer5f016e22007-07-11 17:01:13 +00002425 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2426 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +00002427 // We parsed a # character. If this occurs at the start of the line,
2428 // it's actually the start of a preprocessing directive. Callback to
2429 // the preprocessor to handle it.
2430 // FIXME: -fpreprocessed mode??
Chris Lattner766703b2009-05-13 06:10:29 +00002431 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer) {
Chris Lattnere91e9322009-03-18 20:58:27 +00002432 FormTokenWithChars(Result, CurPtr, tok::hash);
Chris Lattner168ae2d2007-10-17 20:41:00 +00002433 PP->HandleDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00002434
Reid Spencer5f016e22007-07-11 17:01:13 +00002435 // As an optimization, if the preprocessor didn't switch lexers, tail
2436 // recurse.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002437 if (PP->isCurrentLexer(this)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002438 // Start a new token. If this is a #include or something, the PP may
2439 // want us starting at the beginning of the line again. If so, set
Chris Lattner515f43f2010-04-12 23:04:41 +00002440 // the StartOfLine flag and clear LeadingSpace.
Reid Spencer5f016e22007-07-11 17:01:13 +00002441 if (IsAtStartOfLine) {
Chris Lattnerd2177732007-07-20 16:59:19 +00002442 Result.setFlag(Token::StartOfLine);
Chris Lattner515f43f2010-04-12 23:04:41 +00002443 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002444 IsAtStartOfLine = false;
2445 }
2446 goto LexNextToken; // GCC isn't tail call eliminating.
2447 }
Chris Lattner168ae2d2007-10-17 20:41:00 +00002448 return PP->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002449 }
Mike Stump1eb44332009-09-09 15:08:12 +00002450
Chris Lattnere91e9322009-03-18 20:58:27 +00002451 Kind = tok::hash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002452 }
2453 break;
2454
Chris Lattner3a570772008-01-03 17:58:54 +00002455 case '@':
2456 // Objective C support.
2457 if (CurPtr[-1] == '@' && Features.ObjC1)
Chris Lattner9e6293d2008-10-12 04:51:35 +00002458 Kind = tok::at;
Chris Lattner3a570772008-01-03 17:58:54 +00002459 else
Chris Lattner9e6293d2008-10-12 04:51:35 +00002460 Kind = tok::unknown;
Chris Lattner3a570772008-01-03 17:58:54 +00002461 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002462
Reid Spencer5f016e22007-07-11 17:01:13 +00002463 case '\\':
2464 // FIXME: UCN's.
2465 // FALL THROUGH.
2466 default:
Chris Lattner9e6293d2008-10-12 04:51:35 +00002467 Kind = tok::unknown;
Reid Spencer5f016e22007-07-11 17:01:13 +00002468 break;
2469 }
Mike Stump1eb44332009-09-09 15:08:12 +00002470
Reid Spencer5f016e22007-07-11 17:01:13 +00002471 // Notify MIOpt that we read a non-whitespace/non-comment token.
2472 MIOpt.ReadToken();
2473
2474 // Update the location of token as well as BufferPtr.
Chris Lattner9e6293d2008-10-12 04:51:35 +00002475 FormTokenWithChars(Result, CurPtr, Kind);
Reid Spencer5f016e22007-07-11 17:01:13 +00002476}