blob: ad3d35af6bf9e7af2ea3ce61b4891da01726d46f [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.
Sebastian Redlc3526d82010-09-30 01:03:03 +0000245 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts,
246 Buffer.begin(), StrData, Buffer.end());
Chris Lattner39de7402009-10-14 15:04:18 +0000247 TheLexer.SetCommentRetentionState(true);
Chris Lattner9a611942007-10-17 21:18:47 +0000248 Token TheTok;
Chris Lattner590f0cc2008-10-12 01:15:46 +0000249 TheLexer.LexFromRawLexer(TheTok);
Chris Lattner9a611942007-10-17 21:18:47 +0000250 return TheTok.getLength();
251}
252
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000253SourceLocation Lexer::GetBeginningOfToken(SourceLocation Loc,
254 const SourceManager &SM,
255 const LangOptions &LangOpts) {
256 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
257 bool Invalid = false;
258 llvm::StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
259 if (Invalid)
260 return Loc;
261
262 // Back up from the current location until we hit the beginning of a line
263 // (or the buffer). We'll relex from that point.
264 const char *BufStart = Buffer.data();
265 const char *StrData = BufStart+LocInfo.second;
266 if (StrData[0] == '\n' || StrData[0] == '\r')
267 return Loc;
268
269 const char *LexStart = StrData;
270 while (LexStart != BufStart) {
271 if (LexStart[0] == '\n' || LexStart[0] == '\r') {
272 ++LexStart;
273 break;
274 }
275
276 --LexStart;
277 }
278
279 // Create a lexer starting at the beginning of this token.
280 SourceLocation LexerStartLoc = Loc.getFileLocWithOffset(-LocInfo.second);
281 Lexer TheLexer(LexerStartLoc, LangOpts, BufStart, LexStart, Buffer.end());
282 TheLexer.SetCommentRetentionState(true);
283
284 // Lex tokens until we find the token that contains the source location.
285 Token TheTok;
286 do {
287 TheLexer.LexFromRawLexer(TheTok);
288
289 if (TheLexer.getBufferLocation() > StrData) {
290 // Lexing this token has taken the lexer past the source location we're
291 // looking for. If the current token encompasses our source location,
292 // return the beginning of that token.
293 if (TheLexer.getBufferLocation() - TheTok.getLength() <= StrData)
294 return TheTok.getLocation();
295
296 // We ended up skipping over the source location entirely, which means
297 // that it points into whitespace. We're done here.
298 break;
299 }
300 } while (TheTok.getKind() != tok::eof);
301
302 // We've passed our source location; just return the original source location.
303 return Loc;
304}
305
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000306namespace {
307 enum PreambleDirectiveKind {
308 PDK_Skipped,
309 PDK_StartIf,
310 PDK_EndIf,
311 PDK_Unknown
312 };
313}
314
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000315std::pair<unsigned, bool>
Douglas Gregordf95a132010-08-09 20:45:32 +0000316Lexer::ComputePreamble(const llvm::MemoryBuffer *Buffer, unsigned MaxLines) {
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000317 // Create a lexer starting at the beginning of the file. Note that we use a
318 // "fake" file source location at offset 1 so that the lexer will track our
319 // position within the file.
320 const unsigned StartOffset = 1;
321 SourceLocation StartLoc = SourceLocation::getFromRawEncoding(StartOffset);
322 LangOptions LangOpts;
323 Lexer TheLexer(StartLoc, LangOpts, Buffer->getBufferStart(),
324 Buffer->getBufferStart(), Buffer->getBufferEnd());
325
326 bool InPreprocessorDirective = false;
327 Token TheTok;
328 Token IfStartTok;
329 unsigned IfCount = 0;
Douglas Gregordf95a132010-08-09 20:45:32 +0000330 unsigned Line = 0;
331
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000332 do {
333 TheLexer.LexFromRawLexer(TheTok);
334
335 if (InPreprocessorDirective) {
336 // If we've hit the end of the file, we're done.
337 if (TheTok.getKind() == tok::eof) {
338 InPreprocessorDirective = false;
339 break;
340 }
341
342 // If we haven't hit the end of the preprocessor directive, skip this
343 // token.
344 if (!TheTok.isAtStartOfLine())
345 continue;
346
347 // We've passed the end of the preprocessor directive, and will look
348 // at this token again below.
349 InPreprocessorDirective = false;
350 }
351
Douglas Gregordf95a132010-08-09 20:45:32 +0000352 // Keep track of the # of lines in the preamble.
353 if (TheTok.isAtStartOfLine()) {
354 ++Line;
355
356 // If we were asked to limit the number of lines in the preamble,
357 // and we're about to exceed that limit, we're done.
358 if (MaxLines && Line >= MaxLines)
359 break;
360 }
361
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000362 // Comments are okay; skip over them.
363 if (TheTok.getKind() == tok::comment)
364 continue;
365
366 if (TheTok.isAtStartOfLine() && TheTok.getKind() == tok::hash) {
367 // This is the start of a preprocessor directive.
368 Token HashTok = TheTok;
369 InPreprocessorDirective = true;
370
371 // Figure out which direective this is. Since we're lexing raw tokens,
372 // we don't have an identifier table available. Instead, just look at
373 // the raw identifier to recognize and categorize preprocessor directives.
374 TheLexer.LexFromRawLexer(TheTok);
375 if (TheTok.getKind() == tok::identifier && !TheTok.needsCleaning()) {
376 const char *IdStart = Buffer->getBufferStart()
377 + TheTok.getLocation().getRawEncoding() - 1;
378 llvm::StringRef Keyword(IdStart, TheTok.getLength());
379 PreambleDirectiveKind PDK
380 = llvm::StringSwitch<PreambleDirectiveKind>(Keyword)
381 .Case("include", PDK_Skipped)
382 .Case("__include_macros", PDK_Skipped)
383 .Case("define", PDK_Skipped)
384 .Case("undef", PDK_Skipped)
385 .Case("line", PDK_Skipped)
386 .Case("error", PDK_Skipped)
387 .Case("pragma", PDK_Skipped)
388 .Case("import", PDK_Skipped)
389 .Case("include_next", PDK_Skipped)
390 .Case("warning", PDK_Skipped)
391 .Case("ident", PDK_Skipped)
392 .Case("sccs", PDK_Skipped)
393 .Case("assert", PDK_Skipped)
394 .Case("unassert", PDK_Skipped)
395 .Case("if", PDK_StartIf)
396 .Case("ifdef", PDK_StartIf)
397 .Case("ifndef", PDK_StartIf)
398 .Case("elif", PDK_Skipped)
399 .Case("else", PDK_Skipped)
400 .Case("endif", PDK_EndIf)
401 .Default(PDK_Unknown);
402
403 switch (PDK) {
404 case PDK_Skipped:
405 continue;
406
407 case PDK_StartIf:
408 if (IfCount == 0)
409 IfStartTok = HashTok;
410
411 ++IfCount;
412 continue;
413
414 case PDK_EndIf:
415 // Mismatched #endif. The preamble ends here.
416 if (IfCount == 0)
417 break;
418
419 --IfCount;
420 continue;
421
422 case PDK_Unknown:
423 // We don't know what this directive is; stop at the '#'.
424 break;
425 }
426 }
427
428 // We only end up here if we didn't recognize the preprocessor
429 // directive or it was one that can't occur in the preamble at this
430 // point. Roll back the current token to the location of the '#'.
431 InPreprocessorDirective = false;
432 TheTok = HashTok;
433 }
434
Douglas Gregordf95a132010-08-09 20:45:32 +0000435 // We hit a token that we don't recognize as being in the
436 // "preprocessing only" part of the file, so we're no longer in
437 // the preamble.
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000438 break;
439 } while (true);
440
441 SourceLocation End = IfCount? IfStartTok.getLocation() : TheTok.getLocation();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000442 return std::make_pair(End.getRawEncoding() - StartLoc.getRawEncoding(),
443 IfCount? IfStartTok.isAtStartOfLine()
444 : TheTok.isAtStartOfLine());
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000445}
446
Reid Spencer5f016e22007-07-11 17:01:13 +0000447//===----------------------------------------------------------------------===//
448// Character information.
449//===----------------------------------------------------------------------===//
450
Reid Spencer5f016e22007-07-11 17:01:13 +0000451enum {
452 CHAR_HORZ_WS = 0x01, // ' ', '\t', '\f', '\v'. Note, no '\0'
453 CHAR_VERT_WS = 0x02, // '\r', '\n'
454 CHAR_LETTER = 0x04, // a-z,A-Z
455 CHAR_NUMBER = 0x08, // 0-9
456 CHAR_UNDER = 0x10, // _
457 CHAR_PERIOD = 0x20 // .
458};
459
Chris Lattner03b98662009-07-07 17:09:54 +0000460// Statically initialize CharInfo table based on ASCII character set
461// Reference: FreeBSD 7.2 /usr/share/misc/ascii
Chris Lattnera2bf1052009-12-17 05:29:40 +0000462static const unsigned char CharInfo[256] =
Chris Lattner03b98662009-07-07 17:09:54 +0000463{
464// 0 NUL 1 SOH 2 STX 3 ETX
465// 4 EOT 5 ENQ 6 ACK 7 BEL
466 0 , 0 , 0 , 0 ,
467 0 , 0 , 0 , 0 ,
468// 8 BS 9 HT 10 NL 11 VT
469//12 NP 13 CR 14 SO 15 SI
470 0 , CHAR_HORZ_WS, CHAR_VERT_WS, CHAR_HORZ_WS,
471 CHAR_HORZ_WS, CHAR_VERT_WS, 0 , 0 ,
472//16 DLE 17 DC1 18 DC2 19 DC3
473//20 DC4 21 NAK 22 SYN 23 ETB
474 0 , 0 , 0 , 0 ,
475 0 , 0 , 0 , 0 ,
476//24 CAN 25 EM 26 SUB 27 ESC
477//28 FS 29 GS 30 RS 31 US
478 0 , 0 , 0 , 0 ,
479 0 , 0 , 0 , 0 ,
480//32 SP 33 ! 34 " 35 #
481//36 $ 37 % 38 & 39 '
482 CHAR_HORZ_WS, 0 , 0 , 0 ,
483 0 , 0 , 0 , 0 ,
484//40 ( 41 ) 42 * 43 +
485//44 , 45 - 46 . 47 /
486 0 , 0 , 0 , 0 ,
487 0 , 0 , CHAR_PERIOD , 0 ,
488//48 0 49 1 50 2 51 3
489//52 4 53 5 54 6 55 7
490 CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER ,
491 CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER ,
492//56 8 57 9 58 : 59 ;
493//60 < 61 = 62 > 63 ?
494 CHAR_NUMBER , CHAR_NUMBER , 0 , 0 ,
495 0 , 0 , 0 , 0 ,
496//64 @ 65 A 66 B 67 C
497//68 D 69 E 70 F 71 G
498 0 , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
499 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
500//72 H 73 I 74 J 75 K
501//76 L 77 M 78 N 79 O
502 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
503 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
504//80 P 81 Q 82 R 83 S
505//84 T 85 U 86 V 87 W
506 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
507 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
508//88 X 89 Y 90 Z 91 [
509//92 \ 93 ] 94 ^ 95 _
510 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , 0 ,
511 0 , 0 , 0 , CHAR_UNDER ,
512//96 ` 97 a 98 b 99 c
513//100 d 101 e 102 f 103 g
514 0 , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
515 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
516//104 h 105 i 106 j 107 k
517//108 l 109 m 110 n 111 o
518 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
519 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
520//112 p 113 q 114 r 115 s
521//116 t 117 u 118 v 119 w
522 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
523 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
524//120 x 121 y 122 z 123 {
525//124 | 125 } 126 ~ 127 DEL
526 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , 0 ,
527 0 , 0 , 0 , 0
528};
529
Chris Lattnera2bf1052009-12-17 05:29:40 +0000530static void InitCharacterInfo() {
Reid Spencer5f016e22007-07-11 17:01:13 +0000531 static bool isInited = false;
532 if (isInited) return;
Chris Lattner03b98662009-07-07 17:09:54 +0000533 // check the statically-initialized CharInfo table
534 assert(CHAR_HORZ_WS == CharInfo[(int)' ']);
535 assert(CHAR_HORZ_WS == CharInfo[(int)'\t']);
536 assert(CHAR_HORZ_WS == CharInfo[(int)'\f']);
537 assert(CHAR_HORZ_WS == CharInfo[(int)'\v']);
538 assert(CHAR_VERT_WS == CharInfo[(int)'\n']);
539 assert(CHAR_VERT_WS == CharInfo[(int)'\r']);
540 assert(CHAR_UNDER == CharInfo[(int)'_']);
541 assert(CHAR_PERIOD == CharInfo[(int)'.']);
542 for (unsigned i = 'a'; i <= 'z'; ++i) {
543 assert(CHAR_LETTER == CharInfo[i]);
544 assert(CHAR_LETTER == CharInfo[i+'A'-'a']);
545 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000546 for (unsigned i = '0'; i <= '9'; ++i)
Chris Lattner03b98662009-07-07 17:09:54 +0000547 assert(CHAR_NUMBER == CharInfo[i]);
Steve Naroff7b682652009-12-08 16:38:12 +0000548
Chris Lattner03b98662009-07-07 17:09:54 +0000549 isInited = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000550}
551
Chris Lattner03b98662009-07-07 17:09:54 +0000552
Reid Spencer5f016e22007-07-11 17:01:13 +0000553/// isIdentifierBody - Return true if this is the body character of an
554/// identifier, which is [a-zA-Z0-9_].
555static inline bool isIdentifierBody(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000556 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER)) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000557}
558
559/// isHorizontalWhitespace - Return true if this character is horizontal
560/// whitespace: ' ', '\t', '\f', '\v'. Note that this returns false for '\0'.
561static inline bool isHorizontalWhitespace(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000562 return (CharInfo[c] & CHAR_HORZ_WS) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000563}
564
565/// isWhitespace - Return true if this character is horizontal or vertical
566/// whitespace: ' ', '\t', '\f', '\v', '\n', '\r'. Note that this returns false
567/// for '\0'.
568static inline bool isWhitespace(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000569 return (CharInfo[c] & (CHAR_HORZ_WS|CHAR_VERT_WS)) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000570}
571
572/// isNumberBody - Return true if this is the body character of an
573/// preprocessing number, which is [a-zA-Z0-9_.].
574static inline bool isNumberBody(unsigned char c) {
Mike Stump1eb44332009-09-09 15:08:12 +0000575 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER|CHAR_PERIOD)) ?
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000576 true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000577}
578
579
580//===----------------------------------------------------------------------===//
581// Diagnostics forwarding code.
582//===----------------------------------------------------------------------===//
583
Chris Lattner409a0362007-07-22 18:38:25 +0000584/// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
585/// lexer buffer was all instantiated at a single point, perform the mapping.
586/// This is currently only used for _Pragma implementation, so it is the slow
587/// path of the hot getSourceLocation method. Do not allow it to be inlined.
Chandler Carruth14bd9652010-10-23 08:44:57 +0000588static LLVM_ATTRIBUTE_NOINLINE SourceLocation GetMappedTokenLoc(
589 Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen);
Chris Lattner409a0362007-07-22 18:38:25 +0000590static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
591 SourceLocation FileLoc,
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000592 unsigned CharNo, unsigned TokLen) {
Chris Lattnere7fb4842009-02-15 20:52:18 +0000593 assert(FileLoc.isMacroID() && "Must be an instantiation");
Mike Stump1eb44332009-09-09 15:08:12 +0000594
Chris Lattner409a0362007-07-22 18:38:25 +0000595 // Otherwise, we're lexing "mapped tokens". This is used for things like
596 // _Pragma handling. Combine the instantiation location of FileLoc with the
Chris Lattnerdf7c17a2009-01-16 07:00:02 +0000597 // spelling location.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000598 SourceManager &SM = PP.getSourceManager();
Mike Stump1eb44332009-09-09 15:08:12 +0000599
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000600 // Create a new SLoc which is expanded from Instantiation(FileLoc) but whose
Chris Lattnerdf7c17a2009-01-16 07:00:02 +0000601 // characters come from spelling(FileLoc)+Offset.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000602 SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc);
Chris Lattnerbcc2a672009-01-19 06:46:35 +0000603 SpellingLoc = SpellingLoc.getFileLocWithOffset(CharNo);
Mike Stump1eb44332009-09-09 15:08:12 +0000604
Chris Lattnere7fb4842009-02-15 20:52:18 +0000605 // Figure out the expansion loc range, which is the range covered by the
606 // original _Pragma(...) sequence.
607 std::pair<SourceLocation,SourceLocation> II =
608 SM.getImmediateInstantiationRange(FileLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000609
Chris Lattnere7fb4842009-02-15 20:52:18 +0000610 return SM.createInstantiationLoc(SpellingLoc, II.first, II.second, TokLen);
Chris Lattner409a0362007-07-22 18:38:25 +0000611}
612
Reid Spencer5f016e22007-07-11 17:01:13 +0000613/// getSourceLocation - Return a source location identifier for the specified
614/// offset in the current file.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000615SourceLocation Lexer::getSourceLocation(const char *Loc,
616 unsigned TokLen) const {
Chris Lattner448cec42007-07-22 18:44:36 +0000617 assert(Loc >= BufferStart && Loc <= BufferEnd &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000618 "Location out of range for this buffer!");
Chris Lattner9dc1f532007-07-20 16:37:10 +0000619
620 // In the normal case, we're just lexing from a simple file buffer, return
621 // the file id from FileLoc with the offset specified.
Chris Lattner448cec42007-07-22 18:44:36 +0000622 unsigned CharNo = Loc-BufferStart;
Chris Lattner9dc1f532007-07-20 16:37:10 +0000623 if (FileLoc.isFileID())
Chris Lattnerbcc2a672009-01-19 06:46:35 +0000624 return FileLoc.getFileLocWithOffset(CharNo);
Mike Stump1eb44332009-09-09 15:08:12 +0000625
Chris Lattner2b2453a2009-01-17 06:22:33 +0000626 // Otherwise, this is the _Pragma lexer case, which pretends that all of the
627 // tokens are lexed from where the _Pragma was defined.
Chris Lattner168ae2d2007-10-17 20:41:00 +0000628 assert(PP && "This doesn't work on raw lexers");
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000629 return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen);
Reid Spencer5f016e22007-07-11 17:01:13 +0000630}
631
Reid Spencer5f016e22007-07-11 17:01:13 +0000632/// Diag - Forwarding function for diagnostics. This translate a source
633/// position in the current buffer into a SourceLocation object for rendering.
Chris Lattner3cbfe2c2008-11-22 00:59:29 +0000634DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
Chris Lattner3692b092008-11-18 07:59:24 +0000635 return PP->Diag(getSourceLocation(Loc), DiagID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000636}
Reid Spencer5f016e22007-07-11 17:01:13 +0000637
638//===----------------------------------------------------------------------===//
639// Trigraph and Escaped Newline Handling Code.
640//===----------------------------------------------------------------------===//
641
642/// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
643/// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
644static char GetTrigraphCharForLetter(char Letter) {
645 switch (Letter) {
646 default: return 0;
647 case '=': return '#';
648 case ')': return ']';
649 case '(': return '[';
650 case '!': return '|';
651 case '\'': return '^';
652 case '>': return '}';
653 case '/': return '\\';
654 case '<': return '{';
655 case '-': return '~';
656 }
657}
658
659/// DecodeTrigraphChar - If the specified character is a legal trigraph when
660/// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
661/// return the result character. Finally, emit a warning about trigraph use
662/// whether trigraphs are enabled or not.
663static char DecodeTrigraphChar(const char *CP, Lexer *L) {
664 char Res = GetTrigraphCharForLetter(*CP);
Chris Lattner3692b092008-11-18 07:59:24 +0000665 if (!Res || !L) return Res;
Mike Stump1eb44332009-09-09 15:08:12 +0000666
Chris Lattner3692b092008-11-18 07:59:24 +0000667 if (!L->getFeatures().Trigraphs) {
Chris Lattner74d15df2008-11-22 02:02:22 +0000668 if (!L->isLexingRawMode())
669 L->Diag(CP-2, diag::trigraph_ignored);
Chris Lattner3692b092008-11-18 07:59:24 +0000670 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000671 }
Mike Stump1eb44332009-09-09 15:08:12 +0000672
Chris Lattner74d15df2008-11-22 02:02:22 +0000673 if (!L->isLexingRawMode())
Benjamin Kramer476d8b82010-08-11 14:47:12 +0000674 L->Diag(CP-2, diag::trigraph_converted) << llvm::StringRef(&Res, 1);
Reid Spencer5f016e22007-07-11 17:01:13 +0000675 return Res;
676}
677
Chris Lattner24f0e482009-04-18 22:05:41 +0000678/// getEscapedNewLineSize - Return the size of the specified escaped newline,
679/// 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 +0000680/// trigraph equivalent on entry to this function.
Chris Lattner24f0e482009-04-18 22:05:41 +0000681unsigned Lexer::getEscapedNewLineSize(const char *Ptr) {
682 unsigned Size = 0;
683 while (isWhitespace(Ptr[Size])) {
684 ++Size;
Mike Stump1eb44332009-09-09 15:08:12 +0000685
Chris Lattner24f0e482009-04-18 22:05:41 +0000686 if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r')
687 continue;
688
689 // If this is a \r\n or \n\r, skip the other half.
690 if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') &&
691 Ptr[Size-1] != Ptr[Size])
692 ++Size;
Mike Stump1eb44332009-09-09 15:08:12 +0000693
Chris Lattner24f0e482009-04-18 22:05:41 +0000694 return Size;
Mike Stump1eb44332009-09-09 15:08:12 +0000695 }
696
Chris Lattner24f0e482009-04-18 22:05:41 +0000697 // Not an escaped newline, must be a \t or something else.
698 return 0;
699}
700
Chris Lattner03374952009-04-18 22:27:02 +0000701/// SkipEscapedNewLines - If P points to an escaped newline (or a series of
702/// them), skip over them and return the first non-escaped-newline found,
703/// otherwise return P.
704const char *Lexer::SkipEscapedNewLines(const char *P) {
705 while (1) {
706 const char *AfterEscape;
707 if (*P == '\\') {
708 AfterEscape = P+1;
709 } else if (*P == '?') {
710 // If not a trigraph for escape, bail out.
711 if (P[1] != '?' || P[2] != '/')
712 return P;
713 AfterEscape = P+3;
714 } else {
715 return P;
716 }
Mike Stump1eb44332009-09-09 15:08:12 +0000717
Chris Lattner03374952009-04-18 22:27:02 +0000718 unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape);
719 if (NewLineSize == 0) return P;
720 P = AfterEscape+NewLineSize;
721 }
722}
723
Chris Lattner24f0e482009-04-18 22:05:41 +0000724
Reid Spencer5f016e22007-07-11 17:01:13 +0000725/// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
726/// get its size, and return it. This is tricky in several cases:
727/// 1. If currently at the start of a trigraph, we warn about the trigraph,
728/// then either return the trigraph (skipping 3 chars) or the '?',
729/// depending on whether trigraphs are enabled or not.
730/// 2. If this is an escaped newline (potentially with whitespace between
731/// the backslash and newline), implicitly skip the newline and return
732/// the char after it.
733/// 3. If this is a UCN, return it. FIXME: C++ UCN's?
734///
735/// This handles the slow/uncommon case of the getCharAndSize method. Here we
736/// know that we can accumulate into Size, and that we have already incremented
737/// Ptr by Size bytes.
738///
739/// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
740/// be updated to match.
741///
742char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
Chris Lattnerd2177732007-07-20 16:59:19 +0000743 Token *Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000744 // If we have a slash, look for an escaped newline.
745 if (Ptr[0] == '\\') {
746 ++Size;
747 ++Ptr;
748Slash:
749 // Common case, backslash-char where the char is not whitespace.
750 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump1eb44332009-09-09 15:08:12 +0000751
Chris Lattner5636a3b2009-06-23 05:15:06 +0000752 // See if we have optional whitespace characters between the slash and
753 // newline.
Chris Lattner24f0e482009-04-18 22:05:41 +0000754 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
755 // Remember that this token needs to be cleaned.
756 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +0000757
Chris Lattner24f0e482009-04-18 22:05:41 +0000758 // Warn if there was whitespace between the backslash and newline.
Chris Lattner5636a3b2009-06-23 05:15:06 +0000759 if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode())
Chris Lattner24f0e482009-04-18 22:05:41 +0000760 Diag(Ptr, diag::backslash_newline_space);
Mike Stump1eb44332009-09-09 15:08:12 +0000761
Chris Lattner24f0e482009-04-18 22:05:41 +0000762 // Found backslash<whitespace><newline>. Parse the char after it.
763 Size += EscapedNewLineSize;
764 Ptr += EscapedNewLineSize;
765 // Use slow version to accumulate a correct size field.
766 return getCharAndSizeSlow(Ptr, Size, Tok);
767 }
Mike Stump1eb44332009-09-09 15:08:12 +0000768
Reid Spencer5f016e22007-07-11 17:01:13 +0000769 // Otherwise, this is not an escaped newline, just return the slash.
770 return '\\';
771 }
Mike Stump1eb44332009-09-09 15:08:12 +0000772
Reid Spencer5f016e22007-07-11 17:01:13 +0000773 // If this is a trigraph, process it.
774 if (Ptr[0] == '?' && Ptr[1] == '?') {
775 // If this is actually a legal trigraph (not something like "??x"), emit
776 // a trigraph warning. If so, and if trigraphs are enabled, return it.
777 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : 0)) {
778 // Remember that this token needs to be cleaned.
Chris Lattnerd2177732007-07-20 16:59:19 +0000779 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +0000780
781 Ptr += 3;
782 Size += 3;
783 if (C == '\\') goto Slash;
784 return C;
785 }
786 }
Mike Stump1eb44332009-09-09 15:08:12 +0000787
Reid Spencer5f016e22007-07-11 17:01:13 +0000788 // If this is neither, return a single character.
789 ++Size;
790 return *Ptr;
791}
792
793
794/// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
795/// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
796/// and that we have already incremented Ptr by Size bytes.
797///
798/// NOTE: When this method is updated, getCharAndSizeSlow (above) should
799/// be updated to match.
800char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
801 const LangOptions &Features) {
802 // If we have a slash, look for an escaped newline.
803 if (Ptr[0] == '\\') {
804 ++Size;
805 ++Ptr;
806Slash:
807 // Common case, backslash-char where the char is not whitespace.
808 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump1eb44332009-09-09 15:08:12 +0000809
Reid Spencer5f016e22007-07-11 17:01:13 +0000810 // See if we have optional whitespace characters followed by a newline.
Chris Lattner24f0e482009-04-18 22:05:41 +0000811 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
812 // Found backslash<whitespace><newline>. Parse the char after it.
813 Size += EscapedNewLineSize;
814 Ptr += EscapedNewLineSize;
Mike Stump1eb44332009-09-09 15:08:12 +0000815
Chris Lattner24f0e482009-04-18 22:05:41 +0000816 // Use slow version to accumulate a correct size field.
817 return getCharAndSizeSlowNoWarn(Ptr, Size, Features);
818 }
Mike Stump1eb44332009-09-09 15:08:12 +0000819
Reid Spencer5f016e22007-07-11 17:01:13 +0000820 // Otherwise, this is not an escaped newline, just return the slash.
821 return '\\';
822 }
Mike Stump1eb44332009-09-09 15:08:12 +0000823
Reid Spencer5f016e22007-07-11 17:01:13 +0000824 // If this is a trigraph, process it.
825 if (Features.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
826 // If this is actually a legal trigraph (not something like "??x"), return
827 // it.
828 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
829 Ptr += 3;
830 Size += 3;
831 if (C == '\\') goto Slash;
832 return C;
833 }
834 }
Mike Stump1eb44332009-09-09 15:08:12 +0000835
Reid Spencer5f016e22007-07-11 17:01:13 +0000836 // If this is neither, return a single character.
837 ++Size;
838 return *Ptr;
839}
840
841//===----------------------------------------------------------------------===//
842// Helper methods for lexing.
843//===----------------------------------------------------------------------===//
844
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000845/// \brief Routine that indiscriminately skips bytes in the source file.
846void Lexer::SkipBytes(unsigned Bytes, bool StartOfLine) {
847 BufferPtr += Bytes;
848 if (BufferPtr > BufferEnd)
849 BufferPtr = BufferEnd;
850 IsAtStartOfLine = StartOfLine;
851}
852
Chris Lattnerd2177732007-07-20 16:59:19 +0000853void Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000854 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
855 unsigned Size;
856 unsigned char C = *CurPtr++;
Chris Lattnercd991db2010-01-11 02:38:50 +0000857 while (isIdentifierBody(C))
Reid Spencer5f016e22007-07-11 17:01:13 +0000858 C = *CurPtr++;
Chris Lattnercd991db2010-01-11 02:38:50 +0000859
Reid Spencer5f016e22007-07-11 17:01:13 +0000860 --CurPtr; // Back up over the skipped character.
861
862 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
863 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
864 // FIXME: UCNs.
Chris Lattnercd991db2010-01-11 02:38:50 +0000865 //
866 // TODO: Could merge these checks into a CharInfo flag to make the comparison
867 // cheaper
Reid Spencer5f016e22007-07-11 17:01:13 +0000868 if (C != '\\' && C != '?' && (C != '$' || !Features.DollarIdents)) {
869FinishIdentifier:
870 const char *IdStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +0000871 FormTokenWithChars(Result, CurPtr, tok::identifier);
Mike Stump1eb44332009-09-09 15:08:12 +0000872
Reid Spencer5f016e22007-07-11 17:01:13 +0000873 // If we are in raw mode, return this identifier raw. There is no need to
874 // look up identifier information or attempt to macro expand it.
875 if (LexingRawMode) return;
Mike Stump1eb44332009-09-09 15:08:12 +0000876
Reid Spencer5f016e22007-07-11 17:01:13 +0000877 // Fill in Result.IdentifierInfo, looking up the identifier in the
878 // identifier table.
Chris Lattnerd1186fa2009-01-21 07:45:14 +0000879 IdentifierInfo *II = PP->LookUpIdentifierInfo(Result, IdStart);
Mike Stump1eb44332009-09-09 15:08:12 +0000880
Chris Lattner863c4862009-01-23 18:35:48 +0000881 // Change the kind of this identifier to the appropriate token kind, e.g.
882 // turning "for" into a keyword.
883 Result.setKind(II->getTokenID());
Mike Stump1eb44332009-09-09 15:08:12 +0000884
Reid Spencer5f016e22007-07-11 17:01:13 +0000885 // Finally, now that we know we have an identifier, pass this off to the
886 // preprocessor, which may macro expand it or something.
Chris Lattnerd1186fa2009-01-21 07:45:14 +0000887 if (II->isHandleIdentifierCase())
Chris Lattner6a170eb2009-01-21 07:43:11 +0000888 PP->HandleIdentifier(Result);
889 return;
Reid Spencer5f016e22007-07-11 17:01:13 +0000890 }
Mike Stump1eb44332009-09-09 15:08:12 +0000891
Reid Spencer5f016e22007-07-11 17:01:13 +0000892 // Otherwise, $,\,? in identifier found. Enter slower path.
Mike Stump1eb44332009-09-09 15:08:12 +0000893
Reid Spencer5f016e22007-07-11 17:01:13 +0000894 C = getCharAndSize(CurPtr, Size);
895 while (1) {
896 if (C == '$') {
897 // If we hit a $ and they are not supported in identifiers, we are done.
898 if (!Features.DollarIdents) goto FinishIdentifier;
Mike Stump1eb44332009-09-09 15:08:12 +0000899
Reid Spencer5f016e22007-07-11 17:01:13 +0000900 // Otherwise, emit a diagnostic and continue.
Chris Lattner74d15df2008-11-22 02:02:22 +0000901 if (!isLexingRawMode())
902 Diag(CurPtr, diag::ext_dollar_in_identifier);
Reid Spencer5f016e22007-07-11 17:01:13 +0000903 CurPtr = ConsumeChar(CurPtr, Size, Result);
904 C = getCharAndSize(CurPtr, Size);
905 continue;
906 } else if (!isIdentifierBody(C)) { // FIXME: UCNs.
907 // Found end of identifier.
908 goto FinishIdentifier;
909 }
910
911 // Otherwise, this character is good, consume it.
912 CurPtr = ConsumeChar(CurPtr, Size, Result);
913
914 C = getCharAndSize(CurPtr, Size);
915 while (isIdentifierBody(C)) { // FIXME: UCNs.
916 CurPtr = ConsumeChar(CurPtr, Size, Result);
917 C = getCharAndSize(CurPtr, Size);
918 }
919 }
920}
921
Douglas Gregora75ec432010-08-30 14:50:47 +0000922/// isHexaLiteral - Return true if Start points to a hex constant.
Chris Lattner4a551002010-08-30 17:11:14 +0000923/// in microsoft mode (where this is supposed to be several different tokens).
Chris Lattner6ab55eb2010-08-31 16:42:00 +0000924static bool isHexaLiteral(const char *Start, const LangOptions &Features) {
925 unsigned Size;
926 char C1 = Lexer::getCharAndSizeNoWarn(Start, Size, Features);
927 if (C1 != '0')
928 return false;
929 char C2 = Lexer::getCharAndSizeNoWarn(Start + Size, Size, Features);
930 return (C2 == 'x' || C2 == 'X');
Douglas Gregora75ec432010-08-30 14:50:47 +0000931}
Reid Spencer5f016e22007-07-11 17:01:13 +0000932
Nate Begeman5253c7f2008-04-14 02:26:39 +0000933/// LexNumericConstant - Lex the remainder of a integer or floating point
Reid Spencer5f016e22007-07-11 17:01:13 +0000934/// constant. From[-1] is the first character lexed. Return the end of the
935/// constant.
Chris Lattnerd2177732007-07-20 16:59:19 +0000936void Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000937 unsigned Size;
938 char C = getCharAndSize(CurPtr, Size);
939 char PrevCh = 0;
940 while (isNumberBody(C)) { // FIXME: UCNs?
941 CurPtr = ConsumeChar(CurPtr, Size, Result);
942 PrevCh = C;
943 C = getCharAndSize(CurPtr, Size);
944 }
Mike Stump1eb44332009-09-09 15:08:12 +0000945
Reid Spencer5f016e22007-07-11 17:01:13 +0000946 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
Chris Lattnerb2f4a202010-08-30 17:09:08 +0000947 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) {
948 // 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
Chris Lattner6ab55eb2010-08-31 16:42:00 +0000950 if (!Features.Microsoft || !isHexaLiteral(BufferPtr, Features))
Chris Lattnerb2f4a202010-08-30 17:09:08 +0000951 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
952 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000953
954 // If we have a hex FP constant, continue.
Sean Hunt8c723402010-01-10 23:37:56 +0000955 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p') &&
Chris Lattnerb2f4a202010-08-30 17:09:08 +0000956 !Features.CPlusPlus0x)
Reid Spencer5f016e22007-07-11 17:01:13 +0000957 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
Mike Stump1eb44332009-09-09 15:08:12 +0000958
Reid Spencer5f016e22007-07-11 17:01:13 +0000959 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +0000960 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +0000961 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
Chris Lattner47246be2009-01-26 19:29:26 +0000962 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +0000963}
964
965/// LexStringLiteral - Lex the remainder of a string literal, after having lexed
966/// either " or L".
Chris Lattnerd88dc482008-10-12 04:05:48 +0000967void Lexer::LexStringLiteral(Token &Result, const char *CurPtr, bool Wide) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000968 const char *NulCharacter = 0; // Does this string contain the \0 character?
Mike Stump1eb44332009-09-09 15:08:12 +0000969
Reid Spencer5f016e22007-07-11 17:01:13 +0000970 char C = getAndAdvanceChar(CurPtr, Result);
971 while (C != '"') {
Chris Lattner571339c2010-05-30 23:27:38 +0000972 // Skip escaped characters. Escaped newlines will already be processed by
973 // getAndAdvanceChar.
974 if (C == '\\')
Reid Spencer5f016e22007-07-11 17:01:13 +0000975 C = getAndAdvanceChar(CurPtr, Result);
Douglas Gregor33611e02010-05-30 22:59:50 +0000976
Chris Lattner571339c2010-05-30 23:27:38 +0000977 if (C == '\n' || C == '\r' || // Newline.
Douglas Gregor33611e02010-05-30 22:59:50 +0000978 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Douglas Gregor55817af2010-08-25 17:04:25 +0000979 if (C == 0 && PP && PP->isCodeCompletionFile(FileLoc))
980 PP->CodeCompleteNaturalLanguage();
981 else if (!isLexingRawMode() && !Features.AsmPreprocessor)
Chris Lattner74d15df2008-11-22 02:02:22 +0000982 Diag(BufferPtr, diag::err_unterminated_string);
Chris Lattner9e6293d2008-10-12 04:51:35 +0000983 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Reid Spencer5f016e22007-07-11 17:01:13 +0000984 return;
Reid Spencer5f016e22007-07-11 17:01:13 +0000985 }
Chris Lattner571339c2010-05-30 23:27:38 +0000986
987 if (C == 0)
988 NulCharacter = CurPtr-1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000989 C = getAndAdvanceChar(CurPtr, Result);
990 }
Mike Stump1eb44332009-09-09 15:08:12 +0000991
Reid Spencer5f016e22007-07-11 17:01:13 +0000992 // If a nul character existed in the string, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +0000993 if (NulCharacter && !isLexingRawMode())
994 Diag(NulCharacter, diag::null_in_string);
Reid Spencer5f016e22007-07-11 17:01:13 +0000995
Reid Spencer5f016e22007-07-11 17:01:13 +0000996 // Update the location of the token as well as the BufferPtr instance var.
Chris Lattner47246be2009-01-26 19:29:26 +0000997 const char *TokStart = BufferPtr;
Sean Hunt6cf75022010-08-30 17:47:05 +0000998 FormTokenWithChars(Result, CurPtr,
999 Wide ? tok::wide_string_literal : tok::string_literal);
Chris Lattner47246be2009-01-26 19:29:26 +00001000 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001001}
1002
1003/// LexAngledStringLiteral - Lex the remainder of an angled string literal,
1004/// after having lexed the '<' character. This is used for #include filenames.
Chris Lattnerd2177732007-07-20 16:59:19 +00001005void Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001006 const char *NulCharacter = 0; // Does this string contain the \0 character?
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001007 const char *AfterLessPos = CurPtr;
Reid Spencer5f016e22007-07-11 17:01:13 +00001008 char C = getAndAdvanceChar(CurPtr, Result);
1009 while (C != '>') {
1010 // Skip escaped characters.
1011 if (C == '\\') {
1012 // Skip the escaped character.
1013 C = getAndAdvanceChar(CurPtr, Result);
1014 } else if (C == '\n' || C == '\r' || // Newline.
1015 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001016 // If the filename is unterminated, then it must just be a lone <
1017 // character. Return this as such.
1018 FormTokenWithChars(Result, AfterLessPos, tok::less);
Reid Spencer5f016e22007-07-11 17:01:13 +00001019 return;
1020 } else if (C == 0) {
1021 NulCharacter = CurPtr-1;
1022 }
1023 C = getAndAdvanceChar(CurPtr, Result);
1024 }
Mike Stump1eb44332009-09-09 15:08:12 +00001025
Reid Spencer5f016e22007-07-11 17:01:13 +00001026 // If a nul character existed in the string, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001027 if (NulCharacter && !isLexingRawMode())
1028 Diag(NulCharacter, diag::null_in_string);
Mike Stump1eb44332009-09-09 15:08:12 +00001029
Reid Spencer5f016e22007-07-11 17:01:13 +00001030 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001031 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001032 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
Chris Lattner47246be2009-01-26 19:29:26 +00001033 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001034}
1035
1036
1037/// LexCharConstant - Lex the remainder of a character constant, after having
1038/// lexed either ' or L'.
Chris Lattnerd2177732007-07-20 16:59:19 +00001039void Lexer::LexCharConstant(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001040 const char *NulCharacter = 0; // Does this character contain the \0 character?
1041
Reid Spencer5f016e22007-07-11 17:01:13 +00001042 char C = getAndAdvanceChar(CurPtr, Result);
1043 if (C == '\'') {
Chris Lattner33ab3f62009-03-18 21:10:12 +00001044 if (!isLexingRawMode() && !Features.AsmPreprocessor)
Chris Lattner74d15df2008-11-22 02:02:22 +00001045 Diag(BufferPtr, diag::err_empty_character);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001046 FormTokenWithChars(Result, CurPtr, tok::unknown);
Reid Spencer5f016e22007-07-11 17:01:13 +00001047 return;
Chris Lattnerd80f7862010-07-07 23:24:27 +00001048 }
1049
1050 while (C != '\'') {
1051 // Skip escaped characters.
1052 if (C == '\\') {
1053 // Skip the escaped character.
1054 // FIXME: UCN's
1055 C = getAndAdvanceChar(CurPtr, Result);
1056 } else if (C == '\n' || C == '\r' || // Newline.
1057 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Douglas Gregor55817af2010-08-25 17:04:25 +00001058 if (C == 0 && PP && PP->isCodeCompletionFile(FileLoc))
1059 PP->CodeCompleteNaturalLanguage();
1060 else if (!isLexingRawMode() && !Features.AsmPreprocessor)
Chris Lattnerd80f7862010-07-07 23:24:27 +00001061 Diag(BufferPtr, diag::err_unterminated_char);
1062 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1063 return;
1064 } else if (C == 0) {
1065 NulCharacter = CurPtr-1;
1066 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001067 C = getAndAdvanceChar(CurPtr, Result);
1068 }
Mike Stump1eb44332009-09-09 15:08:12 +00001069
Chris Lattnerd80f7862010-07-07 23:24:27 +00001070 // If a nul character existed in the character, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001071 if (NulCharacter && !isLexingRawMode())
1072 Diag(NulCharacter, diag::null_in_char);
Reid Spencer5f016e22007-07-11 17:01:13 +00001073
Reid Spencer5f016e22007-07-11 17:01:13 +00001074 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001075 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001076 FormTokenWithChars(Result, CurPtr, tok::char_constant);
Chris Lattner47246be2009-01-26 19:29:26 +00001077 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001078}
1079
1080/// SkipWhitespace - Efficiently skip over a series of whitespace characters.
1081/// Update BufferPtr to point to the next non-whitespace character and return.
Chris Lattnerd88dc482008-10-12 04:05:48 +00001082///
1083/// This method forms a token and returns true if KeepWhitespaceMode is enabled.
1084///
1085bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001086 // Whitespace - Skip it, then return the token after the whitespace.
1087 unsigned char Char = *CurPtr; // Skip consequtive spaces efficiently.
1088 while (1) {
1089 // Skip horizontal whitespace very aggressively.
1090 while (isHorizontalWhitespace(Char))
1091 Char = *++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001092
Daniel Dunbarddd3e8b2008-11-25 00:20:22 +00001093 // Otherwise if we have something other than whitespace, we're done.
Reid Spencer5f016e22007-07-11 17:01:13 +00001094 if (Char != '\n' && Char != '\r')
1095 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001096
Reid Spencer5f016e22007-07-11 17:01:13 +00001097 if (ParsingPreprocessorDirective) {
1098 // End of preprocessor directive line, let LexTokenInternal handle this.
1099 BufferPtr = CurPtr;
Chris Lattnerd88dc482008-10-12 04:05:48 +00001100 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001101 }
Mike Stump1eb44332009-09-09 15:08:12 +00001102
Reid Spencer5f016e22007-07-11 17:01:13 +00001103 // ok, but handle newline.
1104 // The returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00001105 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00001106 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00001107 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001108 Char = *++CurPtr;
1109 }
1110
1111 // If this isn't immediately after a newline, there is leading space.
1112 char PrevChar = CurPtr[-1];
1113 if (PrevChar != '\n' && PrevChar != '\r')
Chris Lattnerd2177732007-07-20 16:59:19 +00001114 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001115
Chris Lattnerd88dc482008-10-12 04:05:48 +00001116 // If the client wants us to return whitespace, return it now.
1117 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001118 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd88dc482008-10-12 04:05:48 +00001119 return true;
1120 }
Mike Stump1eb44332009-09-09 15:08:12 +00001121
Reid Spencer5f016e22007-07-11 17:01:13 +00001122 BufferPtr = CurPtr;
Chris Lattnerd88dc482008-10-12 04:05:48 +00001123 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001124}
1125
1126// SkipBCPLComment - We have just read the // characters from input. Skip until
1127// we find the newline character thats terminate the comment. Then update
Chris Lattner046c2272010-01-18 22:35:47 +00001128/// BufferPtr and return.
1129///
1130/// If we're in KeepCommentMode or any CommentHandler has inserted
1131/// some tokens, this will store the first token and return true.
Chris Lattnerd2177732007-07-20 16:59:19 +00001132bool Lexer::SkipBCPLComment(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001133 // If BCPL comments aren't explicitly enabled for this language, emit an
1134 // extension warning.
Chris Lattner74d15df2008-11-22 02:02:22 +00001135 if (!Features.BCPLComment && !isLexingRawMode()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001136 Diag(BufferPtr, diag::ext_bcpl_comment);
Mike Stump1eb44332009-09-09 15:08:12 +00001137
Reid Spencer5f016e22007-07-11 17:01:13 +00001138 // Mark them enabled so we only emit one warning for this translation
1139 // unit.
1140 Features.BCPLComment = true;
1141 }
Mike Stump1eb44332009-09-09 15:08:12 +00001142
Reid Spencer5f016e22007-07-11 17:01:13 +00001143 // Scan over the body of the comment. The common case, when scanning, is that
1144 // the comment contains normal ascii characters with nothing interesting in
1145 // them. As such, optimize for this case with the inner loop.
1146 char C;
1147 do {
1148 C = *CurPtr;
1149 // FIXME: Speedup BCPL comment lexing. Just scan for a \n or \r character.
1150 // If we find a \n character, scan backwards, checking to see if it's an
1151 // escaped newline, like we do for block comments.
Mike Stump1eb44332009-09-09 15:08:12 +00001152
Reid Spencer5f016e22007-07-11 17:01:13 +00001153 // Skip over characters in the fast loop.
1154 while (C != 0 && // Potentially EOF.
1155 C != '\\' && // Potentially escaped newline.
1156 C != '?' && // Potentially trigraph.
1157 C != '\n' && C != '\r') // Newline or DOS-style newline.
1158 C = *++CurPtr;
1159
1160 // If this is a newline, we're done.
1161 if (C == '\n' || C == '\r')
1162 break; // Found the newline? Break out!
Mike Stump1eb44332009-09-09 15:08:12 +00001163
Reid Spencer5f016e22007-07-11 17:01:13 +00001164 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001165 // properly decode the character. Read it in raw mode to avoid emitting
1166 // diagnostics about things like trigraphs. If we see an escaped newline,
1167 // we'll handle it below.
Reid Spencer5f016e22007-07-11 17:01:13 +00001168 const char *OldPtr = CurPtr;
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001169 bool OldRawMode = isLexingRawMode();
1170 LexingRawMode = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001171 C = getAndAdvanceChar(CurPtr, Result);
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001172 LexingRawMode = OldRawMode;
Chris Lattneread616c2009-04-05 00:26:41 +00001173
1174 // If the char that we finally got was a \n, then we must have had something
1175 // like \<newline><newline>. We don't want to have consumed the second
1176 // newline, we want CurPtr, to end up pointing to it down below.
1177 if (C == '\n' || C == '\r') {
1178 --CurPtr;
1179 C = 'x'; // doesn't matter what this is.
1180 }
Mike Stump1eb44332009-09-09 15:08:12 +00001181
Reid Spencer5f016e22007-07-11 17:01:13 +00001182 // If we read multiple characters, and one of those characters was a \r or
1183 // \n, then we had an escaped newline within the comment. Emit diagnostic
1184 // unless the next line is also a // comment.
1185 if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') {
1186 for (; OldPtr != CurPtr; ++OldPtr)
1187 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
1188 // Okay, we found a // comment that ends in a newline, if the next
1189 // line is also a // comment, but has spaces, don't emit a diagnostic.
1190 if (isspace(C)) {
1191 const char *ForwardPtr = CurPtr;
1192 while (isspace(*ForwardPtr)) // Skip whitespace.
1193 ++ForwardPtr;
1194 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
1195 break;
1196 }
Mike Stump1eb44332009-09-09 15:08:12 +00001197
Chris Lattner74d15df2008-11-22 02:02:22 +00001198 if (!isLexingRawMode())
1199 Diag(OldPtr-1, diag::ext_multi_line_bcpl_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001200 break;
1201 }
1202 }
Mike Stump1eb44332009-09-09 15:08:12 +00001203
Douglas Gregor55817af2010-08-25 17:04:25 +00001204 if (CurPtr == BufferEnd+1) {
1205 if (PP && PP->isCodeCompletionFile(FileLoc))
1206 PP->CodeCompleteNaturalLanguage();
1207
1208 --CurPtr;
1209 break;
1210 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001211 } while (C != '\n' && C != '\r');
1212
Chris Lattner3d0ad582010-02-03 21:06:21 +00001213 // Found but did not consume the newline. Notify comment handlers about the
1214 // comment unless we're in a #if 0 block.
1215 if (PP && !isLexingRawMode() &&
1216 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
1217 getSourceLocation(CurPtr)))) {
Chris Lattner046c2272010-01-18 22:35:47 +00001218 BufferPtr = CurPtr;
1219 return true; // A token has to be returned.
1220 }
Mike Stump1eb44332009-09-09 15:08:12 +00001221
Reid Spencer5f016e22007-07-11 17:01:13 +00001222 // If we are returning comments as tokens, return this comment as a token.
Chris Lattnerfa95a012008-10-12 03:22:02 +00001223 if (inKeepCommentMode())
Reid Spencer5f016e22007-07-11 17:01:13 +00001224 return SaveBCPLComment(Result, CurPtr);
1225
1226 // If we are inside a preprocessor directive and we see the end of line,
1227 // return immediately, so that the lexer can return this as an EOM token.
1228 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
1229 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001230 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001231 }
Mike Stump1eb44332009-09-09 15:08:12 +00001232
Reid Spencer5f016e22007-07-11 17:01:13 +00001233 // Otherwise, eat the \n character. We don't care if this is a \n\r or
Chris Lattner7a4f0042008-10-12 00:23:07 +00001234 // \r\n sequence. This is an efficiency hack (because we know the \n can't
Chris Lattnerd88dc482008-10-12 04:05:48 +00001235 // contribute to another token), it isn't needed for correctness. Note that
1236 // this is ok even in KeepWhitespaceMode, because we would have returned the
1237 /// comment above in that mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00001238 ++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001239
Reid Spencer5f016e22007-07-11 17:01:13 +00001240 // The next returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00001241 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00001242 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00001243 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001244 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001245 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001246}
1247
1248/// SaveBCPLComment - If in save-comment mode, package up this BCPL comment in
1249/// an appropriate way and return it.
Chris Lattnerd2177732007-07-20 16:59:19 +00001250bool Lexer::SaveBCPLComment(Token &Result, const char *CurPtr) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001251 // If we're not in a preprocessor directive, just return the // comment
1252 // directly.
1253 FormTokenWithChars(Result, CurPtr, tok::comment);
Mike Stump1eb44332009-09-09 15:08:12 +00001254
Chris Lattner9e6293d2008-10-12 04:51:35 +00001255 if (!ParsingPreprocessorDirective)
1256 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001257
Chris Lattner9e6293d2008-10-12 04:51:35 +00001258 // If this BCPL-style comment is in a macro definition, transmogrify it into
1259 // a C-style block comment.
Douglas Gregor453091c2010-03-16 22:30:13 +00001260 bool Invalid = false;
1261 std::string Spelling = PP->getSpelling(Result, &Invalid);
1262 if (Invalid)
1263 return true;
1264
Chris Lattner9e6293d2008-10-12 04:51:35 +00001265 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not bcpl comment?");
1266 Spelling[1] = '*'; // Change prefix to "/*".
1267 Spelling += "*/"; // add suffix.
Mike Stump1eb44332009-09-09 15:08:12 +00001268
Chris Lattner9e6293d2008-10-12 04:51:35 +00001269 Result.setKind(tok::comment);
Chris Lattner47246be2009-01-26 19:29:26 +00001270 PP->CreateString(&Spelling[0], Spelling.size(), Result,
1271 Result.getLocation());
Chris Lattner2d381892008-10-12 04:15:42 +00001272 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001273}
1274
1275/// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
1276/// character (either \n or \r) is part of an escaped newline sequence. Issue a
Chris Lattner47a2b402008-12-12 07:14:34 +00001277/// diagnostic if so. We know that the newline is inside of a block comment.
Mike Stump1eb44332009-09-09 15:08:12 +00001278static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
Reid Spencer5f016e22007-07-11 17:01:13 +00001279 Lexer *L) {
1280 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
Mike Stump1eb44332009-09-09 15:08:12 +00001281
Reid Spencer5f016e22007-07-11 17:01:13 +00001282 // Back up off the newline.
1283 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001284
Reid Spencer5f016e22007-07-11 17:01:13 +00001285 // If this is a two-character newline sequence, skip the other character.
1286 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
1287 // \n\n or \r\r -> not escaped newline.
1288 if (CurPtr[0] == CurPtr[1])
1289 return false;
1290 // \n\r or \r\n -> skip the newline.
1291 --CurPtr;
1292 }
Mike Stump1eb44332009-09-09 15:08:12 +00001293
Reid Spencer5f016e22007-07-11 17:01:13 +00001294 // If we have horizontal whitespace, skip over it. We allow whitespace
1295 // between the slash and newline.
1296 bool HasSpace = false;
1297 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
1298 --CurPtr;
1299 HasSpace = true;
1300 }
Mike Stump1eb44332009-09-09 15:08:12 +00001301
Reid Spencer5f016e22007-07-11 17:01:13 +00001302 // If we have a slash, we know this is an escaped newline.
1303 if (*CurPtr == '\\') {
1304 if (CurPtr[-1] != '*') return false;
1305 } else {
1306 // It isn't a slash, is it the ?? / trigraph?
1307 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
1308 CurPtr[-3] != '*')
1309 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001310
Reid Spencer5f016e22007-07-11 17:01:13 +00001311 // This is the trigraph ending the comment. Emit a stern warning!
1312 CurPtr -= 2;
1313
1314 // If no trigraphs are enabled, warn that we ignored this trigraph and
1315 // ignore this * character.
1316 if (!L->getFeatures().Trigraphs) {
Chris Lattner74d15df2008-11-22 02:02:22 +00001317 if (!L->isLexingRawMode())
1318 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001319 return false;
1320 }
Chris Lattner74d15df2008-11-22 02:02:22 +00001321 if (!L->isLexingRawMode())
1322 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001323 }
Mike Stump1eb44332009-09-09 15:08:12 +00001324
Reid Spencer5f016e22007-07-11 17:01:13 +00001325 // Warn about having an escaped newline between the */ characters.
Chris Lattner74d15df2008-11-22 02:02:22 +00001326 if (!L->isLexingRawMode())
1327 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
Mike Stump1eb44332009-09-09 15:08:12 +00001328
Reid Spencer5f016e22007-07-11 17:01:13 +00001329 // If there was space between the backslash and newline, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001330 if (HasSpace && !L->isLexingRawMode())
1331 L->Diag(CurPtr, diag::backslash_newline_space);
Mike Stump1eb44332009-09-09 15:08:12 +00001332
Reid Spencer5f016e22007-07-11 17:01:13 +00001333 return true;
1334}
1335
1336#ifdef __SSE2__
1337#include <emmintrin.h>
1338#elif __ALTIVEC__
1339#include <altivec.h>
1340#undef bool
1341#endif
1342
1343/// SkipBlockComment - We have just read the /* characters from input. Read
1344/// until we find the */ characters that terminate the comment. Note that we
1345/// don't bother decoding trigraphs or escaped newlines in block comments,
1346/// because they cannot cause the comment to end. The only thing that can
1347/// happen is the comment could end with an escaped newline between the */ end
1348/// of comment.
Chris Lattner2d381892008-10-12 04:15:42 +00001349///
Chris Lattner046c2272010-01-18 22:35:47 +00001350/// If we're in KeepCommentMode or any CommentHandler has inserted
1351/// some tokens, this will store the first token and return true.
Chris Lattnerd2177732007-07-20 16:59:19 +00001352bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001353 // Scan one character past where we should, looking for a '/' character. Once
1354 // we find it, check to see if it was preceeded by a *. This common
1355 // optimization helps people who like to put a lot of * characters in their
1356 // comments.
Chris Lattner8146b682007-07-21 23:43:37 +00001357
1358 // The first character we get with newlines and trigraphs skipped to handle
1359 // the degenerate /*/ case below correctly if the * has an escaped newline
1360 // after it.
1361 unsigned CharSize;
1362 unsigned char C = getCharAndSize(CurPtr, CharSize);
1363 CurPtr += CharSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001364 if (C == 0 && CurPtr == BufferEnd+1) {
Chris Lattner150fcd52010-05-16 19:54:05 +00001365 if (!isLexingRawMode() &&
1366 !PP->isCodeCompletionFile(FileLoc))
Chris Lattner0af57422008-10-12 01:31:51 +00001367 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner31f0eca2008-10-12 04:19:49 +00001368 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001369
Chris Lattner31f0eca2008-10-12 04:19:49 +00001370 // KeepWhitespaceMode should return this broken comment as a token. Since
1371 // it isn't a well formed comment, just return it as an 'unknown' token.
1372 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001373 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner31f0eca2008-10-12 04:19:49 +00001374 return true;
1375 }
Mike Stump1eb44332009-09-09 15:08:12 +00001376
Chris Lattner31f0eca2008-10-12 04:19:49 +00001377 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001378 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001379 }
Mike Stump1eb44332009-09-09 15:08:12 +00001380
Chris Lattner8146b682007-07-21 23:43:37 +00001381 // Check to see if the first character after the '/*' is another /. If so,
1382 // then this slash does not end the block comment, it is part of it.
1383 if (C == '/')
1384 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00001385
Reid Spencer5f016e22007-07-11 17:01:13 +00001386 while (1) {
1387 // Skip over all non-interesting characters until we find end of buffer or a
1388 // (probably ending) '/' character.
1389 if (CurPtr + 24 < BufferEnd) {
1390 // While not aligned to a 16-byte boundary.
1391 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
1392 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00001393
Reid Spencer5f016e22007-07-11 17:01:13 +00001394 if (C == '/') goto FoundSlash;
1395
1396#ifdef __SSE2__
1397 __m128i Slashes = _mm_set_epi8('/', '/', '/', '/', '/', '/', '/', '/',
1398 '/', '/', '/', '/', '/', '/', '/', '/');
1399 while (CurPtr+16 <= BufferEnd &&
1400 _mm_movemask_epi8(_mm_cmpeq_epi8(*(__m128i*)CurPtr, Slashes)) == 0)
1401 CurPtr += 16;
1402#elif __ALTIVEC__
1403 __vector unsigned char Slashes = {
Mike Stump1eb44332009-09-09 15:08:12 +00001404 '/', '/', '/', '/', '/', '/', '/', '/',
Reid Spencer5f016e22007-07-11 17:01:13 +00001405 '/', '/', '/', '/', '/', '/', '/', '/'
1406 };
1407 while (CurPtr+16 <= BufferEnd &&
1408 !vec_any_eq(*(vector unsigned char*)CurPtr, Slashes))
1409 CurPtr += 16;
Mike Stump1eb44332009-09-09 15:08:12 +00001410#else
Reid Spencer5f016e22007-07-11 17:01:13 +00001411 // Scan for '/' quickly. Many block comments are very large.
1412 while (CurPtr[0] != '/' &&
1413 CurPtr[1] != '/' &&
1414 CurPtr[2] != '/' &&
1415 CurPtr[3] != '/' &&
1416 CurPtr+4 < BufferEnd) {
1417 CurPtr += 4;
1418 }
1419#endif
Mike Stump1eb44332009-09-09 15:08:12 +00001420
Reid Spencer5f016e22007-07-11 17:01:13 +00001421 // It has to be one of the bytes scanned, increment to it and read one.
1422 C = *CurPtr++;
1423 }
Mike Stump1eb44332009-09-09 15:08:12 +00001424
Reid Spencer5f016e22007-07-11 17:01:13 +00001425 // Loop to scan the remainder.
1426 while (C != '/' && C != '\0')
1427 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00001428
Reid Spencer5f016e22007-07-11 17:01:13 +00001429 FoundSlash:
1430 if (C == '/') {
1431 if (CurPtr[-2] == '*') // We found the final */. We're done!
1432 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001433
Reid Spencer5f016e22007-07-11 17:01:13 +00001434 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
1435 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
1436 // We found the final */, though it had an escaped newline between the
1437 // * and /. We're done!
1438 break;
1439 }
1440 }
1441 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
1442 // If this is a /* inside of the comment, emit a warning. Don't do this
1443 // if this is a /*/, which will end the comment. This misses cases with
1444 // embedded escaped newlines, but oh well.
Chris Lattner74d15df2008-11-22 02:02:22 +00001445 if (!isLexingRawMode())
1446 Diag(CurPtr-1, diag::warn_nested_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001447 }
1448 } else if (C == 0 && CurPtr == BufferEnd+1) {
Douglas Gregor55817af2010-08-25 17:04:25 +00001449 if (PP && PP->isCodeCompletionFile(FileLoc))
1450 PP->CodeCompleteNaturalLanguage();
1451 else if (!isLexingRawMode())
Chris Lattner74d15df2008-11-22 02:02:22 +00001452 Diag(BufferPtr, diag::err_unterminated_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001453 // Note: the user probably forgot a */. We could continue immediately
1454 // after the /*, but this would involve lexing a lot of what really is the
1455 // comment, which surely would confuse the parser.
Chris Lattner31f0eca2008-10-12 04:19:49 +00001456 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001457
Chris Lattner31f0eca2008-10-12 04:19:49 +00001458 // KeepWhitespaceMode should return this broken comment as a token. Since
1459 // it isn't a well formed comment, just return it as an 'unknown' token.
1460 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001461 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner31f0eca2008-10-12 04:19:49 +00001462 return true;
1463 }
Mike Stump1eb44332009-09-09 15:08:12 +00001464
Chris Lattner31f0eca2008-10-12 04:19:49 +00001465 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001466 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001467 }
1468 C = *CurPtr++;
1469 }
Mike Stump1eb44332009-09-09 15:08:12 +00001470
Chris Lattner3d0ad582010-02-03 21:06:21 +00001471 // Notify comment handlers about the comment unless we're in a #if 0 block.
1472 if (PP && !isLexingRawMode() &&
1473 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
1474 getSourceLocation(CurPtr)))) {
Chris Lattner046c2272010-01-18 22:35:47 +00001475 BufferPtr = CurPtr;
1476 return true; // A token has to be returned.
1477 }
Douglas Gregor2e222532009-07-02 17:08:52 +00001478
Reid Spencer5f016e22007-07-11 17:01:13 +00001479 // If we are returning comments as tokens, return this comment as a token.
Chris Lattnerfa95a012008-10-12 03:22:02 +00001480 if (inKeepCommentMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001481 FormTokenWithChars(Result, CurPtr, tok::comment);
Chris Lattner2d381892008-10-12 04:15:42 +00001482 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001483 }
1484
1485 // It is common for the tokens immediately after a /**/ comment to be
1486 // whitespace. Instead of going through the big switch, handle it
Chris Lattnerd88dc482008-10-12 04:05:48 +00001487 // efficiently now. This is safe even in KeepWhitespaceMode because we would
1488 // have already returned above with the comment as a token.
Reid Spencer5f016e22007-07-11 17:01:13 +00001489 if (isHorizontalWhitespace(*CurPtr)) {
Chris Lattnerd2177732007-07-20 16:59:19 +00001490 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001491 SkipWhitespace(Result, CurPtr+1);
Chris Lattner2d381892008-10-12 04:15:42 +00001492 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001493 }
1494
1495 // Otherwise, just return so that the next character will be lexed as a token.
1496 BufferPtr = CurPtr;
Chris Lattnerd2177732007-07-20 16:59:19 +00001497 Result.setFlag(Token::LeadingSpace);
Chris Lattner2d381892008-10-12 04:15:42 +00001498 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001499}
1500
1501//===----------------------------------------------------------------------===//
1502// Primary Lexing Entry Points
1503//===----------------------------------------------------------------------===//
1504
Reid Spencer5f016e22007-07-11 17:01:13 +00001505/// ReadToEndOfLine - Read the rest of the current preprocessor line as an
1506/// uninterpreted string. This switches the lexer out of directive mode.
1507std::string Lexer::ReadToEndOfLine() {
1508 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
1509 "Must be in a preprocessing directive!");
1510 std::string Result;
Chris Lattnerd2177732007-07-20 16:59:19 +00001511 Token Tmp;
Reid Spencer5f016e22007-07-11 17:01:13 +00001512
1513 // CurPtr - Cache BufferPtr in an automatic variable.
1514 const char *CurPtr = BufferPtr;
1515 while (1) {
1516 char Char = getAndAdvanceChar(CurPtr, Tmp);
1517 switch (Char) {
1518 default:
1519 Result += Char;
1520 break;
1521 case 0: // Null.
1522 // Found end of file?
1523 if (CurPtr-1 != BufferEnd) {
1524 // Nope, normal character, continue.
1525 Result += Char;
1526 break;
1527 }
1528 // FALL THROUGH.
1529 case '\r':
1530 case '\n':
1531 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
1532 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
1533 BufferPtr = CurPtr-1;
Mike Stump1eb44332009-09-09 15:08:12 +00001534
Reid Spencer5f016e22007-07-11 17:01:13 +00001535 // Next, lex the character, which should handle the EOM transition.
1536 Lex(Tmp);
Douglas Gregor55817af2010-08-25 17:04:25 +00001537 if (Tmp.is(tok::code_completion)) {
1538 if (PP && PP->getCodeCompletionHandler())
1539 PP->getCodeCompletionHandler()->CodeCompleteNaturalLanguage();
1540 Lex(Tmp);
1541 }
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001542 assert(Tmp.is(tok::eom) && "Unexpected token!");
Mike Stump1eb44332009-09-09 15:08:12 +00001543
Reid Spencer5f016e22007-07-11 17:01:13 +00001544 // Finally, we're done, return the string we found.
1545 return Result;
1546 }
1547 }
1548}
1549
1550/// LexEndOfFile - CurPtr points to the end of this file. Handle this
1551/// condition, reporting diagnostics and handling other edge cases as required.
1552/// This returns true if Result contains a token, false if PP.Lex should be
1553/// called again.
Chris Lattnerd2177732007-07-20 16:59:19 +00001554bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
Douglas Gregorf44e8542010-08-24 19:08:16 +00001555 // Check if we are performing code completion.
1556 if (PP && PP->isCodeCompletionFile(FileLoc)) {
1557 // We're at the end of the file, but we've been asked to consider the
1558 // end of the file to be a code-completion token. Return the
1559 // code-completion token.
1560 Result.startToken();
1561 FormTokenWithChars(Result, CurPtr, tok::code_completion);
1562
1563 // Only do the eof -> code_completion translation once.
1564 PP->SetCodeCompletionPoint(0, 0, 0);
1565
1566 // Silence any diagnostics that occur once we hit the code-completion point.
1567 PP->getDiagnostics().setSuppressAllDiagnostics(true);
1568 return true;
1569 }
1570
Reid Spencer5f016e22007-07-11 17:01:13 +00001571 // If we hit the end of the file while parsing a preprocessor directive,
1572 // end the preprocessor directive first. The next token returned will
1573 // then be the end of file.
1574 if (ParsingPreprocessorDirective) {
1575 // Done parsing the "line".
1576 ParsingPreprocessorDirective = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001577 // Update the location of token as well as BufferPtr.
Chris Lattner9e6293d2008-10-12 04:51:35 +00001578 FormTokenWithChars(Result, CurPtr, tok::eom);
Mike Stump1eb44332009-09-09 15:08:12 +00001579
Reid Spencer5f016e22007-07-11 17:01:13 +00001580 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattnerf744d132008-10-12 03:27:19 +00001581 SetCommentRetentionState(PP->getCommentRetentionState());
Reid Spencer5f016e22007-07-11 17:01:13 +00001582 return true; // Have a token.
Mike Stump1eb44332009-09-09 15:08:12 +00001583 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00001584
Reid Spencer5f016e22007-07-11 17:01:13 +00001585 // If we are in raw mode, return this event as an EOF token. Let the caller
1586 // that put us in raw mode handle the event.
Chris Lattner74d15df2008-11-22 02:02:22 +00001587 if (isLexingRawMode()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001588 Result.startToken();
1589 BufferPtr = BufferEnd;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001590 FormTokenWithChars(Result, BufferEnd, tok::eof);
Reid Spencer5f016e22007-07-11 17:01:13 +00001591 return true;
1592 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00001593
Douglas Gregorf44e8542010-08-24 19:08:16 +00001594 // Issue diagnostics for unterminated #if and missing newline.
1595
Reid Spencer5f016e22007-07-11 17:01:13 +00001596 // If we are in a #if directive, emit an error.
1597 while (!ConditionalStack.empty()) {
Douglas Gregor2d474ba2010-08-12 17:04:55 +00001598 if (!PP->isCodeCompletionFile(FileLoc))
1599 PP->Diag(ConditionalStack.back().IfLoc,
1600 diag::err_pp_unterminated_conditional);
Reid Spencer5f016e22007-07-11 17:01:13 +00001601 ConditionalStack.pop_back();
1602 }
Mike Stump1eb44332009-09-09 15:08:12 +00001603
Chris Lattnerb25e5d72008-04-12 05:54:25 +00001604 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
1605 // a pedwarn.
1606 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r'))
Mike Stump20d0ee52009-04-02 02:29:42 +00001607 Diag(BufferEnd, diag::ext_no_newline_eof)
Douglas Gregor849b2432010-03-31 17:46:05 +00001608 << FixItHint::CreateInsertion(getSourceLocation(BufferEnd), "\n");
Mike Stump1eb44332009-09-09 15:08:12 +00001609
Reid Spencer5f016e22007-07-11 17:01:13 +00001610 BufferPtr = CurPtr;
1611
1612 // Finally, let the preprocessor handle this.
Chris Lattner168ae2d2007-10-17 20:41:00 +00001613 return PP->HandleEndOfFile(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001614}
1615
1616/// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
1617/// the specified lexer will return a tok::l_paren token, 0 if it is something
1618/// else and 2 if there are no more tokens in the buffer controlled by the
1619/// lexer.
1620unsigned Lexer::isNextPPTokenLParen() {
1621 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
Mike Stump1eb44332009-09-09 15:08:12 +00001622
Reid Spencer5f016e22007-07-11 17:01:13 +00001623 // Switch to 'skipping' mode. This will ensure that we can lex a token
1624 // without emitting diagnostics, disables macro expansion, and will cause EOF
1625 // to return an EOF token instead of popping the include stack.
1626 LexingRawMode = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001627
Reid Spencer5f016e22007-07-11 17:01:13 +00001628 // Save state that can be changed while lexing so that we can restore it.
1629 const char *TmpBufferPtr = BufferPtr;
Chris Lattnera864cf72009-04-24 07:15:46 +00001630 bool inPPDirectiveMode = ParsingPreprocessorDirective;
Mike Stump1eb44332009-09-09 15:08:12 +00001631
Chris Lattnerd2177732007-07-20 16:59:19 +00001632 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001633 Tok.startToken();
1634 LexTokenInternal(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001635
Reid Spencer5f016e22007-07-11 17:01:13 +00001636 // Restore state that may have changed.
1637 BufferPtr = TmpBufferPtr;
Chris Lattnera864cf72009-04-24 07:15:46 +00001638 ParsingPreprocessorDirective = inPPDirectiveMode;
Mike Stump1eb44332009-09-09 15:08:12 +00001639
Reid Spencer5f016e22007-07-11 17:01:13 +00001640 // Restore the lexer back to non-skipping mode.
1641 LexingRawMode = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001642
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001643 if (Tok.is(tok::eof))
Reid Spencer5f016e22007-07-11 17:01:13 +00001644 return 2;
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001645 return Tok.is(tok::l_paren);
Reid Spencer5f016e22007-07-11 17:01:13 +00001646}
1647
Chris Lattner34f349d2009-12-14 06:16:57 +00001648/// FindConflictEnd - Find the end of a version control conflict marker.
1649static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd) {
1650 llvm::StringRef RestOfBuffer(CurPtr+7, BufferEnd-CurPtr-7);
1651 size_t Pos = RestOfBuffer.find(">>>>>>>");
1652 while (Pos != llvm::StringRef::npos) {
1653 // Must occur at start of line.
1654 if (RestOfBuffer[Pos-1] != '\r' &&
1655 RestOfBuffer[Pos-1] != '\n') {
1656 RestOfBuffer = RestOfBuffer.substr(Pos+7);
Chris Lattner3d488992010-05-17 20:27:25 +00001657 Pos = RestOfBuffer.find(">>>>>>>");
Chris Lattner34f349d2009-12-14 06:16:57 +00001658 continue;
1659 }
1660 return RestOfBuffer.data()+Pos;
1661 }
1662 return 0;
1663}
1664
1665/// IsStartOfConflictMarker - If the specified pointer is the start of a version
1666/// control conflict marker like '<<<<<<<', recognize it as such, emit an error
1667/// and recover nicely. This returns true if it is a conflict marker and false
1668/// if not.
1669bool Lexer::IsStartOfConflictMarker(const char *CurPtr) {
1670 // Only a conflict marker if it starts at the beginning of a line.
1671 if (CurPtr != BufferStart &&
1672 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
1673 return false;
1674
1675 // Check to see if we have <<<<<<<.
1676 if (BufferEnd-CurPtr < 8 ||
1677 llvm::StringRef(CurPtr, 7) != "<<<<<<<")
1678 return false;
1679
1680 // If we have a situation where we don't care about conflict markers, ignore
1681 // it.
1682 if (IsInConflictMarker || isLexingRawMode())
1683 return false;
1684
1685 // Check to see if there is a >>>>>>> somewhere in the buffer at the start of
1686 // a line to terminate this conflict marker.
Chris Lattner3d488992010-05-17 20:27:25 +00001687 if (FindConflictEnd(CurPtr, BufferEnd)) {
Chris Lattner34f349d2009-12-14 06:16:57 +00001688 // We found a match. We are really in a conflict marker.
1689 // Diagnose this, and ignore to the end of line.
1690 Diag(CurPtr, diag::err_conflict_marker);
1691 IsInConflictMarker = true;
1692
1693 // Skip ahead to the end of line. We know this exists because the
1694 // end-of-conflict marker starts with \r or \n.
1695 while (*CurPtr != '\r' && *CurPtr != '\n') {
1696 assert(CurPtr != BufferEnd && "Didn't find end of line");
1697 ++CurPtr;
1698 }
1699 BufferPtr = CurPtr;
1700 return true;
1701 }
1702
1703 // No end of conflict marker found.
1704 return false;
1705}
1706
1707
1708/// HandleEndOfConflictMarker - If this is a '=======' or '|||||||' or '>>>>>>>'
1709/// marker, then it is the end of a conflict marker. Handle it by ignoring up
1710/// until the end of the line. This returns true if it is a conflict marker and
1711/// false if not.
1712bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) {
1713 // Only a conflict marker if it starts at the beginning of a line.
1714 if (CurPtr != BufferStart &&
1715 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
1716 return false;
1717
1718 // If we have a situation where we don't care about conflict markers, ignore
1719 // it.
1720 if (!IsInConflictMarker || isLexingRawMode())
1721 return false;
1722
1723 // Check to see if we have the marker (7 characters in a row).
1724 for (unsigned i = 1; i != 7; ++i)
1725 if (CurPtr[i] != CurPtr[0])
1726 return false;
1727
1728 // If we do have it, search for the end of the conflict marker. This could
1729 // fail if it got skipped with a '#if 0' or something. Note that CurPtr might
1730 // be the end of conflict marker.
1731 if (const char *End = FindConflictEnd(CurPtr, BufferEnd)) {
1732 CurPtr = End;
1733
1734 // Skip ahead to the end of line.
1735 while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n')
1736 ++CurPtr;
1737
1738 BufferPtr = CurPtr;
1739
1740 // No longer in the conflict marker.
1741 IsInConflictMarker = false;
1742 return true;
1743 }
1744
1745 return false;
1746}
1747
Reid Spencer5f016e22007-07-11 17:01:13 +00001748
1749/// LexTokenInternal - This implements a simple C family lexer. It is an
1750/// extremely performance critical piece of code. This assumes that the buffer
Chris Lattnerefb173d2009-07-07 05:05:42 +00001751/// has a null character at the end of the file. This returns a preprocessing
1752/// token, not a normal token, as such, it is an internal interface. It assumes
1753/// that the Flags of result have been cleared before calling this.
Chris Lattnerd2177732007-07-20 16:59:19 +00001754void Lexer::LexTokenInternal(Token &Result) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001755LexNextToken:
1756 // New token, can't need cleaning yet.
Chris Lattnerd2177732007-07-20 16:59:19 +00001757 Result.clearFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00001758 Result.setIdentifierInfo(0);
Mike Stump1eb44332009-09-09 15:08:12 +00001759
Reid Spencer5f016e22007-07-11 17:01:13 +00001760 // CurPtr - Cache BufferPtr in an automatic variable.
1761 const char *CurPtr = BufferPtr;
1762
1763 // Small amounts of horizontal whitespace is very common between tokens.
1764 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
1765 ++CurPtr;
1766 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
1767 ++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001768
Chris Lattnerd88dc482008-10-12 04:05:48 +00001769 // If we are keeping whitespace and other tokens, just return what we just
1770 // skipped. The next lexer invocation will return the token after the
1771 // whitespace.
1772 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001773 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd88dc482008-10-12 04:05:48 +00001774 return;
1775 }
Mike Stump1eb44332009-09-09 15:08:12 +00001776
Reid Spencer5f016e22007-07-11 17:01:13 +00001777 BufferPtr = CurPtr;
Chris Lattnerd2177732007-07-20 16:59:19 +00001778 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001779 }
Mike Stump1eb44332009-09-09 15:08:12 +00001780
Reid Spencer5f016e22007-07-11 17:01:13 +00001781 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
Mike Stump1eb44332009-09-09 15:08:12 +00001782
Reid Spencer5f016e22007-07-11 17:01:13 +00001783 // Read a character, advancing over it.
1784 char Char = getAndAdvanceChar(CurPtr, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001785 tok::TokenKind Kind;
Mike Stump1eb44332009-09-09 15:08:12 +00001786
Reid Spencer5f016e22007-07-11 17:01:13 +00001787 switch (Char) {
1788 case 0: // Null.
1789 // Found end of file?
1790 if (CurPtr-1 == BufferEnd) {
1791 // Read the PP instance variable into an automatic variable, because
1792 // LexEndOfFile will often delete 'this'.
Chris Lattner168ae2d2007-10-17 20:41:00 +00001793 Preprocessor *PPCache = PP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001794 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
1795 return; // Got a token to return.
Chris Lattner168ae2d2007-10-17 20:41:00 +00001796 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
1797 return PPCache->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001798 }
Mike Stump1eb44332009-09-09 15:08:12 +00001799
Chris Lattner74d15df2008-11-22 02:02:22 +00001800 if (!isLexingRawMode())
1801 Diag(CurPtr-1, diag::null_in_file);
Chris Lattnerd2177732007-07-20 16:59:19 +00001802 Result.setFlag(Token::LeadingSpace);
Chris Lattnerd88dc482008-10-12 04:05:48 +00001803 if (SkipWhitespace(Result, CurPtr))
1804 return; // KeepWhitespaceMode
Mike Stump1eb44332009-09-09 15:08:12 +00001805
Reid Spencer5f016e22007-07-11 17:01:13 +00001806 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattnera2bf1052009-12-17 05:29:40 +00001807
1808 case 26: // DOS & CP/M EOF: "^Z".
1809 // If we're in Microsoft extensions mode, treat this as end of file.
1810 if (Features.Microsoft) {
1811 // Read the PP instance variable into an automatic variable, because
1812 // LexEndOfFile will often delete 'this'.
1813 Preprocessor *PPCache = PP;
1814 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
1815 return; // Got a token to return.
1816 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
1817 return PPCache->Lex(Result);
1818 }
1819 // If Microsoft extensions are disabled, this is just random garbage.
1820 Kind = tok::unknown;
1821 break;
1822
Reid Spencer5f016e22007-07-11 17:01:13 +00001823 case '\n':
1824 case '\r':
1825 // If we are inside a preprocessor directive and we see the end of line,
1826 // we know we are done with the directive, so return an EOM token.
1827 if (ParsingPreprocessorDirective) {
1828 // Done parsing the "line".
1829 ParsingPreprocessorDirective = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001830
Reid Spencer5f016e22007-07-11 17:01:13 +00001831 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattnerf744d132008-10-12 03:27:19 +00001832 SetCommentRetentionState(PP->getCommentRetentionState());
Mike Stump1eb44332009-09-09 15:08:12 +00001833
Reid Spencer5f016e22007-07-11 17:01:13 +00001834 // Since we consumed a newline, we are back at the start of a line.
1835 IsAtStartOfLine = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001836
Chris Lattner9e6293d2008-10-12 04:51:35 +00001837 Kind = tok::eom;
Reid Spencer5f016e22007-07-11 17:01:13 +00001838 break;
1839 }
1840 // The returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00001841 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00001842 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00001843 Result.clearFlag(Token::LeadingSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001844
Chris Lattnerd88dc482008-10-12 04:05:48 +00001845 if (SkipWhitespace(Result, CurPtr))
1846 return; // KeepWhitespaceMode
Reid Spencer5f016e22007-07-11 17:01:13 +00001847 goto LexNextToken; // GCC isn't tail call eliminating.
1848 case ' ':
1849 case '\t':
1850 case '\f':
1851 case '\v':
Chris Lattner8133cfc2007-07-22 06:29:05 +00001852 SkipHorizontalWhitespace:
Chris Lattnerd2177732007-07-20 16:59:19 +00001853 Result.setFlag(Token::LeadingSpace);
Chris Lattnerd88dc482008-10-12 04:05:48 +00001854 if (SkipWhitespace(Result, CurPtr))
1855 return; // KeepWhitespaceMode
Chris Lattner8133cfc2007-07-22 06:29:05 +00001856
1857 SkipIgnoredUnits:
1858 CurPtr = BufferPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001859
Chris Lattner8133cfc2007-07-22 06:29:05 +00001860 // If the next token is obviously a // or /* */ comment, skip it efficiently
1861 // too (without going through the big switch stmt).
Chris Lattner8402c732009-01-16 22:39:25 +00001862 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
1863 Features.BCPLComment) {
Chris Lattner046c2272010-01-18 22:35:47 +00001864 if (SkipBCPLComment(Result, CurPtr+2))
1865 return; // There is a token to return.
Chris Lattner8133cfc2007-07-22 06:29:05 +00001866 goto SkipIgnoredUnits;
Chris Lattnerfa95a012008-10-12 03:22:02 +00001867 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
Chris Lattner046c2272010-01-18 22:35:47 +00001868 if (SkipBlockComment(Result, CurPtr+2))
1869 return; // There is a token to return.
Chris Lattner8133cfc2007-07-22 06:29:05 +00001870 goto SkipIgnoredUnits;
1871 } else if (isHorizontalWhitespace(*CurPtr)) {
1872 goto SkipHorizontalWhitespace;
1873 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001874 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattnera2bf1052009-12-17 05:29:40 +00001875
Chris Lattner3a570772008-01-03 17:58:54 +00001876 // C99 6.4.4.1: Integer Constants.
1877 // C99 6.4.4.2: Floating Constants.
1878 case '0': case '1': case '2': case '3': case '4':
1879 case '5': case '6': case '7': case '8': case '9':
1880 // Notify MIOpt that we read a non-whitespace/non-comment token.
1881 MIOpt.ReadToken();
1882 return LexNumericConstant(Result, CurPtr);
Mike Stump1eb44332009-09-09 15:08:12 +00001883
Chris Lattner3a570772008-01-03 17:58:54 +00001884 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
Reid Spencer5f016e22007-07-11 17:01:13 +00001885 // Notify MIOpt that we read a non-whitespace/non-comment token.
1886 MIOpt.ReadToken();
1887 Char = getCharAndSize(CurPtr, SizeTmp);
1888
1889 // Wide string literal.
1890 if (Char == '"')
1891 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
1892 true);
1893
1894 // Wide character constant.
1895 if (Char == '\'')
1896 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
1897 // FALL THROUGH, treating L like the start of an identifier.
Mike Stump1eb44332009-09-09 15:08:12 +00001898
Reid Spencer5f016e22007-07-11 17:01:13 +00001899 // C99 6.4.2: Identifiers.
1900 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
1901 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
1902 case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U':
1903 case 'V': case 'W': case 'X': case 'Y': case 'Z':
1904 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
1905 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
1906 case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u':
1907 case 'v': case 'w': case 'x': case 'y': case 'z':
1908 case '_':
1909 // Notify MIOpt that we read a non-whitespace/non-comment token.
1910 MIOpt.ReadToken();
1911 return LexIdentifier(Result, CurPtr);
Chris Lattner3a570772008-01-03 17:58:54 +00001912
1913 case '$': // $ in identifiers.
1914 if (Features.DollarIdents) {
Chris Lattner74d15df2008-11-22 02:02:22 +00001915 if (!isLexingRawMode())
1916 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
Chris Lattner3a570772008-01-03 17:58:54 +00001917 // Notify MIOpt that we read a non-whitespace/non-comment token.
1918 MIOpt.ReadToken();
1919 return LexIdentifier(Result, CurPtr);
1920 }
Mike Stump1eb44332009-09-09 15:08:12 +00001921
Chris Lattner9e6293d2008-10-12 04:51:35 +00001922 Kind = tok::unknown;
Chris Lattner3a570772008-01-03 17:58:54 +00001923 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001924
Reid Spencer5f016e22007-07-11 17:01:13 +00001925 // C99 6.4.4: Character Constants.
1926 case '\'':
1927 // Notify MIOpt that we read a non-whitespace/non-comment token.
1928 MIOpt.ReadToken();
1929 return LexCharConstant(Result, CurPtr);
1930
1931 // C99 6.4.5: String Literals.
1932 case '"':
1933 // Notify MIOpt that we read a non-whitespace/non-comment token.
1934 MIOpt.ReadToken();
1935 return LexStringLiteral(Result, CurPtr, false);
1936
1937 // C99 6.4.6: Punctuators.
1938 case '?':
Chris Lattner9e6293d2008-10-12 04:51:35 +00001939 Kind = tok::question;
Reid Spencer5f016e22007-07-11 17:01:13 +00001940 break;
1941 case '[':
Chris Lattner9e6293d2008-10-12 04:51:35 +00001942 Kind = tok::l_square;
Reid Spencer5f016e22007-07-11 17:01:13 +00001943 break;
1944 case ']':
Chris Lattner9e6293d2008-10-12 04:51:35 +00001945 Kind = tok::r_square;
Reid Spencer5f016e22007-07-11 17:01:13 +00001946 break;
1947 case '(':
Chris Lattner9e6293d2008-10-12 04:51:35 +00001948 Kind = tok::l_paren;
Reid Spencer5f016e22007-07-11 17:01:13 +00001949 break;
1950 case ')':
Chris Lattner9e6293d2008-10-12 04:51:35 +00001951 Kind = tok::r_paren;
Reid Spencer5f016e22007-07-11 17:01:13 +00001952 break;
1953 case '{':
Chris Lattner9e6293d2008-10-12 04:51:35 +00001954 Kind = tok::l_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00001955 break;
1956 case '}':
Chris Lattner9e6293d2008-10-12 04:51:35 +00001957 Kind = tok::r_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00001958 break;
1959 case '.':
1960 Char = getCharAndSize(CurPtr, SizeTmp);
1961 if (Char >= '0' && Char <= '9') {
1962 // Notify MIOpt that we read a non-whitespace/non-comment token.
1963 MIOpt.ReadToken();
1964
1965 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
1966 } else if (Features.CPlusPlus && Char == '*') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001967 Kind = tok::periodstar;
Reid Spencer5f016e22007-07-11 17:01:13 +00001968 CurPtr += SizeTmp;
1969 } else if (Char == '.' &&
1970 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001971 Kind = tok::ellipsis;
Reid Spencer5f016e22007-07-11 17:01:13 +00001972 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1973 SizeTmp2, Result);
1974 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001975 Kind = tok::period;
Reid Spencer5f016e22007-07-11 17:01:13 +00001976 }
1977 break;
1978 case '&':
1979 Char = getCharAndSize(CurPtr, SizeTmp);
1980 if (Char == '&') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001981 Kind = tok::ampamp;
Reid Spencer5f016e22007-07-11 17:01:13 +00001982 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1983 } else if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001984 Kind = tok::ampequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00001985 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1986 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001987 Kind = tok::amp;
Reid Spencer5f016e22007-07-11 17:01:13 +00001988 }
1989 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001990 case '*':
Reid Spencer5f016e22007-07-11 17:01:13 +00001991 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001992 Kind = tok::starequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00001993 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1994 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001995 Kind = tok::star;
Reid Spencer5f016e22007-07-11 17:01:13 +00001996 }
1997 break;
1998 case '+':
1999 Char = getCharAndSize(CurPtr, SizeTmp);
2000 if (Char == '+') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002001 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002002 Kind = tok::plusplus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002003 } else if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002004 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002005 Kind = tok::plusequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002006 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002007 Kind = tok::plus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002008 }
2009 break;
2010 case '-':
2011 Char = getCharAndSize(CurPtr, SizeTmp);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002012 if (Char == '-') { // --
Reid Spencer5f016e22007-07-11 17:01:13 +00002013 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002014 Kind = tok::minusminus;
Mike Stump1eb44332009-09-09 15:08:12 +00002015 } else if (Char == '>' && Features.CPlusPlus &&
Chris Lattner9e6293d2008-10-12 04:51:35 +00002016 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
Reid Spencer5f016e22007-07-11 17:01:13 +00002017 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2018 SizeTmp2, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002019 Kind = tok::arrowstar;
2020 } else if (Char == '>') { // ->
Reid Spencer5f016e22007-07-11 17:01:13 +00002021 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002022 Kind = tok::arrow;
2023 } else 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::minusequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002026 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002027 Kind = tok::minus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002028 }
2029 break;
2030 case '~':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002031 Kind = tok::tilde;
Reid Spencer5f016e22007-07-11 17:01:13 +00002032 break;
2033 case '!':
2034 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002035 Kind = tok::exclaimequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002036 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2037 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002038 Kind = tok::exclaim;
Reid Spencer5f016e22007-07-11 17:01:13 +00002039 }
2040 break;
2041 case '/':
2042 // 6.4.9: Comments
2043 Char = getCharAndSize(CurPtr, SizeTmp);
2044 if (Char == '/') { // BCPL comment.
Chris Lattner8402c732009-01-16 22:39:25 +00002045 // Even if BCPL comments are disabled (e.g. in C89 mode), we generally
2046 // want to lex this as a comment. There is one problem with this though,
2047 // that in one particular corner case, this can change the behavior of the
2048 // resultant program. For example, In "foo //**/ bar", C89 would lex
2049 // this as "foo / bar" and langauges with BCPL comments would lex it as
2050 // "foo". Check to see if the character after the second slash is a '*'.
2051 // If so, we will lex that as a "/" instead of the start of a comment.
2052 if (Features.BCPLComment ||
2053 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*') {
2054 if (SkipBCPLComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattner046c2272010-01-18 22:35:47 +00002055 return; // There is a token to return.
Mike Stump1eb44332009-09-09 15:08:12 +00002056
Chris Lattner8402c732009-01-16 22:39:25 +00002057 // It is common for the tokens immediately after a // comment to be
2058 // whitespace (indentation for the next line). Instead of going through
2059 // the big switch, handle it efficiently now.
2060 goto SkipIgnoredUnits;
2061 }
2062 }
Mike Stump1eb44332009-09-09 15:08:12 +00002063
Chris Lattner8402c732009-01-16 22:39:25 +00002064 if (Char == '*') { // /**/ comment.
Reid Spencer5f016e22007-07-11 17:01:13 +00002065 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattner046c2272010-01-18 22:35:47 +00002066 return; // There is a token to return.
Chris Lattner2d381892008-10-12 04:15:42 +00002067 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattner8402c732009-01-16 22:39:25 +00002068 }
Mike Stump1eb44332009-09-09 15:08:12 +00002069
Chris Lattner8402c732009-01-16 22:39:25 +00002070 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002071 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002072 Kind = tok::slashequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002073 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002074 Kind = tok::slash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002075 }
2076 break;
2077 case '%':
2078 Char = getCharAndSize(CurPtr, SizeTmp);
2079 if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002080 Kind = tok::percentequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002081 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2082 } else if (Features.Digraphs && Char == '>') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002083 Kind = tok::r_brace; // '%>' -> '}'
Reid Spencer5f016e22007-07-11 17:01:13 +00002084 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2085 } else if (Features.Digraphs && Char == ':') {
2086 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2087 Char = getCharAndSize(CurPtr, SizeTmp);
2088 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002089 Kind = tok::hashhash; // '%:%:' -> '##'
Reid Spencer5f016e22007-07-11 17:01:13 +00002090 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2091 SizeTmp2, Result);
2092 } else if (Char == '@' && Features.Microsoft) { // %:@ -> #@ -> Charize
Reid Spencer5f016e22007-07-11 17:01:13 +00002093 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner74d15df2008-11-22 02:02:22 +00002094 if (!isLexingRawMode())
2095 Diag(BufferPtr, diag::charize_microsoft_ext);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002096 Kind = tok::hashat;
Chris Lattnere91e9322009-03-18 20:58:27 +00002097 } else { // '%:' -> '#'
Reid Spencer5f016e22007-07-11 17:01:13 +00002098 // We parsed a # character. If this occurs at the start of the line,
2099 // it's actually the start of a preprocessing directive. Callback to
2100 // the preprocessor to handle it.
2101 // FIXME: -fpreprocessed mode??
Chris Lattner766703b2009-05-13 06:10:29 +00002102 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer) {
Chris Lattnere91e9322009-03-18 20:58:27 +00002103 FormTokenWithChars(Result, CurPtr, tok::hash);
Chris Lattner168ae2d2007-10-17 20:41:00 +00002104 PP->HandleDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00002105
Reid Spencer5f016e22007-07-11 17:01:13 +00002106 // As an optimization, if the preprocessor didn't switch lexers, tail
2107 // recurse.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002108 if (PP->isCurrentLexer(this)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002109 // Start a new token. If this is a #include or something, the PP may
2110 // want us starting at the beginning of the line again. If so, set
Chris Lattner515f43f2010-04-12 23:04:41 +00002111 // the StartOfLine flag and clear LeadingSpace.
Reid Spencer5f016e22007-07-11 17:01:13 +00002112 if (IsAtStartOfLine) {
Chris Lattnerd2177732007-07-20 16:59:19 +00002113 Result.setFlag(Token::StartOfLine);
Chris Lattner515f43f2010-04-12 23:04:41 +00002114 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002115 IsAtStartOfLine = false;
2116 }
2117 goto LexNextToken; // GCC isn't tail call eliminating.
2118 }
Mike Stump1eb44332009-09-09 15:08:12 +00002119
Chris Lattner168ae2d2007-10-17 20:41:00 +00002120 return PP->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002121 }
Mike Stump1eb44332009-09-09 15:08:12 +00002122
Chris Lattnere91e9322009-03-18 20:58:27 +00002123 Kind = tok::hash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002124 }
2125 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002126 Kind = tok::percent;
Reid Spencer5f016e22007-07-11 17:01:13 +00002127 }
2128 break;
2129 case '<':
2130 Char = getCharAndSize(CurPtr, SizeTmp);
2131 if (ParsingFilename) {
Chris Lattner9cb51ce2009-04-17 23:56:52 +00002132 return LexAngledStringLiteral(Result, CurPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +00002133 } else if (Char == '<') {
Chris Lattner34f349d2009-12-14 06:16:57 +00002134 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
2135 if (After == '=') {
2136 Kind = tok::lesslessequal;
2137 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2138 SizeTmp2, Result);
2139 } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) {
2140 // If this is actually a '<<<<<<<' version control conflict marker,
2141 // recognize it as such and recover nicely.
2142 goto LexNextToken;
2143 } else {
2144 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2145 Kind = tok::lessless;
2146 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002147 } else if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002148 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002149 Kind = tok::lessequal;
2150 } else if (Features.Digraphs && Char == ':') { // '<:' -> '['
Reid Spencer5f016e22007-07-11 17:01:13 +00002151 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002152 Kind = tok::l_square;
2153 } else if (Features.Digraphs && Char == '%') { // '<%' -> '{'
Reid Spencer5f016e22007-07-11 17:01:13 +00002154 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002155 Kind = tok::l_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00002156 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002157 Kind = tok::less;
Reid Spencer5f016e22007-07-11 17:01:13 +00002158 }
2159 break;
2160 case '>':
2161 Char = getCharAndSize(CurPtr, SizeTmp);
2162 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002163 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002164 Kind = tok::greaterequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002165 } else if (Char == '>') {
Chris Lattner34f349d2009-12-14 06:16:57 +00002166 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
2167 if (After == '=') {
2168 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2169 SizeTmp2, Result);
2170 Kind = tok::greatergreaterequal;
2171 } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) {
2172 // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
2173 goto LexNextToken;
2174 } else {
2175 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2176 Kind = tok::greatergreater;
2177 }
2178
Reid Spencer5f016e22007-07-11 17:01:13 +00002179 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002180 Kind = tok::greater;
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::caretequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002188 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002189 Kind = tok::caret;
Reid Spencer5f016e22007-07-11 17:01:13 +00002190 }
2191 break;
2192 case '|':
2193 Char = getCharAndSize(CurPtr, SizeTmp);
2194 if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002195 Kind = tok::pipeequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002196 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2197 } else if (Char == '|') {
Chris Lattner34f349d2009-12-14 06:16:57 +00002198 // If this is '|||||||' and we're in a conflict marker, ignore it.
2199 if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
2200 goto LexNextToken;
Chris Lattner9e6293d2008-10-12 04:51:35 +00002201 Kind = tok::pipepipe;
Reid Spencer5f016e22007-07-11 17:01:13 +00002202 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2203 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002204 Kind = tok::pipe;
Reid Spencer5f016e22007-07-11 17:01:13 +00002205 }
2206 break;
2207 case ':':
2208 Char = getCharAndSize(CurPtr, SizeTmp);
2209 if (Features.Digraphs && Char == '>') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002210 Kind = tok::r_square; // ':>' -> ']'
Reid Spencer5f016e22007-07-11 17:01:13 +00002211 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2212 } else if (Features.CPlusPlus && Char == ':') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002213 Kind = tok::coloncolon;
Reid Spencer5f016e22007-07-11 17:01:13 +00002214 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump1eb44332009-09-09 15:08:12 +00002215 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002216 Kind = tok::colon;
Reid Spencer5f016e22007-07-11 17:01:13 +00002217 }
2218 break;
2219 case ';':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002220 Kind = tok::semi;
Reid Spencer5f016e22007-07-11 17:01:13 +00002221 break;
2222 case '=':
2223 Char = getCharAndSize(CurPtr, SizeTmp);
2224 if (Char == '=') {
Chris Lattner34f349d2009-12-14 06:16:57 +00002225 // If this is '=======' and we're in a conflict marker, ignore it.
2226 if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
2227 goto LexNextToken;
2228
Chris Lattner9e6293d2008-10-12 04:51:35 +00002229 Kind = tok::equalequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002230 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump1eb44332009-09-09 15:08:12 +00002231 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002232 Kind = tok::equal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002233 }
2234 break;
2235 case ',':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002236 Kind = tok::comma;
Reid Spencer5f016e22007-07-11 17:01:13 +00002237 break;
2238 case '#':
2239 Char = getCharAndSize(CurPtr, SizeTmp);
2240 if (Char == '#') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002241 Kind = tok::hashhash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002242 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2243 } else if (Char == '@' && Features.Microsoft) { // #@ -> Charize
Chris Lattner9e6293d2008-10-12 04:51:35 +00002244 Kind = tok::hashat;
Chris Lattner74d15df2008-11-22 02:02:22 +00002245 if (!isLexingRawMode())
2246 Diag(BufferPtr, diag::charize_microsoft_ext);
Reid Spencer5f016e22007-07-11 17:01:13 +00002247 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2248 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +00002249 // We parsed a # character. If this occurs at the start of the line,
2250 // it's actually the start of a preprocessing directive. Callback to
2251 // the preprocessor to handle it.
2252 // FIXME: -fpreprocessed mode??
Chris Lattner766703b2009-05-13 06:10:29 +00002253 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer) {
Chris Lattnere91e9322009-03-18 20:58:27 +00002254 FormTokenWithChars(Result, CurPtr, tok::hash);
Chris Lattner168ae2d2007-10-17 20:41:00 +00002255 PP->HandleDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00002256
Reid Spencer5f016e22007-07-11 17:01:13 +00002257 // As an optimization, if the preprocessor didn't switch lexers, tail
2258 // recurse.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002259 if (PP->isCurrentLexer(this)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002260 // Start a new token. If this is a #include or something, the PP may
2261 // want us starting at the beginning of the line again. If so, set
Chris Lattner515f43f2010-04-12 23:04:41 +00002262 // the StartOfLine flag and clear LeadingSpace.
Reid Spencer5f016e22007-07-11 17:01:13 +00002263 if (IsAtStartOfLine) {
Chris Lattnerd2177732007-07-20 16:59:19 +00002264 Result.setFlag(Token::StartOfLine);
Chris Lattner515f43f2010-04-12 23:04:41 +00002265 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002266 IsAtStartOfLine = false;
2267 }
2268 goto LexNextToken; // GCC isn't tail call eliminating.
2269 }
Chris Lattner168ae2d2007-10-17 20:41:00 +00002270 return PP->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002271 }
Mike Stump1eb44332009-09-09 15:08:12 +00002272
Chris Lattnere91e9322009-03-18 20:58:27 +00002273 Kind = tok::hash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002274 }
2275 break;
2276
Chris Lattner3a570772008-01-03 17:58:54 +00002277 case '@':
2278 // Objective C support.
2279 if (CurPtr[-1] == '@' && Features.ObjC1)
Chris Lattner9e6293d2008-10-12 04:51:35 +00002280 Kind = tok::at;
Chris Lattner3a570772008-01-03 17:58:54 +00002281 else
Chris Lattner9e6293d2008-10-12 04:51:35 +00002282 Kind = tok::unknown;
Chris Lattner3a570772008-01-03 17:58:54 +00002283 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002284
Reid Spencer5f016e22007-07-11 17:01:13 +00002285 case '\\':
2286 // FIXME: UCN's.
2287 // FALL THROUGH.
2288 default:
Chris Lattner9e6293d2008-10-12 04:51:35 +00002289 Kind = tok::unknown;
Reid Spencer5f016e22007-07-11 17:01:13 +00002290 break;
2291 }
Mike Stump1eb44332009-09-09 15:08:12 +00002292
Reid Spencer5f016e22007-07-11 17:01:13 +00002293 // Notify MIOpt that we read a non-whitespace/non-comment token.
2294 MIOpt.ReadToken();
2295
2296 // Update the location of token as well as BufferPtr.
Chris Lattner9e6293d2008-10-12 04:51:35 +00002297 FormTokenWithChars(Result, CurPtr, Kind);
Reid Spencer5f016e22007-07-11 17:01:13 +00002298}