blob: 4fd35be19c20b8c0ad5ed71ddf6c4660d31ec213 [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
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000215static bool isWhitespace(unsigned char c);
Reid Spencer5f016e22007-07-11 17:01:13 +0000216
Chris Lattner9a611942007-10-17 21:18:47 +0000217/// MeasureTokenLength - Relex the token at the specified location and return
218/// its length in bytes in the input file. If the token needs cleaning (e.g.
219/// includes a trigraph or an escaped newline) then this count includes bytes
220/// that are part of that.
221unsigned Lexer::MeasureTokenLength(SourceLocation Loc,
Chris Lattner2c78b872009-04-14 23:22:57 +0000222 const SourceManager &SM,
223 const LangOptions &LangOpts) {
Chris Lattner9a611942007-10-17 21:18:47 +0000224 // TODO: this could be special cased for common tokens like identifiers, ')',
225 // etc to make this faster, if it mattered. Just look at StrData[0] to handle
Mike Stump1eb44332009-09-09 15:08:12 +0000226 // all obviously single-char tokens. This could use
Chris Lattner9a611942007-10-17 21:18:47 +0000227 // Lexer::isObviouslySimpleCharacter for example to handle identifiers or
228 // something.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000229
230 // If this comes from a macro expansion, we really do want the macro name, not
231 // the token this macro expanded to.
Chris Lattner363fdc22009-01-26 22:24:27 +0000232 Loc = SM.getInstantiationLoc(Loc);
233 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +0000234 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000235 llvm::StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Douglas Gregorf715ca12010-03-16 00:06:06 +0000236 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +0000237 return 0;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000238
239 const char *StrData = Buffer.data()+LocInfo.second;
Chris Lattner83503942009-01-17 08:30:10 +0000240
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000241 if (isWhitespace(StrData[0]))
242 return 0;
243
Chris Lattner9a611942007-10-17 21:18:47 +0000244 // Create a lexer starting at the beginning of this token.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000245 Lexer TheLexer(Loc, LangOpts, Buffer.begin(), StrData, Buffer.end());
Chris Lattner39de7402009-10-14 15:04:18 +0000246 TheLexer.SetCommentRetentionState(true);
Chris Lattner9a611942007-10-17 21:18:47 +0000247 Token TheTok;
Chris Lattner590f0cc2008-10-12 01:15:46 +0000248 TheLexer.LexFromRawLexer(TheTok);
Chris Lattner9a611942007-10-17 21:18:47 +0000249 return TheTok.getLength();
250}
251
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000252SourceLocation Lexer::GetBeginningOfToken(SourceLocation Loc,
253 const SourceManager &SM,
254 const LangOptions &LangOpts) {
255 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
256 bool Invalid = false;
257 llvm::StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
258 if (Invalid)
259 return Loc;
260
261 // Back up from the current location until we hit the beginning of a line
262 // (or the buffer). We'll relex from that point.
263 const char *BufStart = Buffer.data();
264 const char *StrData = BufStart+LocInfo.second;
265 if (StrData[0] == '\n' || StrData[0] == '\r')
266 return Loc;
267
268 const char *LexStart = StrData;
269 while (LexStart != BufStart) {
270 if (LexStart[0] == '\n' || LexStart[0] == '\r') {
271 ++LexStart;
272 break;
273 }
274
275 --LexStart;
276 }
277
278 // Create a lexer starting at the beginning of this token.
279 SourceLocation LexerStartLoc = Loc.getFileLocWithOffset(-LocInfo.second);
280 Lexer TheLexer(LexerStartLoc, LangOpts, BufStart, LexStart, Buffer.end());
281 TheLexer.SetCommentRetentionState(true);
282
283 // Lex tokens until we find the token that contains the source location.
284 Token TheTok;
285 do {
286 TheLexer.LexFromRawLexer(TheTok);
287
288 if (TheLexer.getBufferLocation() > StrData) {
289 // Lexing this token has taken the lexer past the source location we're
290 // looking for. If the current token encompasses our source location,
291 // return the beginning of that token.
292 if (TheLexer.getBufferLocation() - TheTok.getLength() <= StrData)
293 return TheTok.getLocation();
294
295 // We ended up skipping over the source location entirely, which means
296 // that it points into whitespace. We're done here.
297 break;
298 }
299 } while (TheTok.getKind() != tok::eof);
300
301 // We've passed our source location; just return the original source location.
302 return Loc;
303}
304
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000305namespace {
306 enum PreambleDirectiveKind {
307 PDK_Skipped,
308 PDK_StartIf,
309 PDK_EndIf,
310 PDK_Unknown
311 };
312}
313
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000314std::pair<unsigned, bool>
Douglas Gregordf95a132010-08-09 20:45:32 +0000315Lexer::ComputePreamble(const llvm::MemoryBuffer *Buffer, unsigned MaxLines) {
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000316 // Create a lexer starting at the beginning of the file. Note that we use a
317 // "fake" file source location at offset 1 so that the lexer will track our
318 // position within the file.
319 const unsigned StartOffset = 1;
320 SourceLocation StartLoc = SourceLocation::getFromRawEncoding(StartOffset);
321 LangOptions LangOpts;
322 Lexer TheLexer(StartLoc, LangOpts, Buffer->getBufferStart(),
323 Buffer->getBufferStart(), Buffer->getBufferEnd());
324
325 bool InPreprocessorDirective = false;
326 Token TheTok;
327 Token IfStartTok;
328 unsigned IfCount = 0;
Douglas Gregordf95a132010-08-09 20:45:32 +0000329 unsigned Line = 0;
330
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000331 do {
332 TheLexer.LexFromRawLexer(TheTok);
333
334 if (InPreprocessorDirective) {
335 // If we've hit the end of the file, we're done.
336 if (TheTok.getKind() == tok::eof) {
337 InPreprocessorDirective = false;
338 break;
339 }
340
341 // If we haven't hit the end of the preprocessor directive, skip this
342 // token.
343 if (!TheTok.isAtStartOfLine())
344 continue;
345
346 // We've passed the end of the preprocessor directive, and will look
347 // at this token again below.
348 InPreprocessorDirective = false;
349 }
350
Douglas Gregordf95a132010-08-09 20:45:32 +0000351 // Keep track of the # of lines in the preamble.
352 if (TheTok.isAtStartOfLine()) {
353 ++Line;
354
355 // If we were asked to limit the number of lines in the preamble,
356 // and we're about to exceed that limit, we're done.
357 if (MaxLines && Line >= MaxLines)
358 break;
359 }
360
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000361 // Comments are okay; skip over them.
362 if (TheTok.getKind() == tok::comment)
363 continue;
364
365 if (TheTok.isAtStartOfLine() && TheTok.getKind() == tok::hash) {
366 // This is the start of a preprocessor directive.
367 Token HashTok = TheTok;
368 InPreprocessorDirective = true;
369
370 // Figure out which direective this is. Since we're lexing raw tokens,
371 // we don't have an identifier table available. Instead, just look at
372 // the raw identifier to recognize and categorize preprocessor directives.
373 TheLexer.LexFromRawLexer(TheTok);
374 if (TheTok.getKind() == tok::identifier && !TheTok.needsCleaning()) {
375 const char *IdStart = Buffer->getBufferStart()
376 + TheTok.getLocation().getRawEncoding() - 1;
377 llvm::StringRef Keyword(IdStart, TheTok.getLength());
378 PreambleDirectiveKind PDK
379 = llvm::StringSwitch<PreambleDirectiveKind>(Keyword)
380 .Case("include", PDK_Skipped)
381 .Case("__include_macros", PDK_Skipped)
382 .Case("define", PDK_Skipped)
383 .Case("undef", PDK_Skipped)
384 .Case("line", PDK_Skipped)
385 .Case("error", PDK_Skipped)
386 .Case("pragma", PDK_Skipped)
387 .Case("import", PDK_Skipped)
388 .Case("include_next", PDK_Skipped)
389 .Case("warning", PDK_Skipped)
390 .Case("ident", PDK_Skipped)
391 .Case("sccs", PDK_Skipped)
392 .Case("assert", PDK_Skipped)
393 .Case("unassert", PDK_Skipped)
394 .Case("if", PDK_StartIf)
395 .Case("ifdef", PDK_StartIf)
396 .Case("ifndef", PDK_StartIf)
397 .Case("elif", PDK_Skipped)
398 .Case("else", PDK_Skipped)
399 .Case("endif", PDK_EndIf)
400 .Default(PDK_Unknown);
401
402 switch (PDK) {
403 case PDK_Skipped:
404 continue;
405
406 case PDK_StartIf:
407 if (IfCount == 0)
408 IfStartTok = HashTok;
409
410 ++IfCount;
411 continue;
412
413 case PDK_EndIf:
414 // Mismatched #endif. The preamble ends here.
415 if (IfCount == 0)
416 break;
417
418 --IfCount;
419 continue;
420
421 case PDK_Unknown:
422 // We don't know what this directive is; stop at the '#'.
423 break;
424 }
425 }
426
427 // We only end up here if we didn't recognize the preprocessor
428 // directive or it was one that can't occur in the preamble at this
429 // point. Roll back the current token to the location of the '#'.
430 InPreprocessorDirective = false;
431 TheTok = HashTok;
432 }
433
Douglas Gregordf95a132010-08-09 20:45:32 +0000434 // We hit a token that we don't recognize as being in the
435 // "preprocessing only" part of the file, so we're no longer in
436 // the preamble.
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000437 break;
438 } while (true);
439
440 SourceLocation End = IfCount? IfStartTok.getLocation() : TheTok.getLocation();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000441 return std::make_pair(End.getRawEncoding() - StartLoc.getRawEncoding(),
442 IfCount? IfStartTok.isAtStartOfLine()
443 : TheTok.isAtStartOfLine());
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000444}
445
Reid Spencer5f016e22007-07-11 17:01:13 +0000446//===----------------------------------------------------------------------===//
447// Character information.
448//===----------------------------------------------------------------------===//
449
Reid Spencer5f016e22007-07-11 17:01:13 +0000450enum {
451 CHAR_HORZ_WS = 0x01, // ' ', '\t', '\f', '\v'. Note, no '\0'
452 CHAR_VERT_WS = 0x02, // '\r', '\n'
453 CHAR_LETTER = 0x04, // a-z,A-Z
454 CHAR_NUMBER = 0x08, // 0-9
455 CHAR_UNDER = 0x10, // _
456 CHAR_PERIOD = 0x20 // .
457};
458
Chris Lattner03b98662009-07-07 17:09:54 +0000459// Statically initialize CharInfo table based on ASCII character set
460// Reference: FreeBSD 7.2 /usr/share/misc/ascii
Chris Lattnera2bf1052009-12-17 05:29:40 +0000461static const unsigned char CharInfo[256] =
Chris Lattner03b98662009-07-07 17:09:54 +0000462{
463// 0 NUL 1 SOH 2 STX 3 ETX
464// 4 EOT 5 ENQ 6 ACK 7 BEL
465 0 , 0 , 0 , 0 ,
466 0 , 0 , 0 , 0 ,
467// 8 BS 9 HT 10 NL 11 VT
468//12 NP 13 CR 14 SO 15 SI
469 0 , CHAR_HORZ_WS, CHAR_VERT_WS, CHAR_HORZ_WS,
470 CHAR_HORZ_WS, CHAR_VERT_WS, 0 , 0 ,
471//16 DLE 17 DC1 18 DC2 19 DC3
472//20 DC4 21 NAK 22 SYN 23 ETB
473 0 , 0 , 0 , 0 ,
474 0 , 0 , 0 , 0 ,
475//24 CAN 25 EM 26 SUB 27 ESC
476//28 FS 29 GS 30 RS 31 US
477 0 , 0 , 0 , 0 ,
478 0 , 0 , 0 , 0 ,
479//32 SP 33 ! 34 " 35 #
480//36 $ 37 % 38 & 39 '
481 CHAR_HORZ_WS, 0 , 0 , 0 ,
482 0 , 0 , 0 , 0 ,
483//40 ( 41 ) 42 * 43 +
484//44 , 45 - 46 . 47 /
485 0 , 0 , 0 , 0 ,
486 0 , 0 , CHAR_PERIOD , 0 ,
487//48 0 49 1 50 2 51 3
488//52 4 53 5 54 6 55 7
489 CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER ,
490 CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER ,
491//56 8 57 9 58 : 59 ;
492//60 < 61 = 62 > 63 ?
493 CHAR_NUMBER , CHAR_NUMBER , 0 , 0 ,
494 0 , 0 , 0 , 0 ,
495//64 @ 65 A 66 B 67 C
496//68 D 69 E 70 F 71 G
497 0 , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
498 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
499//72 H 73 I 74 J 75 K
500//76 L 77 M 78 N 79 O
501 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
502 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
503//80 P 81 Q 82 R 83 S
504//84 T 85 U 86 V 87 W
505 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
506 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
507//88 X 89 Y 90 Z 91 [
508//92 \ 93 ] 94 ^ 95 _
509 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , 0 ,
510 0 , 0 , 0 , CHAR_UNDER ,
511//96 ` 97 a 98 b 99 c
512//100 d 101 e 102 f 103 g
513 0 , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
514 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
515//104 h 105 i 106 j 107 k
516//108 l 109 m 110 n 111 o
517 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
518 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
519//112 p 113 q 114 r 115 s
520//116 t 117 u 118 v 119 w
521 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
522 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
523//120 x 121 y 122 z 123 {
524//124 | 125 } 126 ~ 127 DEL
525 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , 0 ,
526 0 , 0 , 0 , 0
527};
528
Chris Lattnera2bf1052009-12-17 05:29:40 +0000529static void InitCharacterInfo() {
Reid Spencer5f016e22007-07-11 17:01:13 +0000530 static bool isInited = false;
531 if (isInited) return;
Chris Lattner03b98662009-07-07 17:09:54 +0000532 // check the statically-initialized CharInfo table
533 assert(CHAR_HORZ_WS == CharInfo[(int)' ']);
534 assert(CHAR_HORZ_WS == CharInfo[(int)'\t']);
535 assert(CHAR_HORZ_WS == CharInfo[(int)'\f']);
536 assert(CHAR_HORZ_WS == CharInfo[(int)'\v']);
537 assert(CHAR_VERT_WS == CharInfo[(int)'\n']);
538 assert(CHAR_VERT_WS == CharInfo[(int)'\r']);
539 assert(CHAR_UNDER == CharInfo[(int)'_']);
540 assert(CHAR_PERIOD == CharInfo[(int)'.']);
541 for (unsigned i = 'a'; i <= 'z'; ++i) {
542 assert(CHAR_LETTER == CharInfo[i]);
543 assert(CHAR_LETTER == CharInfo[i+'A'-'a']);
544 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000545 for (unsigned i = '0'; i <= '9'; ++i)
Chris Lattner03b98662009-07-07 17:09:54 +0000546 assert(CHAR_NUMBER == CharInfo[i]);
Steve Naroff7b682652009-12-08 16:38:12 +0000547
Chris Lattner03b98662009-07-07 17:09:54 +0000548 isInited = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000549}
550
Sean Hunt0016d512010-08-29 21:26:48 +0000551/// isIdentifierStart - Return true if this is the start character of an
552/// identifier, which is [a-zA-Z_].
553static inline bool isIdentifierStart(unsigned char c) {
554 return (CharInfo[c] & (CHAR_LETTER|CHAR_UNDER)) ? true : false;
555}
Chris Lattner03b98662009-07-07 17:09:54 +0000556
Reid Spencer5f016e22007-07-11 17:01:13 +0000557/// isIdentifierBody - Return true if this is the body character of an
558/// identifier, which is [a-zA-Z0-9_].
559static inline bool isIdentifierBody(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000560 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER)) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000561}
562
563/// isHorizontalWhitespace - Return true if this character is horizontal
564/// whitespace: ' ', '\t', '\f', '\v'. Note that this returns false for '\0'.
565static inline bool isHorizontalWhitespace(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000566 return (CharInfo[c] & CHAR_HORZ_WS) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000567}
568
569/// isWhitespace - Return true if this character is horizontal or vertical
570/// whitespace: ' ', '\t', '\f', '\v', '\n', '\r'. Note that this returns false
571/// for '\0'.
572static inline bool isWhitespace(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000573 return (CharInfo[c] & (CHAR_HORZ_WS|CHAR_VERT_WS)) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000574}
575
576/// isNumberBody - Return true if this is the body character of an
577/// preprocessing number, which is [a-zA-Z0-9_.].
578static inline bool isNumberBody(unsigned char c) {
Mike Stump1eb44332009-09-09 15:08:12 +0000579 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER|CHAR_PERIOD)) ?
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000580 true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000581}
582
583
584//===----------------------------------------------------------------------===//
585// Diagnostics forwarding code.
586//===----------------------------------------------------------------------===//
587
Chris Lattner409a0362007-07-22 18:38:25 +0000588/// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
589/// lexer buffer was all instantiated at a single point, perform the mapping.
590/// This is currently only used for _Pragma implementation, so it is the slow
591/// path of the hot getSourceLocation method. Do not allow it to be inlined.
Benjamin Kramerc997eb42009-11-14 16:36:57 +0000592static DISABLE_INLINE SourceLocation GetMappedTokenLoc(Preprocessor &PP,
593 SourceLocation FileLoc,
594 unsigned CharNo,
595 unsigned TokLen);
Chris Lattner409a0362007-07-22 18:38:25 +0000596static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
597 SourceLocation FileLoc,
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000598 unsigned CharNo, unsigned TokLen) {
Chris Lattnere7fb4842009-02-15 20:52:18 +0000599 assert(FileLoc.isMacroID() && "Must be an instantiation");
Mike Stump1eb44332009-09-09 15:08:12 +0000600
Chris Lattner409a0362007-07-22 18:38:25 +0000601 // Otherwise, we're lexing "mapped tokens". This is used for things like
602 // _Pragma handling. Combine the instantiation location of FileLoc with the
Chris Lattnerdf7c17a2009-01-16 07:00:02 +0000603 // spelling location.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000604 SourceManager &SM = PP.getSourceManager();
Mike Stump1eb44332009-09-09 15:08:12 +0000605
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000606 // Create a new SLoc which is expanded from Instantiation(FileLoc) but whose
Chris Lattnerdf7c17a2009-01-16 07:00:02 +0000607 // characters come from spelling(FileLoc)+Offset.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000608 SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc);
Chris Lattnerbcc2a672009-01-19 06:46:35 +0000609 SpellingLoc = SpellingLoc.getFileLocWithOffset(CharNo);
Mike Stump1eb44332009-09-09 15:08:12 +0000610
Chris Lattnere7fb4842009-02-15 20:52:18 +0000611 // Figure out the expansion loc range, which is the range covered by the
612 // original _Pragma(...) sequence.
613 std::pair<SourceLocation,SourceLocation> II =
614 SM.getImmediateInstantiationRange(FileLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000615
Chris Lattnere7fb4842009-02-15 20:52:18 +0000616 return SM.createInstantiationLoc(SpellingLoc, II.first, II.second, TokLen);
Chris Lattner409a0362007-07-22 18:38:25 +0000617}
618
Reid Spencer5f016e22007-07-11 17:01:13 +0000619/// getSourceLocation - Return a source location identifier for the specified
620/// offset in the current file.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000621SourceLocation Lexer::getSourceLocation(const char *Loc,
622 unsigned TokLen) const {
Chris Lattner448cec42007-07-22 18:44:36 +0000623 assert(Loc >= BufferStart && Loc <= BufferEnd &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000624 "Location out of range for this buffer!");
Chris Lattner9dc1f532007-07-20 16:37:10 +0000625
626 // In the normal case, we're just lexing from a simple file buffer, return
627 // the file id from FileLoc with the offset specified.
Chris Lattner448cec42007-07-22 18:44:36 +0000628 unsigned CharNo = Loc-BufferStart;
Chris Lattner9dc1f532007-07-20 16:37:10 +0000629 if (FileLoc.isFileID())
Chris Lattnerbcc2a672009-01-19 06:46:35 +0000630 return FileLoc.getFileLocWithOffset(CharNo);
Mike Stump1eb44332009-09-09 15:08:12 +0000631
Chris Lattner2b2453a2009-01-17 06:22:33 +0000632 // Otherwise, this is the _Pragma lexer case, which pretends that all of the
633 // tokens are lexed from where the _Pragma was defined.
Chris Lattner168ae2d2007-10-17 20:41:00 +0000634 assert(PP && "This doesn't work on raw lexers");
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000635 return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen);
Reid Spencer5f016e22007-07-11 17:01:13 +0000636}
637
Reid Spencer5f016e22007-07-11 17:01:13 +0000638/// Diag - Forwarding function for diagnostics. This translate a source
639/// position in the current buffer into a SourceLocation object for rendering.
Chris Lattner3cbfe2c2008-11-22 00:59:29 +0000640DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
Chris Lattner3692b092008-11-18 07:59:24 +0000641 return PP->Diag(getSourceLocation(Loc), DiagID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000642}
Reid Spencer5f016e22007-07-11 17:01:13 +0000643
644//===----------------------------------------------------------------------===//
645// Trigraph and Escaped Newline Handling Code.
646//===----------------------------------------------------------------------===//
647
648/// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
649/// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
650static char GetTrigraphCharForLetter(char Letter) {
651 switch (Letter) {
652 default: return 0;
653 case '=': return '#';
654 case ')': return ']';
655 case '(': return '[';
656 case '!': return '|';
657 case '\'': return '^';
658 case '>': return '}';
659 case '/': return '\\';
660 case '<': return '{';
661 case '-': return '~';
662 }
663}
664
665/// DecodeTrigraphChar - If the specified character is a legal trigraph when
666/// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
667/// return the result character. Finally, emit a warning about trigraph use
668/// whether trigraphs are enabled or not.
669static char DecodeTrigraphChar(const char *CP, Lexer *L) {
670 char Res = GetTrigraphCharForLetter(*CP);
Chris Lattner3692b092008-11-18 07:59:24 +0000671 if (!Res || !L) return Res;
Mike Stump1eb44332009-09-09 15:08:12 +0000672
Chris Lattner3692b092008-11-18 07:59:24 +0000673 if (!L->getFeatures().Trigraphs) {
Chris Lattner74d15df2008-11-22 02:02:22 +0000674 if (!L->isLexingRawMode())
675 L->Diag(CP-2, diag::trigraph_ignored);
Chris Lattner3692b092008-11-18 07:59:24 +0000676 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000677 }
Mike Stump1eb44332009-09-09 15:08:12 +0000678
Chris Lattner74d15df2008-11-22 02:02:22 +0000679 if (!L->isLexingRawMode())
Benjamin Kramer476d8b82010-08-11 14:47:12 +0000680 L->Diag(CP-2, diag::trigraph_converted) << llvm::StringRef(&Res, 1);
Reid Spencer5f016e22007-07-11 17:01:13 +0000681 return Res;
682}
683
Chris Lattner24f0e482009-04-18 22:05:41 +0000684/// getEscapedNewLineSize - Return the size of the specified escaped newline,
685/// 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 +0000686/// trigraph equivalent on entry to this function.
Chris Lattner24f0e482009-04-18 22:05:41 +0000687unsigned Lexer::getEscapedNewLineSize(const char *Ptr) {
688 unsigned Size = 0;
689 while (isWhitespace(Ptr[Size])) {
690 ++Size;
Mike Stump1eb44332009-09-09 15:08:12 +0000691
Chris Lattner24f0e482009-04-18 22:05:41 +0000692 if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r')
693 continue;
694
695 // If this is a \r\n or \n\r, skip the other half.
696 if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') &&
697 Ptr[Size-1] != Ptr[Size])
698 ++Size;
Mike Stump1eb44332009-09-09 15:08:12 +0000699
Chris Lattner24f0e482009-04-18 22:05:41 +0000700 return Size;
Mike Stump1eb44332009-09-09 15:08:12 +0000701 }
702
Chris Lattner24f0e482009-04-18 22:05:41 +0000703 // Not an escaped newline, must be a \t or something else.
704 return 0;
705}
706
Chris Lattner03374952009-04-18 22:27:02 +0000707/// SkipEscapedNewLines - If P points to an escaped newline (or a series of
708/// them), skip over them and return the first non-escaped-newline found,
709/// otherwise return P.
710const char *Lexer::SkipEscapedNewLines(const char *P) {
711 while (1) {
712 const char *AfterEscape;
713 if (*P == '\\') {
714 AfterEscape = P+1;
715 } else if (*P == '?') {
716 // If not a trigraph for escape, bail out.
717 if (P[1] != '?' || P[2] != '/')
718 return P;
719 AfterEscape = P+3;
720 } else {
721 return P;
722 }
Mike Stump1eb44332009-09-09 15:08:12 +0000723
Chris Lattner03374952009-04-18 22:27:02 +0000724 unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape);
725 if (NewLineSize == 0) return P;
726 P = AfterEscape+NewLineSize;
727 }
728}
729
Chris Lattner24f0e482009-04-18 22:05:41 +0000730
Reid Spencer5f016e22007-07-11 17:01:13 +0000731/// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
732/// get its size, and return it. This is tricky in several cases:
733/// 1. If currently at the start of a trigraph, we warn about the trigraph,
734/// then either return the trigraph (skipping 3 chars) or the '?',
735/// depending on whether trigraphs are enabled or not.
736/// 2. If this is an escaped newline (potentially with whitespace between
737/// the backslash and newline), implicitly skip the newline and return
738/// the char after it.
739/// 3. If this is a UCN, return it. FIXME: C++ UCN's?
740///
741/// This handles the slow/uncommon case of the getCharAndSize method. Here we
742/// know that we can accumulate into Size, and that we have already incremented
743/// Ptr by Size bytes.
744///
745/// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
746/// be updated to match.
747///
748char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
Chris Lattnerd2177732007-07-20 16:59:19 +0000749 Token *Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000750 // If we have a slash, look for an escaped newline.
751 if (Ptr[0] == '\\') {
752 ++Size;
753 ++Ptr;
754Slash:
755 // Common case, backslash-char where the char is not whitespace.
756 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump1eb44332009-09-09 15:08:12 +0000757
Chris Lattner5636a3b2009-06-23 05:15:06 +0000758 // See if we have optional whitespace characters between the slash and
759 // newline.
Chris Lattner24f0e482009-04-18 22:05:41 +0000760 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
761 // Remember that this token needs to be cleaned.
762 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +0000763
Chris Lattner24f0e482009-04-18 22:05:41 +0000764 // Warn if there was whitespace between the backslash and newline.
Chris Lattner5636a3b2009-06-23 05:15:06 +0000765 if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode())
Chris Lattner24f0e482009-04-18 22:05:41 +0000766 Diag(Ptr, diag::backslash_newline_space);
Mike Stump1eb44332009-09-09 15:08:12 +0000767
Chris Lattner24f0e482009-04-18 22:05:41 +0000768 // Found backslash<whitespace><newline>. Parse the char after it.
769 Size += EscapedNewLineSize;
770 Ptr += EscapedNewLineSize;
771 // Use slow version to accumulate a correct size field.
772 return getCharAndSizeSlow(Ptr, Size, Tok);
773 }
Mike Stump1eb44332009-09-09 15:08:12 +0000774
Reid Spencer5f016e22007-07-11 17:01:13 +0000775 // Otherwise, this is not an escaped newline, just return the slash.
776 return '\\';
777 }
Mike Stump1eb44332009-09-09 15:08:12 +0000778
Reid Spencer5f016e22007-07-11 17:01:13 +0000779 // If this is a trigraph, process it.
780 if (Ptr[0] == '?' && Ptr[1] == '?') {
781 // If this is actually a legal trigraph (not something like "??x"), emit
782 // a trigraph warning. If so, and if trigraphs are enabled, return it.
783 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : 0)) {
784 // Remember that this token needs to be cleaned.
Chris Lattnerd2177732007-07-20 16:59:19 +0000785 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +0000786
787 Ptr += 3;
788 Size += 3;
789 if (C == '\\') goto Slash;
790 return C;
791 }
792 }
Mike Stump1eb44332009-09-09 15:08:12 +0000793
Reid Spencer5f016e22007-07-11 17:01:13 +0000794 // If this is neither, return a single character.
795 ++Size;
796 return *Ptr;
797}
798
799
800/// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
801/// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
802/// and that we have already incremented Ptr by Size bytes.
803///
804/// NOTE: When this method is updated, getCharAndSizeSlow (above) should
805/// be updated to match.
806char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
807 const LangOptions &Features) {
808 // If we have a slash, look for an escaped newline.
809 if (Ptr[0] == '\\') {
810 ++Size;
811 ++Ptr;
812Slash:
813 // Common case, backslash-char where the char is not whitespace.
814 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump1eb44332009-09-09 15:08:12 +0000815
Reid Spencer5f016e22007-07-11 17:01:13 +0000816 // See if we have optional whitespace characters followed by a newline.
Chris Lattner24f0e482009-04-18 22:05:41 +0000817 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
818 // Found backslash<whitespace><newline>. Parse the char after it.
819 Size += EscapedNewLineSize;
820 Ptr += EscapedNewLineSize;
Mike Stump1eb44332009-09-09 15:08:12 +0000821
Chris Lattner24f0e482009-04-18 22:05:41 +0000822 // Use slow version to accumulate a correct size field.
823 return getCharAndSizeSlowNoWarn(Ptr, Size, Features);
824 }
Mike Stump1eb44332009-09-09 15:08:12 +0000825
Reid Spencer5f016e22007-07-11 17:01:13 +0000826 // Otherwise, this is not an escaped newline, just return the slash.
827 return '\\';
828 }
Mike Stump1eb44332009-09-09 15:08:12 +0000829
Reid Spencer5f016e22007-07-11 17:01:13 +0000830 // If this is a trigraph, process it.
831 if (Features.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
832 // If this is actually a legal trigraph (not something like "??x"), return
833 // it.
834 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
835 Ptr += 3;
836 Size += 3;
837 if (C == '\\') goto Slash;
838 return C;
839 }
840 }
Mike Stump1eb44332009-09-09 15:08:12 +0000841
Reid Spencer5f016e22007-07-11 17:01:13 +0000842 // If this is neither, return a single character.
843 ++Size;
844 return *Ptr;
845}
846
847//===----------------------------------------------------------------------===//
848// Helper methods for lexing.
849//===----------------------------------------------------------------------===//
850
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000851/// \brief Routine that indiscriminately skips bytes in the source file.
852void Lexer::SkipBytes(unsigned Bytes, bool StartOfLine) {
853 BufferPtr += Bytes;
854 if (BufferPtr > BufferEnd)
855 BufferPtr = BufferEnd;
856 IsAtStartOfLine = StartOfLine;
857}
858
Chris Lattnerd2177732007-07-20 16:59:19 +0000859void Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000860 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
861 unsigned Size;
862 unsigned char C = *CurPtr++;
Chris Lattnercd991db2010-01-11 02:38:50 +0000863 while (isIdentifierBody(C))
Reid Spencer5f016e22007-07-11 17:01:13 +0000864 C = *CurPtr++;
Chris Lattnercd991db2010-01-11 02:38:50 +0000865
Reid Spencer5f016e22007-07-11 17:01:13 +0000866 --CurPtr; // Back up over the skipped character.
867
868 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
869 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
870 // FIXME: UCNs.
Chris Lattnercd991db2010-01-11 02:38:50 +0000871 //
872 // TODO: Could merge these checks into a CharInfo flag to make the comparison
873 // cheaper
Reid Spencer5f016e22007-07-11 17:01:13 +0000874 if (C != '\\' && C != '?' && (C != '$' || !Features.DollarIdents)) {
875FinishIdentifier:
876 const char *IdStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +0000877 FormTokenWithChars(Result, CurPtr, tok::identifier);
Mike Stump1eb44332009-09-09 15:08:12 +0000878
Reid Spencer5f016e22007-07-11 17:01:13 +0000879 // If we are in raw mode, return this identifier raw. There is no need to
880 // look up identifier information or attempt to macro expand it.
881 if (LexingRawMode) return;
Mike Stump1eb44332009-09-09 15:08:12 +0000882
Reid Spencer5f016e22007-07-11 17:01:13 +0000883 // Fill in Result.IdentifierInfo, looking up the identifier in the
884 // identifier table.
Chris Lattnerd1186fa2009-01-21 07:45:14 +0000885 IdentifierInfo *II = PP->LookUpIdentifierInfo(Result, IdStart);
Mike Stump1eb44332009-09-09 15:08:12 +0000886
Chris Lattner863c4862009-01-23 18:35:48 +0000887 // Change the kind of this identifier to the appropriate token kind, e.g.
888 // turning "for" into a keyword.
889 Result.setKind(II->getTokenID());
Mike Stump1eb44332009-09-09 15:08:12 +0000890
Reid Spencer5f016e22007-07-11 17:01:13 +0000891 // Finally, now that we know we have an identifier, pass this off to the
892 // preprocessor, which may macro expand it or something.
Chris Lattnerd1186fa2009-01-21 07:45:14 +0000893 if (II->isHandleIdentifierCase())
Chris Lattner6a170eb2009-01-21 07:43:11 +0000894 PP->HandleIdentifier(Result);
895 return;
Reid Spencer5f016e22007-07-11 17:01:13 +0000896 }
Mike Stump1eb44332009-09-09 15:08:12 +0000897
Reid Spencer5f016e22007-07-11 17:01:13 +0000898 // Otherwise, $,\,? in identifier found. Enter slower path.
Mike Stump1eb44332009-09-09 15:08:12 +0000899
Reid Spencer5f016e22007-07-11 17:01:13 +0000900 C = getCharAndSize(CurPtr, Size);
901 while (1) {
902 if (C == '$') {
903 // If we hit a $ and they are not supported in identifiers, we are done.
904 if (!Features.DollarIdents) goto FinishIdentifier;
Mike Stump1eb44332009-09-09 15:08:12 +0000905
Reid Spencer5f016e22007-07-11 17:01:13 +0000906 // Otherwise, emit a diagnostic and continue.
Chris Lattner74d15df2008-11-22 02:02:22 +0000907 if (!isLexingRawMode())
908 Diag(CurPtr, diag::ext_dollar_in_identifier);
Reid Spencer5f016e22007-07-11 17:01:13 +0000909 CurPtr = ConsumeChar(CurPtr, Size, Result);
910 C = getCharAndSize(CurPtr, Size);
911 continue;
912 } else if (!isIdentifierBody(C)) { // FIXME: UCNs.
913 // Found end of identifier.
914 goto FinishIdentifier;
915 }
916
917 // Otherwise, this character is good, consume it.
918 CurPtr = ConsumeChar(CurPtr, Size, Result);
919
920 C = getCharAndSize(CurPtr, Size);
921 while (isIdentifierBody(C)) { // FIXME: UCNs.
922 CurPtr = ConsumeChar(CurPtr, Size, Result);
923 C = getCharAndSize(CurPtr, Size);
924 }
925 }
926}
927
Douglas Gregora75ec432010-08-30 14:50:47 +0000928/// isHexaLiteral - Return true if Start points to a hex constant.
929static inline bool isHexaLiteral(const char* Start, const char* End) {
930 return ((End - Start > 2) && Start[0] == '0' &&
931 (Start[1] == 'x' || Start[1] == 'X'));
932}
Reid Spencer5f016e22007-07-11 17:01:13 +0000933
Nate Begeman5253c7f2008-04-14 02:26:39 +0000934/// LexNumericConstant - Lex the remainder of a integer or floating point
Reid Spencer5f016e22007-07-11 17:01:13 +0000935/// constant. From[-1] is the first character lexed. Return the end of the
936/// constant.
Chris Lattnerd2177732007-07-20 16:59:19 +0000937void Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000938 unsigned Size;
939 char C = getCharAndSize(CurPtr, Size);
940 char PrevCh = 0;
941 while (isNumberBody(C)) { // FIXME: UCNs?
942 CurPtr = ConsumeChar(CurPtr, Size, Result);
943 PrevCh = C;
944 C = getCharAndSize(CurPtr, Size);
945 }
Mike Stump1eb44332009-09-09 15:08:12 +0000946
Reid Spencer5f016e22007-07-11 17:01:13 +0000947 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
Douglas Gregora75ec432010-08-30 14:50:47 +0000948 // If we are in Microsoft mode, don't continue if the constant is hex.
949 // For example, MSVC will accept the following as 3 tokens: 0x1234567e+1
950 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e') &&
951 (!PP || !PP->getLangOptions().Microsoft ||
952 !isHexaLiteral(BufferPtr, CurPtr)))
Reid Spencer5f016e22007-07-11 17:01:13 +0000953 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
954
955 // If we have a hex FP constant, continue.
Sean Hunt8c723402010-01-10 23:37:56 +0000956 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p') &&
957 (!PP || !PP->getLangOptions().CPlusPlus0x))
Reid Spencer5f016e22007-07-11 17:01:13 +0000958 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
Mike Stump1eb44332009-09-09 15:08:12 +0000959
Reid Spencer5f016e22007-07-11 17:01:13 +0000960 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +0000961 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +0000962 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
Chris Lattner47246be2009-01-26 19:29:26 +0000963 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +0000964}
965
966/// LexStringLiteral - Lex the remainder of a string literal, after having lexed
967/// either " or L".
Chris Lattnerd88dc482008-10-12 04:05:48 +0000968void Lexer::LexStringLiteral(Token &Result, const char *CurPtr, bool Wide) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000969 const char *NulCharacter = 0; // Does this string contain the \0 character?
Mike Stump1eb44332009-09-09 15:08:12 +0000970
Reid Spencer5f016e22007-07-11 17:01:13 +0000971 char C = getAndAdvanceChar(CurPtr, Result);
972 while (C != '"') {
Chris Lattner571339c2010-05-30 23:27:38 +0000973 // Skip escaped characters. Escaped newlines will already be processed by
974 // getAndAdvanceChar.
975 if (C == '\\')
Reid Spencer5f016e22007-07-11 17:01:13 +0000976 C = getAndAdvanceChar(CurPtr, Result);
Douglas Gregor33611e02010-05-30 22:59:50 +0000977
Chris Lattner571339c2010-05-30 23:27:38 +0000978 if (C == '\n' || C == '\r' || // Newline.
Douglas Gregor33611e02010-05-30 22:59:50 +0000979 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Douglas Gregor55817af2010-08-25 17:04:25 +0000980 if (C == 0 && PP && PP->isCodeCompletionFile(FileLoc))
981 PP->CodeCompleteNaturalLanguage();
982 else if (!isLexingRawMode() && !Features.AsmPreprocessor)
Chris Lattner74d15df2008-11-22 02:02:22 +0000983 Diag(BufferPtr, diag::err_unterminated_string);
Chris Lattner9e6293d2008-10-12 04:51:35 +0000984 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Reid Spencer5f016e22007-07-11 17:01:13 +0000985 return;
Reid Spencer5f016e22007-07-11 17:01:13 +0000986 }
Chris Lattner571339c2010-05-30 23:27:38 +0000987
988 if (C == 0)
989 NulCharacter = CurPtr-1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000990 C = getAndAdvanceChar(CurPtr, Result);
991 }
Mike Stump1eb44332009-09-09 15:08:12 +0000992
Reid Spencer5f016e22007-07-11 17:01:13 +0000993 // If a nul character existed in the string, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +0000994 if (NulCharacter && !isLexingRawMode())
995 Diag(NulCharacter, diag::null_in_string);
Reid Spencer5f016e22007-07-11 17:01:13 +0000996
Reid Spencer5f016e22007-07-11 17:01:13 +0000997 // Update the location of the token as well as the BufferPtr instance var.
Chris Lattner47246be2009-01-26 19:29:26 +0000998 const char *TokStart = BufferPtr;
Sean Hunt0016d512010-08-29 21:26:48 +0000999 tok::TokenKind Kind = Wide ? tok::wide_string_literal : tok::string_literal;
1000
1001 // FIXME: Handle UCNs
1002 unsigned Size;
1003 if (PP && PP->getLangOptions().CPlusPlus0x &&
1004 isIdentifierStart(getCharAndSize(CurPtr, Size))) {
1005 Result.makeUserDefinedLiteral(ExtraDataAllocator);
1006 Result.setFlagValue(Token::LiteralPortionClean, !Result.needsCleaning());
1007 Result.setKind(Kind);
1008 Result.setLiteralLength(CurPtr - BufferPtr);
1009
1010 // FIXME: We hack around the lexer's routines a lot here.
1011 BufferPtr = CurPtr;
1012 bool OldRawMode = LexingRawMode;
1013 LexingRawMode = true;
1014 LexIdentifier(Result, ConsumeChar(CurPtr, Size, Result));
1015 LexingRawMode = OldRawMode;
1016 PP->LookUpIdentifierInfo(Result, CurPtr);
1017
1018 CurPtr = BufferPtr;
1019 BufferPtr = TokStart;
1020 }
1021
1022 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner47246be2009-01-26 19:29:26 +00001023 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001024}
1025
1026/// LexAngledStringLiteral - Lex the remainder of an angled string literal,
1027/// after having lexed the '<' character. This is used for #include filenames.
Chris Lattnerd2177732007-07-20 16:59:19 +00001028void Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001029 const char *NulCharacter = 0; // Does this string contain the \0 character?
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001030 const char *AfterLessPos = CurPtr;
Reid Spencer5f016e22007-07-11 17:01:13 +00001031 char C = getAndAdvanceChar(CurPtr, Result);
1032 while (C != '>') {
1033 // Skip escaped characters.
1034 if (C == '\\') {
1035 // Skip the escaped character.
1036 C = getAndAdvanceChar(CurPtr, Result);
1037 } else if (C == '\n' || C == '\r' || // Newline.
1038 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001039 // If the filename is unterminated, then it must just be a lone <
1040 // character. Return this as such.
1041 FormTokenWithChars(Result, AfterLessPos, tok::less);
Reid Spencer5f016e22007-07-11 17:01:13 +00001042 return;
1043 } else if (C == 0) {
1044 NulCharacter = CurPtr-1;
1045 }
1046 C = getAndAdvanceChar(CurPtr, Result);
1047 }
Mike Stump1eb44332009-09-09 15:08:12 +00001048
Reid Spencer5f016e22007-07-11 17:01:13 +00001049 // If a nul character existed in the string, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001050 if (NulCharacter && !isLexingRawMode())
1051 Diag(NulCharacter, diag::null_in_string);
Mike Stump1eb44332009-09-09 15:08:12 +00001052
Reid Spencer5f016e22007-07-11 17:01:13 +00001053 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001054 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001055 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
Chris Lattner47246be2009-01-26 19:29:26 +00001056 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001057}
1058
1059
1060/// LexCharConstant - Lex the remainder of a character constant, after having
1061/// lexed either ' or L'.
Chris Lattnerd2177732007-07-20 16:59:19 +00001062void Lexer::LexCharConstant(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001063 const char *NulCharacter = 0; // Does this character contain the \0 character?
1064
Reid Spencer5f016e22007-07-11 17:01:13 +00001065 char C = getAndAdvanceChar(CurPtr, Result);
1066 if (C == '\'') {
Chris Lattner33ab3f62009-03-18 21:10:12 +00001067 if (!isLexingRawMode() && !Features.AsmPreprocessor)
Chris Lattner74d15df2008-11-22 02:02:22 +00001068 Diag(BufferPtr, diag::err_empty_character);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001069 FormTokenWithChars(Result, CurPtr, tok::unknown);
Reid Spencer5f016e22007-07-11 17:01:13 +00001070 return;
Chris Lattnerd80f7862010-07-07 23:24:27 +00001071 }
1072
1073 while (C != '\'') {
1074 // Skip escaped characters.
1075 if (C == '\\') {
1076 // Skip the escaped character.
1077 // FIXME: UCN's
1078 C = getAndAdvanceChar(CurPtr, Result);
1079 } else if (C == '\n' || C == '\r' || // Newline.
1080 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Douglas Gregor55817af2010-08-25 17:04:25 +00001081 if (C == 0 && PP && PP->isCodeCompletionFile(FileLoc))
1082 PP->CodeCompleteNaturalLanguage();
1083 else if (!isLexingRawMode() && !Features.AsmPreprocessor)
Chris Lattnerd80f7862010-07-07 23:24:27 +00001084 Diag(BufferPtr, diag::err_unterminated_char);
1085 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1086 return;
1087 } else if (C == 0) {
1088 NulCharacter = CurPtr-1;
1089 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001090 C = getAndAdvanceChar(CurPtr, Result);
1091 }
Mike Stump1eb44332009-09-09 15:08:12 +00001092
Chris Lattnerd80f7862010-07-07 23:24:27 +00001093 // If a nul character existed in the character, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001094 if (NulCharacter && !isLexingRawMode())
1095 Diag(NulCharacter, diag::null_in_char);
Reid Spencer5f016e22007-07-11 17:01:13 +00001096
Reid Spencer5f016e22007-07-11 17:01:13 +00001097 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001098 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001099 FormTokenWithChars(Result, CurPtr, tok::char_constant);
Chris Lattner47246be2009-01-26 19:29:26 +00001100 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001101}
1102
1103/// SkipWhitespace - Efficiently skip over a series of whitespace characters.
1104/// Update BufferPtr to point to the next non-whitespace character and return.
Chris Lattnerd88dc482008-10-12 04:05:48 +00001105///
1106/// This method forms a token and returns true if KeepWhitespaceMode is enabled.
1107///
1108bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001109 // Whitespace - Skip it, then return the token after the whitespace.
1110 unsigned char Char = *CurPtr; // Skip consequtive spaces efficiently.
1111 while (1) {
1112 // Skip horizontal whitespace very aggressively.
1113 while (isHorizontalWhitespace(Char))
1114 Char = *++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001115
Daniel Dunbarddd3e8b2008-11-25 00:20:22 +00001116 // Otherwise if we have something other than whitespace, we're done.
Reid Spencer5f016e22007-07-11 17:01:13 +00001117 if (Char != '\n' && Char != '\r')
1118 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001119
Reid Spencer5f016e22007-07-11 17:01:13 +00001120 if (ParsingPreprocessorDirective) {
1121 // End of preprocessor directive line, let LexTokenInternal handle this.
1122 BufferPtr = CurPtr;
Chris Lattnerd88dc482008-10-12 04:05:48 +00001123 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001124 }
Mike Stump1eb44332009-09-09 15:08:12 +00001125
Reid Spencer5f016e22007-07-11 17:01:13 +00001126 // ok, but handle newline.
1127 // The returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00001128 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00001129 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00001130 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001131 Char = *++CurPtr;
1132 }
1133
1134 // If this isn't immediately after a newline, there is leading space.
1135 char PrevChar = CurPtr[-1];
1136 if (PrevChar != '\n' && PrevChar != '\r')
Chris Lattnerd2177732007-07-20 16:59:19 +00001137 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001138
Chris Lattnerd88dc482008-10-12 04:05:48 +00001139 // If the client wants us to return whitespace, return it now.
1140 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001141 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd88dc482008-10-12 04:05:48 +00001142 return true;
1143 }
Mike Stump1eb44332009-09-09 15:08:12 +00001144
Reid Spencer5f016e22007-07-11 17:01:13 +00001145 BufferPtr = CurPtr;
Chris Lattnerd88dc482008-10-12 04:05:48 +00001146 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001147}
1148
1149// SkipBCPLComment - We have just read the // characters from input. Skip until
1150// we find the newline character thats terminate the comment. Then update
Chris Lattner046c2272010-01-18 22:35:47 +00001151/// BufferPtr and return.
1152///
1153/// If we're in KeepCommentMode or any CommentHandler has inserted
1154/// some tokens, this will store the first token and return true.
Chris Lattnerd2177732007-07-20 16:59:19 +00001155bool Lexer::SkipBCPLComment(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001156 // If BCPL comments aren't explicitly enabled for this language, emit an
1157 // extension warning.
Chris Lattner74d15df2008-11-22 02:02:22 +00001158 if (!Features.BCPLComment && !isLexingRawMode()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001159 Diag(BufferPtr, diag::ext_bcpl_comment);
Mike Stump1eb44332009-09-09 15:08:12 +00001160
Reid Spencer5f016e22007-07-11 17:01:13 +00001161 // Mark them enabled so we only emit one warning for this translation
1162 // unit.
1163 Features.BCPLComment = true;
1164 }
Mike Stump1eb44332009-09-09 15:08:12 +00001165
Reid Spencer5f016e22007-07-11 17:01:13 +00001166 // Scan over the body of the comment. The common case, when scanning, is that
1167 // the comment contains normal ascii characters with nothing interesting in
1168 // them. As such, optimize for this case with the inner loop.
1169 char C;
1170 do {
1171 C = *CurPtr;
1172 // FIXME: Speedup BCPL comment lexing. Just scan for a \n or \r character.
1173 // If we find a \n character, scan backwards, checking to see if it's an
1174 // escaped newline, like we do for block comments.
Mike Stump1eb44332009-09-09 15:08:12 +00001175
Reid Spencer5f016e22007-07-11 17:01:13 +00001176 // Skip over characters in the fast loop.
1177 while (C != 0 && // Potentially EOF.
1178 C != '\\' && // Potentially escaped newline.
1179 C != '?' && // Potentially trigraph.
1180 C != '\n' && C != '\r') // Newline or DOS-style newline.
1181 C = *++CurPtr;
1182
1183 // If this is a newline, we're done.
1184 if (C == '\n' || C == '\r')
1185 break; // Found the newline? Break out!
Mike Stump1eb44332009-09-09 15:08:12 +00001186
Reid Spencer5f016e22007-07-11 17:01:13 +00001187 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001188 // properly decode the character. Read it in raw mode to avoid emitting
1189 // diagnostics about things like trigraphs. If we see an escaped newline,
1190 // we'll handle it below.
Reid Spencer5f016e22007-07-11 17:01:13 +00001191 const char *OldPtr = CurPtr;
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001192 bool OldRawMode = isLexingRawMode();
1193 LexingRawMode = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001194 C = getAndAdvanceChar(CurPtr, Result);
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001195 LexingRawMode = OldRawMode;
Chris Lattneread616c2009-04-05 00:26:41 +00001196
1197 // If the char that we finally got was a \n, then we must have had something
1198 // like \<newline><newline>. We don't want to have consumed the second
1199 // newline, we want CurPtr, to end up pointing to it down below.
1200 if (C == '\n' || C == '\r') {
1201 --CurPtr;
1202 C = 'x'; // doesn't matter what this is.
1203 }
Mike Stump1eb44332009-09-09 15:08:12 +00001204
Reid Spencer5f016e22007-07-11 17:01:13 +00001205 // If we read multiple characters, and one of those characters was a \r or
1206 // \n, then we had an escaped newline within the comment. Emit diagnostic
1207 // unless the next line is also a // comment.
1208 if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') {
1209 for (; OldPtr != CurPtr; ++OldPtr)
1210 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
1211 // Okay, we found a // comment that ends in a newline, if the next
1212 // line is also a // comment, but has spaces, don't emit a diagnostic.
1213 if (isspace(C)) {
1214 const char *ForwardPtr = CurPtr;
1215 while (isspace(*ForwardPtr)) // Skip whitespace.
1216 ++ForwardPtr;
1217 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
1218 break;
1219 }
Mike Stump1eb44332009-09-09 15:08:12 +00001220
Chris Lattner74d15df2008-11-22 02:02:22 +00001221 if (!isLexingRawMode())
1222 Diag(OldPtr-1, diag::ext_multi_line_bcpl_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001223 break;
1224 }
1225 }
Mike Stump1eb44332009-09-09 15:08:12 +00001226
Douglas Gregor55817af2010-08-25 17:04:25 +00001227 if (CurPtr == BufferEnd+1) {
1228 if (PP && PP->isCodeCompletionFile(FileLoc))
1229 PP->CodeCompleteNaturalLanguage();
1230
1231 --CurPtr;
1232 break;
1233 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001234 } while (C != '\n' && C != '\r');
1235
Chris Lattner3d0ad582010-02-03 21:06:21 +00001236 // Found but did not consume the newline. Notify comment handlers about the
1237 // comment unless we're in a #if 0 block.
1238 if (PP && !isLexingRawMode() &&
1239 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
1240 getSourceLocation(CurPtr)))) {
Chris Lattner046c2272010-01-18 22:35:47 +00001241 BufferPtr = CurPtr;
1242 return true; // A token has to be returned.
1243 }
Mike Stump1eb44332009-09-09 15:08:12 +00001244
Reid Spencer5f016e22007-07-11 17:01:13 +00001245 // If we are returning comments as tokens, return this comment as a token.
Chris Lattnerfa95a012008-10-12 03:22:02 +00001246 if (inKeepCommentMode())
Reid Spencer5f016e22007-07-11 17:01:13 +00001247 return SaveBCPLComment(Result, CurPtr);
1248
1249 // If we are inside a preprocessor directive and we see the end of line,
1250 // return immediately, so that the lexer can return this as an EOM token.
1251 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
1252 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001253 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001254 }
Mike Stump1eb44332009-09-09 15:08:12 +00001255
Reid Spencer5f016e22007-07-11 17:01:13 +00001256 // Otherwise, eat the \n character. We don't care if this is a \n\r or
Chris Lattner7a4f0042008-10-12 00:23:07 +00001257 // \r\n sequence. This is an efficiency hack (because we know the \n can't
Chris Lattnerd88dc482008-10-12 04:05:48 +00001258 // contribute to another token), it isn't needed for correctness. Note that
1259 // this is ok even in KeepWhitespaceMode, because we would have returned the
1260 /// comment above in that mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00001261 ++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001262
Reid Spencer5f016e22007-07-11 17:01:13 +00001263 // The next returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00001264 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00001265 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00001266 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001267 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001268 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001269}
1270
1271/// SaveBCPLComment - If in save-comment mode, package up this BCPL comment in
1272/// an appropriate way and return it.
Chris Lattnerd2177732007-07-20 16:59:19 +00001273bool Lexer::SaveBCPLComment(Token &Result, const char *CurPtr) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001274 // If we're not in a preprocessor directive, just return the // comment
1275 // directly.
1276 FormTokenWithChars(Result, CurPtr, tok::comment);
Mike Stump1eb44332009-09-09 15:08:12 +00001277
Chris Lattner9e6293d2008-10-12 04:51:35 +00001278 if (!ParsingPreprocessorDirective)
1279 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001280
Chris Lattner9e6293d2008-10-12 04:51:35 +00001281 // If this BCPL-style comment is in a macro definition, transmogrify it into
1282 // a C-style block comment.
Douglas Gregor453091c2010-03-16 22:30:13 +00001283 bool Invalid = false;
1284 std::string Spelling = PP->getSpelling(Result, &Invalid);
1285 if (Invalid)
1286 return true;
1287
Chris Lattner9e6293d2008-10-12 04:51:35 +00001288 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not bcpl comment?");
1289 Spelling[1] = '*'; // Change prefix to "/*".
1290 Spelling += "*/"; // add suffix.
Mike Stump1eb44332009-09-09 15:08:12 +00001291
Chris Lattner9e6293d2008-10-12 04:51:35 +00001292 Result.setKind(tok::comment);
Chris Lattner47246be2009-01-26 19:29:26 +00001293 PP->CreateString(&Spelling[0], Spelling.size(), Result,
1294 Result.getLocation());
Chris Lattner2d381892008-10-12 04:15:42 +00001295 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001296}
1297
1298/// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
1299/// character (either \n or \r) is part of an escaped newline sequence. Issue a
Chris Lattner47a2b402008-12-12 07:14:34 +00001300/// diagnostic if so. We know that the newline is inside of a block comment.
Mike Stump1eb44332009-09-09 15:08:12 +00001301static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
Reid Spencer5f016e22007-07-11 17:01:13 +00001302 Lexer *L) {
1303 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
Mike Stump1eb44332009-09-09 15:08:12 +00001304
Reid Spencer5f016e22007-07-11 17:01:13 +00001305 // Back up off the newline.
1306 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001307
Reid Spencer5f016e22007-07-11 17:01:13 +00001308 // If this is a two-character newline sequence, skip the other character.
1309 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
1310 // \n\n or \r\r -> not escaped newline.
1311 if (CurPtr[0] == CurPtr[1])
1312 return false;
1313 // \n\r or \r\n -> skip the newline.
1314 --CurPtr;
1315 }
Mike Stump1eb44332009-09-09 15:08:12 +00001316
Reid Spencer5f016e22007-07-11 17:01:13 +00001317 // If we have horizontal whitespace, skip over it. We allow whitespace
1318 // between the slash and newline.
1319 bool HasSpace = false;
1320 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
1321 --CurPtr;
1322 HasSpace = true;
1323 }
Mike Stump1eb44332009-09-09 15:08:12 +00001324
Reid Spencer5f016e22007-07-11 17:01:13 +00001325 // If we have a slash, we know this is an escaped newline.
1326 if (*CurPtr == '\\') {
1327 if (CurPtr[-1] != '*') return false;
1328 } else {
1329 // It isn't a slash, is it the ?? / trigraph?
1330 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
1331 CurPtr[-3] != '*')
1332 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001333
Reid Spencer5f016e22007-07-11 17:01:13 +00001334 // This is the trigraph ending the comment. Emit a stern warning!
1335 CurPtr -= 2;
1336
1337 // If no trigraphs are enabled, warn that we ignored this trigraph and
1338 // ignore this * character.
1339 if (!L->getFeatures().Trigraphs) {
Chris Lattner74d15df2008-11-22 02:02:22 +00001340 if (!L->isLexingRawMode())
1341 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001342 return false;
1343 }
Chris Lattner74d15df2008-11-22 02:02:22 +00001344 if (!L->isLexingRawMode())
1345 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001346 }
Mike Stump1eb44332009-09-09 15:08:12 +00001347
Reid Spencer5f016e22007-07-11 17:01:13 +00001348 // Warn about having an escaped newline between the */ characters.
Chris Lattner74d15df2008-11-22 02:02:22 +00001349 if (!L->isLexingRawMode())
1350 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
Mike Stump1eb44332009-09-09 15:08:12 +00001351
Reid Spencer5f016e22007-07-11 17:01:13 +00001352 // If there was space between the backslash and newline, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001353 if (HasSpace && !L->isLexingRawMode())
1354 L->Diag(CurPtr, diag::backslash_newline_space);
Mike Stump1eb44332009-09-09 15:08:12 +00001355
Reid Spencer5f016e22007-07-11 17:01:13 +00001356 return true;
1357}
1358
1359#ifdef __SSE2__
1360#include <emmintrin.h>
1361#elif __ALTIVEC__
1362#include <altivec.h>
1363#undef bool
1364#endif
1365
1366/// SkipBlockComment - We have just read the /* characters from input. Read
1367/// until we find the */ characters that terminate the comment. Note that we
1368/// don't bother decoding trigraphs or escaped newlines in block comments,
1369/// because they cannot cause the comment to end. The only thing that can
1370/// happen is the comment could end with an escaped newline between the */ end
1371/// of comment.
Chris Lattner2d381892008-10-12 04:15:42 +00001372///
Chris Lattner046c2272010-01-18 22:35:47 +00001373/// If we're in KeepCommentMode or any CommentHandler has inserted
1374/// some tokens, this will store the first token and return true.
Chris Lattnerd2177732007-07-20 16:59:19 +00001375bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001376 // Scan one character past where we should, looking for a '/' character. Once
1377 // we find it, check to see if it was preceeded by a *. This common
1378 // optimization helps people who like to put a lot of * characters in their
1379 // comments.
Chris Lattner8146b682007-07-21 23:43:37 +00001380
1381 // The first character we get with newlines and trigraphs skipped to handle
1382 // the degenerate /*/ case below correctly if the * has an escaped newline
1383 // after it.
1384 unsigned CharSize;
1385 unsigned char C = getCharAndSize(CurPtr, CharSize);
1386 CurPtr += CharSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001387 if (C == 0 && CurPtr == BufferEnd+1) {
Chris Lattner150fcd52010-05-16 19:54:05 +00001388 if (!isLexingRawMode() &&
1389 !PP->isCodeCompletionFile(FileLoc))
Chris Lattner0af57422008-10-12 01:31:51 +00001390 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner31f0eca2008-10-12 04:19:49 +00001391 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001392
Chris Lattner31f0eca2008-10-12 04:19:49 +00001393 // KeepWhitespaceMode should return this broken comment as a token. Since
1394 // it isn't a well formed comment, just return it as an 'unknown' token.
1395 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001396 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner31f0eca2008-10-12 04:19:49 +00001397 return true;
1398 }
Mike Stump1eb44332009-09-09 15:08:12 +00001399
Chris Lattner31f0eca2008-10-12 04:19:49 +00001400 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001401 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001402 }
Mike Stump1eb44332009-09-09 15:08:12 +00001403
Chris Lattner8146b682007-07-21 23:43:37 +00001404 // Check to see if the first character after the '/*' is another /. If so,
1405 // then this slash does not end the block comment, it is part of it.
1406 if (C == '/')
1407 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00001408
Reid Spencer5f016e22007-07-11 17:01:13 +00001409 while (1) {
1410 // Skip over all non-interesting characters until we find end of buffer or a
1411 // (probably ending) '/' character.
1412 if (CurPtr + 24 < BufferEnd) {
1413 // While not aligned to a 16-byte boundary.
1414 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
1415 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00001416
Reid Spencer5f016e22007-07-11 17:01:13 +00001417 if (C == '/') goto FoundSlash;
1418
1419#ifdef __SSE2__
1420 __m128i Slashes = _mm_set_epi8('/', '/', '/', '/', '/', '/', '/', '/',
1421 '/', '/', '/', '/', '/', '/', '/', '/');
1422 while (CurPtr+16 <= BufferEnd &&
1423 _mm_movemask_epi8(_mm_cmpeq_epi8(*(__m128i*)CurPtr, Slashes)) == 0)
1424 CurPtr += 16;
1425#elif __ALTIVEC__
1426 __vector unsigned char Slashes = {
Mike Stump1eb44332009-09-09 15:08:12 +00001427 '/', '/', '/', '/', '/', '/', '/', '/',
Reid Spencer5f016e22007-07-11 17:01:13 +00001428 '/', '/', '/', '/', '/', '/', '/', '/'
1429 };
1430 while (CurPtr+16 <= BufferEnd &&
1431 !vec_any_eq(*(vector unsigned char*)CurPtr, Slashes))
1432 CurPtr += 16;
Mike Stump1eb44332009-09-09 15:08:12 +00001433#else
Reid Spencer5f016e22007-07-11 17:01:13 +00001434 // Scan for '/' quickly. Many block comments are very large.
1435 while (CurPtr[0] != '/' &&
1436 CurPtr[1] != '/' &&
1437 CurPtr[2] != '/' &&
1438 CurPtr[3] != '/' &&
1439 CurPtr+4 < BufferEnd) {
1440 CurPtr += 4;
1441 }
1442#endif
Mike Stump1eb44332009-09-09 15:08:12 +00001443
Reid Spencer5f016e22007-07-11 17:01:13 +00001444 // It has to be one of the bytes scanned, increment to it and read one.
1445 C = *CurPtr++;
1446 }
Mike Stump1eb44332009-09-09 15:08:12 +00001447
Reid Spencer5f016e22007-07-11 17:01:13 +00001448 // Loop to scan the remainder.
1449 while (C != '/' && C != '\0')
1450 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00001451
Reid Spencer5f016e22007-07-11 17:01:13 +00001452 FoundSlash:
1453 if (C == '/') {
1454 if (CurPtr[-2] == '*') // We found the final */. We're done!
1455 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001456
Reid Spencer5f016e22007-07-11 17:01:13 +00001457 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
1458 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
1459 // We found the final */, though it had an escaped newline between the
1460 // * and /. We're done!
1461 break;
1462 }
1463 }
1464 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
1465 // If this is a /* inside of the comment, emit a warning. Don't do this
1466 // if this is a /*/, which will end the comment. This misses cases with
1467 // embedded escaped newlines, but oh well.
Chris Lattner74d15df2008-11-22 02:02:22 +00001468 if (!isLexingRawMode())
1469 Diag(CurPtr-1, diag::warn_nested_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001470 }
1471 } else if (C == 0 && CurPtr == BufferEnd+1) {
Douglas Gregor55817af2010-08-25 17:04:25 +00001472 if (PP && PP->isCodeCompletionFile(FileLoc))
1473 PP->CodeCompleteNaturalLanguage();
1474 else if (!isLexingRawMode())
Chris Lattner74d15df2008-11-22 02:02:22 +00001475 Diag(BufferPtr, diag::err_unterminated_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001476 // Note: the user probably forgot a */. We could continue immediately
1477 // after the /*, but this would involve lexing a lot of what really is the
1478 // comment, which surely would confuse the parser.
Chris Lattner31f0eca2008-10-12 04:19:49 +00001479 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001480
Chris Lattner31f0eca2008-10-12 04:19:49 +00001481 // KeepWhitespaceMode should return this broken comment as a token. Since
1482 // it isn't a well formed comment, just return it as an 'unknown' token.
1483 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001484 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner31f0eca2008-10-12 04:19:49 +00001485 return true;
1486 }
Mike Stump1eb44332009-09-09 15:08:12 +00001487
Chris Lattner31f0eca2008-10-12 04:19:49 +00001488 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001489 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001490 }
1491 C = *CurPtr++;
1492 }
Mike Stump1eb44332009-09-09 15:08:12 +00001493
Chris Lattner3d0ad582010-02-03 21:06:21 +00001494 // Notify comment handlers about the comment unless we're in a #if 0 block.
1495 if (PP && !isLexingRawMode() &&
1496 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
1497 getSourceLocation(CurPtr)))) {
Chris Lattner046c2272010-01-18 22:35:47 +00001498 BufferPtr = CurPtr;
1499 return true; // A token has to be returned.
1500 }
Douglas Gregor2e222532009-07-02 17:08:52 +00001501
Reid Spencer5f016e22007-07-11 17:01:13 +00001502 // If we are returning comments as tokens, return this comment as a token.
Chris Lattnerfa95a012008-10-12 03:22:02 +00001503 if (inKeepCommentMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001504 FormTokenWithChars(Result, CurPtr, tok::comment);
Chris Lattner2d381892008-10-12 04:15:42 +00001505 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001506 }
1507
1508 // It is common for the tokens immediately after a /**/ comment to be
1509 // whitespace. Instead of going through the big switch, handle it
Chris Lattnerd88dc482008-10-12 04:05:48 +00001510 // efficiently now. This is safe even in KeepWhitespaceMode because we would
1511 // have already returned above with the comment as a token.
Reid Spencer5f016e22007-07-11 17:01:13 +00001512 if (isHorizontalWhitespace(*CurPtr)) {
Chris Lattnerd2177732007-07-20 16:59:19 +00001513 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001514 SkipWhitespace(Result, CurPtr+1);
Chris Lattner2d381892008-10-12 04:15:42 +00001515 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001516 }
1517
1518 // Otherwise, just return so that the next character will be lexed as a token.
1519 BufferPtr = CurPtr;
Chris Lattnerd2177732007-07-20 16:59:19 +00001520 Result.setFlag(Token::LeadingSpace);
Chris Lattner2d381892008-10-12 04:15:42 +00001521 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001522}
1523
1524//===----------------------------------------------------------------------===//
1525// Primary Lexing Entry Points
1526//===----------------------------------------------------------------------===//
1527
Reid Spencer5f016e22007-07-11 17:01:13 +00001528/// ReadToEndOfLine - Read the rest of the current preprocessor line as an
1529/// uninterpreted string. This switches the lexer out of directive mode.
1530std::string Lexer::ReadToEndOfLine() {
1531 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
1532 "Must be in a preprocessing directive!");
1533 std::string Result;
Chris Lattnerd2177732007-07-20 16:59:19 +00001534 Token Tmp;
Reid Spencer5f016e22007-07-11 17:01:13 +00001535
1536 // CurPtr - Cache BufferPtr in an automatic variable.
1537 const char *CurPtr = BufferPtr;
1538 while (1) {
1539 char Char = getAndAdvanceChar(CurPtr, Tmp);
1540 switch (Char) {
1541 default:
1542 Result += Char;
1543 break;
1544 case 0: // Null.
1545 // Found end of file?
1546 if (CurPtr-1 != BufferEnd) {
1547 // Nope, normal character, continue.
1548 Result += Char;
1549 break;
1550 }
1551 // FALL THROUGH.
1552 case '\r':
1553 case '\n':
1554 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
1555 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
1556 BufferPtr = CurPtr-1;
Mike Stump1eb44332009-09-09 15:08:12 +00001557
Reid Spencer5f016e22007-07-11 17:01:13 +00001558 // Next, lex the character, which should handle the EOM transition.
1559 Lex(Tmp);
Douglas Gregor55817af2010-08-25 17:04:25 +00001560 if (Tmp.is(tok::code_completion)) {
1561 if (PP && PP->getCodeCompletionHandler())
1562 PP->getCodeCompletionHandler()->CodeCompleteNaturalLanguage();
1563 Lex(Tmp);
1564 }
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001565 assert(Tmp.is(tok::eom) && "Unexpected token!");
Mike Stump1eb44332009-09-09 15:08:12 +00001566
Reid Spencer5f016e22007-07-11 17:01:13 +00001567 // Finally, we're done, return the string we found.
1568 return Result;
1569 }
1570 }
1571}
1572
1573/// LexEndOfFile - CurPtr points to the end of this file. Handle this
1574/// condition, reporting diagnostics and handling other edge cases as required.
1575/// This returns true if Result contains a token, false if PP.Lex should be
1576/// called again.
Chris Lattnerd2177732007-07-20 16:59:19 +00001577bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
Douglas Gregorf44e8542010-08-24 19:08:16 +00001578 // Check if we are performing code completion.
1579 if (PP && PP->isCodeCompletionFile(FileLoc)) {
1580 // We're at the end of the file, but we've been asked to consider the
1581 // end of the file to be a code-completion token. Return the
1582 // code-completion token.
1583 Result.startToken();
1584 FormTokenWithChars(Result, CurPtr, tok::code_completion);
1585
1586 // Only do the eof -> code_completion translation once.
1587 PP->SetCodeCompletionPoint(0, 0, 0);
1588
1589 // Silence any diagnostics that occur once we hit the code-completion point.
1590 PP->getDiagnostics().setSuppressAllDiagnostics(true);
1591 return true;
1592 }
1593
Reid Spencer5f016e22007-07-11 17:01:13 +00001594 // If we hit the end of the file while parsing a preprocessor directive,
1595 // end the preprocessor directive first. The next token returned will
1596 // then be the end of file.
1597 if (ParsingPreprocessorDirective) {
1598 // Done parsing the "line".
1599 ParsingPreprocessorDirective = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001600 // Update the location of token as well as BufferPtr.
Chris Lattner9e6293d2008-10-12 04:51:35 +00001601 FormTokenWithChars(Result, CurPtr, tok::eom);
Mike Stump1eb44332009-09-09 15:08:12 +00001602
Reid Spencer5f016e22007-07-11 17:01:13 +00001603 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattnerf744d132008-10-12 03:27:19 +00001604 SetCommentRetentionState(PP->getCommentRetentionState());
Reid Spencer5f016e22007-07-11 17:01:13 +00001605 return true; // Have a token.
Mike Stump1eb44332009-09-09 15:08:12 +00001606 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00001607
Reid Spencer5f016e22007-07-11 17:01:13 +00001608 // If we are in raw mode, return this event as an EOF token. Let the caller
1609 // that put us in raw mode handle the event.
Chris Lattner74d15df2008-11-22 02:02:22 +00001610 if (isLexingRawMode()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001611 Result.startToken();
1612 BufferPtr = BufferEnd;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001613 FormTokenWithChars(Result, BufferEnd, tok::eof);
Reid Spencer5f016e22007-07-11 17:01:13 +00001614 return true;
1615 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00001616
Douglas Gregorf44e8542010-08-24 19:08:16 +00001617 // Issue diagnostics for unterminated #if and missing newline.
1618
Reid Spencer5f016e22007-07-11 17:01:13 +00001619 // If we are in a #if directive, emit an error.
1620 while (!ConditionalStack.empty()) {
Douglas Gregor2d474ba2010-08-12 17:04:55 +00001621 if (!PP->isCodeCompletionFile(FileLoc))
1622 PP->Diag(ConditionalStack.back().IfLoc,
1623 diag::err_pp_unterminated_conditional);
Reid Spencer5f016e22007-07-11 17:01:13 +00001624 ConditionalStack.pop_back();
1625 }
Mike Stump1eb44332009-09-09 15:08:12 +00001626
Chris Lattnerb25e5d72008-04-12 05:54:25 +00001627 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
1628 // a pedwarn.
1629 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r'))
Mike Stump20d0ee52009-04-02 02:29:42 +00001630 Diag(BufferEnd, diag::ext_no_newline_eof)
Douglas Gregor849b2432010-03-31 17:46:05 +00001631 << FixItHint::CreateInsertion(getSourceLocation(BufferEnd), "\n");
Mike Stump1eb44332009-09-09 15:08:12 +00001632
Reid Spencer5f016e22007-07-11 17:01:13 +00001633 BufferPtr = CurPtr;
1634
1635 // Finally, let the preprocessor handle this.
Chris Lattner168ae2d2007-10-17 20:41:00 +00001636 return PP->HandleEndOfFile(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001637}
1638
1639/// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
1640/// the specified lexer will return a tok::l_paren token, 0 if it is something
1641/// else and 2 if there are no more tokens in the buffer controlled by the
1642/// lexer.
1643unsigned Lexer::isNextPPTokenLParen() {
1644 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
Mike Stump1eb44332009-09-09 15:08:12 +00001645
Reid Spencer5f016e22007-07-11 17:01:13 +00001646 // Switch to 'skipping' mode. This will ensure that we can lex a token
1647 // without emitting diagnostics, disables macro expansion, and will cause EOF
1648 // to return an EOF token instead of popping the include stack.
1649 LexingRawMode = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001650
Reid Spencer5f016e22007-07-11 17:01:13 +00001651 // Save state that can be changed while lexing so that we can restore it.
1652 const char *TmpBufferPtr = BufferPtr;
Chris Lattnera864cf72009-04-24 07:15:46 +00001653 bool inPPDirectiveMode = ParsingPreprocessorDirective;
Mike Stump1eb44332009-09-09 15:08:12 +00001654
Chris Lattnerd2177732007-07-20 16:59:19 +00001655 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001656 Tok.startToken();
1657 LexTokenInternal(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001658
Reid Spencer5f016e22007-07-11 17:01:13 +00001659 // Restore state that may have changed.
1660 BufferPtr = TmpBufferPtr;
Chris Lattnera864cf72009-04-24 07:15:46 +00001661 ParsingPreprocessorDirective = inPPDirectiveMode;
Mike Stump1eb44332009-09-09 15:08:12 +00001662
Reid Spencer5f016e22007-07-11 17:01:13 +00001663 // Restore the lexer back to non-skipping mode.
1664 LexingRawMode = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001665
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001666 if (Tok.is(tok::eof))
Reid Spencer5f016e22007-07-11 17:01:13 +00001667 return 2;
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001668 return Tok.is(tok::l_paren);
Reid Spencer5f016e22007-07-11 17:01:13 +00001669}
1670
Chris Lattner34f349d2009-12-14 06:16:57 +00001671/// FindConflictEnd - Find the end of a version control conflict marker.
1672static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd) {
1673 llvm::StringRef RestOfBuffer(CurPtr+7, BufferEnd-CurPtr-7);
1674 size_t Pos = RestOfBuffer.find(">>>>>>>");
1675 while (Pos != llvm::StringRef::npos) {
1676 // Must occur at start of line.
1677 if (RestOfBuffer[Pos-1] != '\r' &&
1678 RestOfBuffer[Pos-1] != '\n') {
1679 RestOfBuffer = RestOfBuffer.substr(Pos+7);
Chris Lattner3d488992010-05-17 20:27:25 +00001680 Pos = RestOfBuffer.find(">>>>>>>");
Chris Lattner34f349d2009-12-14 06:16:57 +00001681 continue;
1682 }
1683 return RestOfBuffer.data()+Pos;
1684 }
1685 return 0;
1686}
1687
1688/// IsStartOfConflictMarker - If the specified pointer is the start of a version
1689/// control conflict marker like '<<<<<<<', recognize it as such, emit an error
1690/// and recover nicely. This returns true if it is a conflict marker and false
1691/// if not.
1692bool Lexer::IsStartOfConflictMarker(const char *CurPtr) {
1693 // Only a conflict marker if it starts at the beginning of a line.
1694 if (CurPtr != BufferStart &&
1695 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
1696 return false;
1697
1698 // Check to see if we have <<<<<<<.
1699 if (BufferEnd-CurPtr < 8 ||
1700 llvm::StringRef(CurPtr, 7) != "<<<<<<<")
1701 return false;
1702
1703 // If we have a situation where we don't care about conflict markers, ignore
1704 // it.
1705 if (IsInConflictMarker || isLexingRawMode())
1706 return false;
1707
1708 // Check to see if there is a >>>>>>> somewhere in the buffer at the start of
1709 // a line to terminate this conflict marker.
Chris Lattner3d488992010-05-17 20:27:25 +00001710 if (FindConflictEnd(CurPtr, BufferEnd)) {
Chris Lattner34f349d2009-12-14 06:16:57 +00001711 // We found a match. We are really in a conflict marker.
1712 // Diagnose this, and ignore to the end of line.
1713 Diag(CurPtr, diag::err_conflict_marker);
1714 IsInConflictMarker = true;
1715
1716 // Skip ahead to the end of line. We know this exists because the
1717 // end-of-conflict marker starts with \r or \n.
1718 while (*CurPtr != '\r' && *CurPtr != '\n') {
1719 assert(CurPtr != BufferEnd && "Didn't find end of line");
1720 ++CurPtr;
1721 }
1722 BufferPtr = CurPtr;
1723 return true;
1724 }
1725
1726 // No end of conflict marker found.
1727 return false;
1728}
1729
1730
1731/// HandleEndOfConflictMarker - If this is a '=======' or '|||||||' or '>>>>>>>'
1732/// marker, then it is the end of a conflict marker. Handle it by ignoring up
1733/// until the end of the line. This returns true if it is a conflict marker and
1734/// false if not.
1735bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) {
1736 // Only a conflict marker if it starts at the beginning of a line.
1737 if (CurPtr != BufferStart &&
1738 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
1739 return false;
1740
1741 // If we have a situation where we don't care about conflict markers, ignore
1742 // it.
1743 if (!IsInConflictMarker || isLexingRawMode())
1744 return false;
1745
1746 // Check to see if we have the marker (7 characters in a row).
1747 for (unsigned i = 1; i != 7; ++i)
1748 if (CurPtr[i] != CurPtr[0])
1749 return false;
1750
1751 // If we do have it, search for the end of the conflict marker. This could
1752 // fail if it got skipped with a '#if 0' or something. Note that CurPtr might
1753 // be the end of conflict marker.
1754 if (const char *End = FindConflictEnd(CurPtr, BufferEnd)) {
1755 CurPtr = End;
1756
1757 // Skip ahead to the end of line.
1758 while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n')
1759 ++CurPtr;
1760
1761 BufferPtr = CurPtr;
1762
1763 // No longer in the conflict marker.
1764 IsInConflictMarker = false;
1765 return true;
1766 }
1767
1768 return false;
1769}
1770
Reid Spencer5f016e22007-07-11 17:01:13 +00001771
1772/// LexTokenInternal - This implements a simple C family lexer. It is an
1773/// extremely performance critical piece of code. This assumes that the buffer
Chris Lattnerefb173d2009-07-07 05:05:42 +00001774/// has a null character at the end of the file. This returns a preprocessing
1775/// token, not a normal token, as such, it is an internal interface. It assumes
1776/// that the Flags of result have been cleared before calling this.
Chris Lattnerd2177732007-07-20 16:59:19 +00001777void Lexer::LexTokenInternal(Token &Result) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001778LexNextToken:
1779 // New token, can't need cleaning yet.
Chris Lattnerd2177732007-07-20 16:59:19 +00001780 Result.clearFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00001781 Result.setIdentifierInfo(0);
Mike Stump1eb44332009-09-09 15:08:12 +00001782
Reid Spencer5f016e22007-07-11 17:01:13 +00001783 // CurPtr - Cache BufferPtr in an automatic variable.
1784 const char *CurPtr = BufferPtr;
1785
1786 // Small amounts of horizontal whitespace is very common between tokens.
1787 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
1788 ++CurPtr;
1789 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
1790 ++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001791
Chris Lattnerd88dc482008-10-12 04:05:48 +00001792 // If we are keeping whitespace and other tokens, just return what we just
1793 // skipped. The next lexer invocation will return the token after the
1794 // whitespace.
1795 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001796 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd88dc482008-10-12 04:05:48 +00001797 return;
1798 }
Mike Stump1eb44332009-09-09 15:08:12 +00001799
Reid Spencer5f016e22007-07-11 17:01:13 +00001800 BufferPtr = CurPtr;
Chris Lattnerd2177732007-07-20 16:59:19 +00001801 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001802 }
Mike Stump1eb44332009-09-09 15:08:12 +00001803
Reid Spencer5f016e22007-07-11 17:01:13 +00001804 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
Mike Stump1eb44332009-09-09 15:08:12 +00001805
Reid Spencer5f016e22007-07-11 17:01:13 +00001806 // Read a character, advancing over it.
1807 char Char = getAndAdvanceChar(CurPtr, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001808 tok::TokenKind Kind;
Mike Stump1eb44332009-09-09 15:08:12 +00001809
Reid Spencer5f016e22007-07-11 17:01:13 +00001810 switch (Char) {
1811 case 0: // Null.
1812 // Found end of file?
1813 if (CurPtr-1 == BufferEnd) {
1814 // Read the PP instance variable into an automatic variable, because
1815 // LexEndOfFile will often delete 'this'.
Chris Lattner168ae2d2007-10-17 20:41:00 +00001816 Preprocessor *PPCache = PP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001817 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
1818 return; // Got a token to return.
Chris Lattner168ae2d2007-10-17 20:41:00 +00001819 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
1820 return PPCache->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001821 }
Mike Stump1eb44332009-09-09 15:08:12 +00001822
Chris Lattner74d15df2008-11-22 02:02:22 +00001823 if (!isLexingRawMode())
1824 Diag(CurPtr-1, diag::null_in_file);
Chris Lattnerd2177732007-07-20 16:59:19 +00001825 Result.setFlag(Token::LeadingSpace);
Chris Lattnerd88dc482008-10-12 04:05:48 +00001826 if (SkipWhitespace(Result, CurPtr))
1827 return; // KeepWhitespaceMode
Mike Stump1eb44332009-09-09 15:08:12 +00001828
Reid Spencer5f016e22007-07-11 17:01:13 +00001829 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattnera2bf1052009-12-17 05:29:40 +00001830
1831 case 26: // DOS & CP/M EOF: "^Z".
1832 // If we're in Microsoft extensions mode, treat this as end of file.
1833 if (Features.Microsoft) {
1834 // Read the PP instance variable into an automatic variable, because
1835 // LexEndOfFile will often delete 'this'.
1836 Preprocessor *PPCache = PP;
1837 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
1838 return; // Got a token to return.
1839 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
1840 return PPCache->Lex(Result);
1841 }
1842 // If Microsoft extensions are disabled, this is just random garbage.
1843 Kind = tok::unknown;
1844 break;
1845
Reid Spencer5f016e22007-07-11 17:01:13 +00001846 case '\n':
1847 case '\r':
1848 // If we are inside a preprocessor directive and we see the end of line,
1849 // we know we are done with the directive, so return an EOM token.
1850 if (ParsingPreprocessorDirective) {
1851 // Done parsing the "line".
1852 ParsingPreprocessorDirective = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001853
Reid Spencer5f016e22007-07-11 17:01:13 +00001854 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattnerf744d132008-10-12 03:27:19 +00001855 SetCommentRetentionState(PP->getCommentRetentionState());
Mike Stump1eb44332009-09-09 15:08:12 +00001856
Reid Spencer5f016e22007-07-11 17:01:13 +00001857 // Since we consumed a newline, we are back at the start of a line.
1858 IsAtStartOfLine = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001859
Chris Lattner9e6293d2008-10-12 04:51:35 +00001860 Kind = tok::eom;
Reid Spencer5f016e22007-07-11 17:01:13 +00001861 break;
1862 }
1863 // The returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00001864 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00001865 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00001866 Result.clearFlag(Token::LeadingSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001867
Chris Lattnerd88dc482008-10-12 04:05:48 +00001868 if (SkipWhitespace(Result, CurPtr))
1869 return; // KeepWhitespaceMode
Reid Spencer5f016e22007-07-11 17:01:13 +00001870 goto LexNextToken; // GCC isn't tail call eliminating.
1871 case ' ':
1872 case '\t':
1873 case '\f':
1874 case '\v':
Chris Lattner8133cfc2007-07-22 06:29:05 +00001875 SkipHorizontalWhitespace:
Chris Lattnerd2177732007-07-20 16:59:19 +00001876 Result.setFlag(Token::LeadingSpace);
Chris Lattnerd88dc482008-10-12 04:05:48 +00001877 if (SkipWhitespace(Result, CurPtr))
1878 return; // KeepWhitespaceMode
Chris Lattner8133cfc2007-07-22 06:29:05 +00001879
1880 SkipIgnoredUnits:
1881 CurPtr = BufferPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001882
Chris Lattner8133cfc2007-07-22 06:29:05 +00001883 // If the next token is obviously a // or /* */ comment, skip it efficiently
1884 // too (without going through the big switch stmt).
Chris Lattner8402c732009-01-16 22:39:25 +00001885 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
1886 Features.BCPLComment) {
Chris Lattner046c2272010-01-18 22:35:47 +00001887 if (SkipBCPLComment(Result, CurPtr+2))
1888 return; // There is a token to return.
Chris Lattner8133cfc2007-07-22 06:29:05 +00001889 goto SkipIgnoredUnits;
Chris Lattnerfa95a012008-10-12 03:22:02 +00001890 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
Chris Lattner046c2272010-01-18 22:35:47 +00001891 if (SkipBlockComment(Result, CurPtr+2))
1892 return; // There is a token to return.
Chris Lattner8133cfc2007-07-22 06:29:05 +00001893 goto SkipIgnoredUnits;
1894 } else if (isHorizontalWhitespace(*CurPtr)) {
1895 goto SkipHorizontalWhitespace;
1896 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001897 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattnera2bf1052009-12-17 05:29:40 +00001898
Chris Lattner3a570772008-01-03 17:58:54 +00001899 // C99 6.4.4.1: Integer Constants.
1900 // C99 6.4.4.2: Floating Constants.
1901 case '0': case '1': case '2': case '3': case '4':
1902 case '5': case '6': case '7': case '8': case '9':
1903 // Notify MIOpt that we read a non-whitespace/non-comment token.
1904 MIOpt.ReadToken();
1905 return LexNumericConstant(Result, CurPtr);
Mike Stump1eb44332009-09-09 15:08:12 +00001906
Chris Lattner3a570772008-01-03 17:58:54 +00001907 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
Reid Spencer5f016e22007-07-11 17:01:13 +00001908 // Notify MIOpt that we read a non-whitespace/non-comment token.
1909 MIOpt.ReadToken();
1910 Char = getCharAndSize(CurPtr, SizeTmp);
1911
1912 // Wide string literal.
1913 if (Char == '"')
1914 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
1915 true);
1916
1917 // Wide character constant.
1918 if (Char == '\'')
1919 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
1920 // FALL THROUGH, treating L like the start of an identifier.
Mike Stump1eb44332009-09-09 15:08:12 +00001921
Reid Spencer5f016e22007-07-11 17:01:13 +00001922 // C99 6.4.2: Identifiers.
1923 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
1924 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
1925 case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U':
1926 case 'V': case 'W': case 'X': case 'Y': case 'Z':
1927 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
1928 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
1929 case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u':
1930 case 'v': case 'w': case 'x': case 'y': case 'z':
1931 case '_':
1932 // Notify MIOpt that we read a non-whitespace/non-comment token.
1933 MIOpt.ReadToken();
1934 return LexIdentifier(Result, CurPtr);
Chris Lattner3a570772008-01-03 17:58:54 +00001935
1936 case '$': // $ in identifiers.
1937 if (Features.DollarIdents) {
Chris Lattner74d15df2008-11-22 02:02:22 +00001938 if (!isLexingRawMode())
1939 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
Chris Lattner3a570772008-01-03 17:58:54 +00001940 // Notify MIOpt that we read a non-whitespace/non-comment token.
1941 MIOpt.ReadToken();
1942 return LexIdentifier(Result, CurPtr);
1943 }
Mike Stump1eb44332009-09-09 15:08:12 +00001944
Chris Lattner9e6293d2008-10-12 04:51:35 +00001945 Kind = tok::unknown;
Chris Lattner3a570772008-01-03 17:58:54 +00001946 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001947
Reid Spencer5f016e22007-07-11 17:01:13 +00001948 // C99 6.4.4: Character Constants.
1949 case '\'':
1950 // Notify MIOpt that we read a non-whitespace/non-comment token.
1951 MIOpt.ReadToken();
1952 return LexCharConstant(Result, CurPtr);
1953
1954 // C99 6.4.5: String Literals.
1955 case '"':
1956 // Notify MIOpt that we read a non-whitespace/non-comment token.
1957 MIOpt.ReadToken();
1958 return LexStringLiteral(Result, CurPtr, false);
1959
1960 // C99 6.4.6: Punctuators.
1961 case '?':
Chris Lattner9e6293d2008-10-12 04:51:35 +00001962 Kind = tok::question;
Reid Spencer5f016e22007-07-11 17:01:13 +00001963 break;
1964 case '[':
Chris Lattner9e6293d2008-10-12 04:51:35 +00001965 Kind = tok::l_square;
Reid Spencer5f016e22007-07-11 17:01:13 +00001966 break;
1967 case ']':
Chris Lattner9e6293d2008-10-12 04:51:35 +00001968 Kind = tok::r_square;
Reid Spencer5f016e22007-07-11 17:01:13 +00001969 break;
1970 case '(':
Chris Lattner9e6293d2008-10-12 04:51:35 +00001971 Kind = tok::l_paren;
Reid Spencer5f016e22007-07-11 17:01:13 +00001972 break;
1973 case ')':
Chris Lattner9e6293d2008-10-12 04:51:35 +00001974 Kind = tok::r_paren;
Reid Spencer5f016e22007-07-11 17:01:13 +00001975 break;
1976 case '{':
Chris Lattner9e6293d2008-10-12 04:51:35 +00001977 Kind = tok::l_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00001978 break;
1979 case '}':
Chris Lattner9e6293d2008-10-12 04:51:35 +00001980 Kind = tok::r_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00001981 break;
1982 case '.':
1983 Char = getCharAndSize(CurPtr, SizeTmp);
1984 if (Char >= '0' && Char <= '9') {
1985 // Notify MIOpt that we read a non-whitespace/non-comment token.
1986 MIOpt.ReadToken();
1987
1988 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
1989 } else if (Features.CPlusPlus && Char == '*') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001990 Kind = tok::periodstar;
Reid Spencer5f016e22007-07-11 17:01:13 +00001991 CurPtr += SizeTmp;
1992 } else if (Char == '.' &&
1993 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001994 Kind = tok::ellipsis;
Reid Spencer5f016e22007-07-11 17:01:13 +00001995 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1996 SizeTmp2, Result);
1997 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001998 Kind = tok::period;
Reid Spencer5f016e22007-07-11 17:01:13 +00001999 }
2000 break;
2001 case '&':
2002 Char = getCharAndSize(CurPtr, SizeTmp);
2003 if (Char == '&') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002004 Kind = tok::ampamp;
Reid Spencer5f016e22007-07-11 17:01:13 +00002005 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2006 } else if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002007 Kind = tok::ampequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002008 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2009 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002010 Kind = tok::amp;
Reid Spencer5f016e22007-07-11 17:01:13 +00002011 }
2012 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002013 case '*':
Reid Spencer5f016e22007-07-11 17:01:13 +00002014 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002015 Kind = tok::starequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002016 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2017 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002018 Kind = tok::star;
Reid Spencer5f016e22007-07-11 17:01:13 +00002019 }
2020 break;
2021 case '+':
2022 Char = getCharAndSize(CurPtr, SizeTmp);
2023 if (Char == '+') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002024 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002025 Kind = tok::plusplus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002026 } else if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002027 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002028 Kind = tok::plusequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002029 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002030 Kind = tok::plus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002031 }
2032 break;
2033 case '-':
2034 Char = getCharAndSize(CurPtr, SizeTmp);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002035 if (Char == '-') { // --
Reid Spencer5f016e22007-07-11 17:01:13 +00002036 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002037 Kind = tok::minusminus;
Mike Stump1eb44332009-09-09 15:08:12 +00002038 } else if (Char == '>' && Features.CPlusPlus &&
Chris Lattner9e6293d2008-10-12 04:51:35 +00002039 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
Reid Spencer5f016e22007-07-11 17:01:13 +00002040 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2041 SizeTmp2, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002042 Kind = tok::arrowstar;
2043 } else if (Char == '>') { // ->
Reid Spencer5f016e22007-07-11 17:01:13 +00002044 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002045 Kind = tok::arrow;
2046 } else if (Char == '=') { // -=
Reid Spencer5f016e22007-07-11 17:01:13 +00002047 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002048 Kind = tok::minusequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002049 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002050 Kind = tok::minus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002051 }
2052 break;
2053 case '~':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002054 Kind = tok::tilde;
Reid Spencer5f016e22007-07-11 17:01:13 +00002055 break;
2056 case '!':
2057 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002058 Kind = tok::exclaimequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002059 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2060 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002061 Kind = tok::exclaim;
Reid Spencer5f016e22007-07-11 17:01:13 +00002062 }
2063 break;
2064 case '/':
2065 // 6.4.9: Comments
2066 Char = getCharAndSize(CurPtr, SizeTmp);
2067 if (Char == '/') { // BCPL comment.
Chris Lattner8402c732009-01-16 22:39:25 +00002068 // Even if BCPL comments are disabled (e.g. in C89 mode), we generally
2069 // want to lex this as a comment. There is one problem with this though,
2070 // that in one particular corner case, this can change the behavior of the
2071 // resultant program. For example, In "foo //**/ bar", C89 would lex
2072 // this as "foo / bar" and langauges with BCPL comments would lex it as
2073 // "foo". Check to see if the character after the second slash is a '*'.
2074 // If so, we will lex that as a "/" instead of the start of a comment.
2075 if (Features.BCPLComment ||
2076 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*') {
2077 if (SkipBCPLComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattner046c2272010-01-18 22:35:47 +00002078 return; // There is a token to return.
Mike Stump1eb44332009-09-09 15:08:12 +00002079
Chris Lattner8402c732009-01-16 22:39:25 +00002080 // It is common for the tokens immediately after a // comment to be
2081 // whitespace (indentation for the next line). Instead of going through
2082 // the big switch, handle it efficiently now.
2083 goto SkipIgnoredUnits;
2084 }
2085 }
Mike Stump1eb44332009-09-09 15:08:12 +00002086
Chris Lattner8402c732009-01-16 22:39:25 +00002087 if (Char == '*') { // /**/ comment.
Reid Spencer5f016e22007-07-11 17:01:13 +00002088 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattner046c2272010-01-18 22:35:47 +00002089 return; // There is a token to return.
Chris Lattner2d381892008-10-12 04:15:42 +00002090 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattner8402c732009-01-16 22:39:25 +00002091 }
Mike Stump1eb44332009-09-09 15:08:12 +00002092
Chris Lattner8402c732009-01-16 22:39:25 +00002093 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002094 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002095 Kind = tok::slashequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002096 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002097 Kind = tok::slash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002098 }
2099 break;
2100 case '%':
2101 Char = getCharAndSize(CurPtr, SizeTmp);
2102 if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002103 Kind = tok::percentequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002104 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2105 } else if (Features.Digraphs && Char == '>') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002106 Kind = tok::r_brace; // '%>' -> '}'
Reid Spencer5f016e22007-07-11 17:01:13 +00002107 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2108 } else if (Features.Digraphs && Char == ':') {
2109 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2110 Char = getCharAndSize(CurPtr, SizeTmp);
2111 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002112 Kind = tok::hashhash; // '%:%:' -> '##'
Reid Spencer5f016e22007-07-11 17:01:13 +00002113 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2114 SizeTmp2, Result);
2115 } else if (Char == '@' && Features.Microsoft) { // %:@ -> #@ -> Charize
Reid Spencer5f016e22007-07-11 17:01:13 +00002116 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner74d15df2008-11-22 02:02:22 +00002117 if (!isLexingRawMode())
2118 Diag(BufferPtr, diag::charize_microsoft_ext);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002119 Kind = tok::hashat;
Chris Lattnere91e9322009-03-18 20:58:27 +00002120 } else { // '%:' -> '#'
Reid Spencer5f016e22007-07-11 17:01:13 +00002121 // We parsed a # character. If this occurs at the start of the line,
2122 // it's actually the start of a preprocessing directive. Callback to
2123 // the preprocessor to handle it.
2124 // FIXME: -fpreprocessed mode??
Chris Lattner766703b2009-05-13 06:10:29 +00002125 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer) {
Chris Lattnere91e9322009-03-18 20:58:27 +00002126 FormTokenWithChars(Result, CurPtr, tok::hash);
Chris Lattner168ae2d2007-10-17 20:41:00 +00002127 PP->HandleDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00002128
Reid Spencer5f016e22007-07-11 17:01:13 +00002129 // As an optimization, if the preprocessor didn't switch lexers, tail
2130 // recurse.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002131 if (PP->isCurrentLexer(this)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002132 // Start a new token. If this is a #include or something, the PP may
2133 // want us starting at the beginning of the line again. If so, set
Chris Lattner515f43f2010-04-12 23:04:41 +00002134 // the StartOfLine flag and clear LeadingSpace.
Reid Spencer5f016e22007-07-11 17:01:13 +00002135 if (IsAtStartOfLine) {
Chris Lattnerd2177732007-07-20 16:59:19 +00002136 Result.setFlag(Token::StartOfLine);
Chris Lattner515f43f2010-04-12 23:04:41 +00002137 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002138 IsAtStartOfLine = false;
2139 }
2140 goto LexNextToken; // GCC isn't tail call eliminating.
2141 }
Mike Stump1eb44332009-09-09 15:08:12 +00002142
Chris Lattner168ae2d2007-10-17 20:41:00 +00002143 return PP->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002144 }
Mike Stump1eb44332009-09-09 15:08:12 +00002145
Chris Lattnere91e9322009-03-18 20:58:27 +00002146 Kind = tok::hash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002147 }
2148 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002149 Kind = tok::percent;
Reid Spencer5f016e22007-07-11 17:01:13 +00002150 }
2151 break;
2152 case '<':
2153 Char = getCharAndSize(CurPtr, SizeTmp);
2154 if (ParsingFilename) {
Chris Lattner9cb51ce2009-04-17 23:56:52 +00002155 return LexAngledStringLiteral(Result, CurPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +00002156 } else if (Char == '<') {
Chris Lattner34f349d2009-12-14 06:16:57 +00002157 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
2158 if (After == '=') {
2159 Kind = tok::lesslessequal;
2160 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2161 SizeTmp2, Result);
2162 } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) {
2163 // If this is actually a '<<<<<<<' version control conflict marker,
2164 // recognize it as such and recover nicely.
2165 goto LexNextToken;
2166 } else {
2167 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2168 Kind = tok::lessless;
2169 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002170 } else if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002171 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002172 Kind = tok::lessequal;
2173 } else if (Features.Digraphs && Char == ':') { // '<:' -> '['
Reid Spencer5f016e22007-07-11 17:01:13 +00002174 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002175 Kind = tok::l_square;
2176 } else if (Features.Digraphs && Char == '%') { // '<%' -> '{'
Reid Spencer5f016e22007-07-11 17:01:13 +00002177 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002178 Kind = tok::l_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00002179 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002180 Kind = tok::less;
Reid Spencer5f016e22007-07-11 17:01:13 +00002181 }
2182 break;
2183 case '>':
2184 Char = getCharAndSize(CurPtr, SizeTmp);
2185 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002186 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002187 Kind = tok::greaterequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002188 } else if (Char == '>') {
Chris Lattner34f349d2009-12-14 06:16:57 +00002189 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
2190 if (After == '=') {
2191 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2192 SizeTmp2, Result);
2193 Kind = tok::greatergreaterequal;
2194 } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) {
2195 // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
2196 goto LexNextToken;
2197 } else {
2198 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2199 Kind = tok::greatergreater;
2200 }
2201
Reid Spencer5f016e22007-07-11 17:01:13 +00002202 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002203 Kind = tok::greater;
Reid Spencer5f016e22007-07-11 17:01:13 +00002204 }
2205 break;
2206 case '^':
2207 Char = getCharAndSize(CurPtr, SizeTmp);
2208 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002209 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002210 Kind = tok::caretequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002211 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002212 Kind = tok::caret;
Reid Spencer5f016e22007-07-11 17:01:13 +00002213 }
2214 break;
2215 case '|':
2216 Char = getCharAndSize(CurPtr, SizeTmp);
2217 if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002218 Kind = tok::pipeequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002219 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2220 } else if (Char == '|') {
Chris Lattner34f349d2009-12-14 06:16:57 +00002221 // If this is '|||||||' and we're in a conflict marker, ignore it.
2222 if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
2223 goto LexNextToken;
Chris Lattner9e6293d2008-10-12 04:51:35 +00002224 Kind = tok::pipepipe;
Reid Spencer5f016e22007-07-11 17:01:13 +00002225 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2226 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002227 Kind = tok::pipe;
Reid Spencer5f016e22007-07-11 17:01:13 +00002228 }
2229 break;
2230 case ':':
2231 Char = getCharAndSize(CurPtr, SizeTmp);
2232 if (Features.Digraphs && Char == '>') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002233 Kind = tok::r_square; // ':>' -> ']'
Reid Spencer5f016e22007-07-11 17:01:13 +00002234 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2235 } else if (Features.CPlusPlus && Char == ':') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002236 Kind = tok::coloncolon;
Reid Spencer5f016e22007-07-11 17:01:13 +00002237 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump1eb44332009-09-09 15:08:12 +00002238 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002239 Kind = tok::colon;
Reid Spencer5f016e22007-07-11 17:01:13 +00002240 }
2241 break;
2242 case ';':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002243 Kind = tok::semi;
Reid Spencer5f016e22007-07-11 17:01:13 +00002244 break;
2245 case '=':
2246 Char = getCharAndSize(CurPtr, SizeTmp);
2247 if (Char == '=') {
Chris Lattner34f349d2009-12-14 06:16:57 +00002248 // If this is '=======' and we're in a conflict marker, ignore it.
2249 if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
2250 goto LexNextToken;
2251
Chris Lattner9e6293d2008-10-12 04:51:35 +00002252 Kind = tok::equalequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002253 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump1eb44332009-09-09 15:08:12 +00002254 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002255 Kind = tok::equal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002256 }
2257 break;
2258 case ',':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002259 Kind = tok::comma;
Reid Spencer5f016e22007-07-11 17:01:13 +00002260 break;
2261 case '#':
2262 Char = getCharAndSize(CurPtr, SizeTmp);
2263 if (Char == '#') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002264 Kind = tok::hashhash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002265 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2266 } else if (Char == '@' && Features.Microsoft) { // #@ -> Charize
Chris Lattner9e6293d2008-10-12 04:51:35 +00002267 Kind = tok::hashat;
Chris Lattner74d15df2008-11-22 02:02:22 +00002268 if (!isLexingRawMode())
2269 Diag(BufferPtr, diag::charize_microsoft_ext);
Reid Spencer5f016e22007-07-11 17:01:13 +00002270 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2271 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +00002272 // We parsed a # character. If this occurs at the start of the line,
2273 // it's actually the start of a preprocessing directive. Callback to
2274 // the preprocessor to handle it.
2275 // FIXME: -fpreprocessed mode??
Chris Lattner766703b2009-05-13 06:10:29 +00002276 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer) {
Chris Lattnere91e9322009-03-18 20:58:27 +00002277 FormTokenWithChars(Result, CurPtr, tok::hash);
Chris Lattner168ae2d2007-10-17 20:41:00 +00002278 PP->HandleDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00002279
Reid Spencer5f016e22007-07-11 17:01:13 +00002280 // As an optimization, if the preprocessor didn't switch lexers, tail
2281 // recurse.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002282 if (PP->isCurrentLexer(this)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002283 // Start a new token. If this is a #include or something, the PP may
2284 // want us starting at the beginning of the line again. If so, set
Chris Lattner515f43f2010-04-12 23:04:41 +00002285 // the StartOfLine flag and clear LeadingSpace.
Reid Spencer5f016e22007-07-11 17:01:13 +00002286 if (IsAtStartOfLine) {
Chris Lattnerd2177732007-07-20 16:59:19 +00002287 Result.setFlag(Token::StartOfLine);
Chris Lattner515f43f2010-04-12 23:04:41 +00002288 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002289 IsAtStartOfLine = false;
2290 }
2291 goto LexNextToken; // GCC isn't tail call eliminating.
2292 }
Chris Lattner168ae2d2007-10-17 20:41:00 +00002293 return PP->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002294 }
Mike Stump1eb44332009-09-09 15:08:12 +00002295
Chris Lattnere91e9322009-03-18 20:58:27 +00002296 Kind = tok::hash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002297 }
2298 break;
2299
Chris Lattner3a570772008-01-03 17:58:54 +00002300 case '@':
2301 // Objective C support.
2302 if (CurPtr[-1] == '@' && Features.ObjC1)
Chris Lattner9e6293d2008-10-12 04:51:35 +00002303 Kind = tok::at;
Chris Lattner3a570772008-01-03 17:58:54 +00002304 else
Chris Lattner9e6293d2008-10-12 04:51:35 +00002305 Kind = tok::unknown;
Chris Lattner3a570772008-01-03 17:58:54 +00002306 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002307
Reid Spencer5f016e22007-07-11 17:01:13 +00002308 case '\\':
2309 // FIXME: UCN's.
2310 // FALL THROUGH.
2311 default:
Chris Lattner9e6293d2008-10-12 04:51:35 +00002312 Kind = tok::unknown;
Reid Spencer5f016e22007-07-11 17:01:13 +00002313 break;
2314 }
Mike Stump1eb44332009-09-09 15:08:12 +00002315
Reid Spencer5f016e22007-07-11 17:01:13 +00002316 // Notify MIOpt that we read a non-whitespace/non-comment token.
2317 MIOpt.ReadToken();
2318
2319 // Update the location of token as well as BufferPtr.
Chris Lattner9e6293d2008-10-12 04:51:35 +00002320 FormTokenWithChars(Result, CurPtr, Kind);
Reid Spencer5f016e22007-07-11 17:01:13 +00002321}