blob: 772a4d9684ddbac501a28e67705cb94635ea411e [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- Lexer.cpp - C Language Family Lexer ------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Lexer and Token interfaces.
11//
12//===----------------------------------------------------------------------===//
13//
14// TODO: GCC Diagnostics emitted by the lexer:
15// PEDWARN: (form feed|vertical tab) in preprocessing directive
16//
17// Universal characters, unicode, char mapping:
18// WARNING: `%.*s' is not in NFKC
19// WARNING: `%.*s' is not in NFC
20//
21// Other:
22// TODO: Options to support:
23// -fexec-charset,-fwide-exec-charset
24//
25//===----------------------------------------------------------------------===//
26
27#include "clang/Lex/Lexer.h"
28#include "clang/Lex/Preprocessor.h"
29#include "clang/Basic/Diagnostic.h"
30#include "clang/Basic/SourceManager.h"
31#include "llvm/Support/Compiler.h"
32#include "llvm/Support/MemoryBuffer.h"
33#include <cctype>
34using namespace clang;
35
36static void InitCharacterInfo();
37
Chris Lattneraa9bdf12007-10-07 08:47:24 +000038//===----------------------------------------------------------------------===//
39// Token Class Implementation
40//===----------------------------------------------------------------------===//
41
42/// isObjCAtKeyword - Return true if we have an ObjC keyword identifier.
43bool Token::isObjCAtKeyword(tok::ObjCKeywordKind objcKey) const {
Douglas Gregora7502582008-12-01 21:46:47 +000044 if (IdentifierInfo *II = getIdentifierInfo())
45 return II->getObjCKeywordID() == objcKey;
46 return false;
Chris Lattneraa9bdf12007-10-07 08:47:24 +000047}
48
49/// getObjCKeywordID - Return the ObjC keyword kind.
50tok::ObjCKeywordKind Token::getObjCKeywordID() const {
51 IdentifierInfo *specId = getIdentifierInfo();
52 return specId ? specId->getObjCKeywordID() : tok::objc_not_keyword;
53}
54
Chris Lattner7208a4b2007-12-13 01:59:49 +000055
Chris Lattneraa9bdf12007-10-07 08:47:24 +000056//===----------------------------------------------------------------------===//
57// Lexer Class Implementation
58//===----------------------------------------------------------------------===//
59
Chris Lattner9bb53672009-01-17 06:55:17 +000060void Lexer::InitLexer(const char *BufStart, const char *BufPtr,
61 const char *BufEnd) {
62 InitCharacterInfo();
63
64 BufferStart = BufStart;
65 BufferPtr = BufPtr;
66 BufferEnd = BufEnd;
67
68 assert(BufEnd[0] == 0 &&
69 "We assume that the input buffer has a null character at the end"
70 " to simplify lexing!");
71
72 Is_PragmaLexer = false;
73
74 // Start of the file is a start of line.
75 IsAtStartOfLine = true;
76
77 // We are not after parsing a #.
78 ParsingPreprocessorDirective = false;
79
80 // We are not after parsing #include.
81 ParsingFilename = false;
82
83 // We are not in raw mode. Raw mode disables diagnostics and interpretation
84 // of tokens (e.g. identifiers, thus disabling macro expansion). It is used
85 // to quickly lex the tokens of the buffer, e.g. when handling a "#if 0" block
86 // or otherwise skipping over tokens.
87 LexingRawMode = false;
88
89 // Default to not keeping comments.
90 ExtendedTokenMode = 0;
91}
92
Chris Lattner54edb962009-01-17 07:56:59 +000093/// Lexer constructor - Create a new lexer object for the specified buffer
94/// with the specified preprocessor managing the lexing process. This lexer
95/// assumes that the associated file buffer and Preprocessor objects will
96/// outlive it, so it doesn't take ownership of either of them.
Chris Lattner5df086f2009-01-17 08:03:42 +000097Lexer::Lexer(FileID FID, Preprocessor &PP)
98 : PreprocessorLexer(&PP, FID),
99 FileLoc(PP.getSourceManager().getLocForStartOfFile(FID)),
100 Features(PP.getLangOptions()) {
Chris Lattner54edb962009-01-17 07:56:59 +0000101
Chris Lattner5df086f2009-01-17 08:03:42 +0000102 const llvm::MemoryBuffer *InputFile = PP.getSourceManager().getBuffer(FID);
Chris Lattner54edb962009-01-17 07:56:59 +0000103
104 InitLexer(InputFile->getBufferStart(), InputFile->getBufferStart(),
105 InputFile->getBufferEnd());
106
107 // Default to keeping comments if the preprocessor wants them.
108 SetCommentRetentionState(PP.getCommentRetentionState());
109}
Chris Lattneraa9bdf12007-10-07 08:47:24 +0000110
Chris Lattner342dccb2007-10-17 20:41:00 +0000111/// Lexer constructor - Create a new lexer object for the specified buffer
112/// with the specified preprocessor managing the lexing process. This lexer
113/// assumes that the associated file buffer and Preprocessor objects will
114/// outlive it, so it doesn't take ownership of either of them.
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000115Lexer::Lexer(SourceLocation fileloc, Preprocessor &PP,
Chris Lattner9bb53672009-01-17 06:55:17 +0000116 const char *BufPtr, const char *BufEnd)
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000117// FIXME: This is really horrible and only needed for _Pragma lexers, split this
118// out of the main lexer path!
119 : PreprocessorLexer(&PP,
120 PP.getSourceManager().getCanonicalFileID(
121 PP.getSourceManager().getSpellingLoc(fileloc))),
Chris Lattner5df086f2009-01-17 08:03:42 +0000122 FileLoc(fileloc),
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000123 Features(PP.getLangOptions()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000124
Chris Lattner54edb962009-01-17 07:56:59 +0000125 InitLexer(PP.getSourceManager().getBuffer(getFileID())->getBufferStart(),
126 BufPtr, BufEnd);
Chris Lattner4b009652007-07-25 00:24:17 +0000127
Chris Lattner867a87b2008-10-12 04:05:48 +0000128 // Default to keeping comments if the preprocessor wants them.
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000129 SetCommentRetentionState(PP.getCommentRetentionState());
Chris Lattner4b009652007-07-25 00:24:17 +0000130}
131
Chris Lattner342dccb2007-10-17 20:41:00 +0000132/// Lexer constructor - Create a new raw lexer object. This object is only
Chris Lattner0b5892e2008-10-12 01:15:46 +0000133/// suitable for calls to 'LexRawToken'. This lexer assumes that the text
134/// range will outlive it, so it doesn't take ownership of it.
Chris Lattner342dccb2007-10-17 20:41:00 +0000135Lexer::Lexer(SourceLocation fileloc, const LangOptions &features,
Chris Lattnerded7b322009-01-17 07:42:27 +0000136 const char *BufStart, const char *BufPtr, const char *BufEnd)
Chris Lattneref63fd52009-01-17 03:48:08 +0000137 : FileLoc(fileloc), Features(features) {
Chris Lattner9bb53672009-01-17 06:55:17 +0000138
Chris Lattner9bb53672009-01-17 06:55:17 +0000139 InitLexer(BufStart, BufPtr, BufEnd);
Chris Lattner342dccb2007-10-17 20:41:00 +0000140
141 // We *are* in raw mode.
142 LexingRawMode = true;
Chris Lattner342dccb2007-10-17 20:41:00 +0000143}
144
Chris Lattnerc7b23592009-01-17 07:35:14 +0000145/// Lexer constructor - Create a new raw lexer object. This object is only
146/// suitable for calls to 'LexRawToken'. This lexer assumes that the text
147/// range will outlive it, so it doesn't take ownership of it.
148Lexer::Lexer(FileID FID, const SourceManager &SM, const LangOptions &features)
149 : FileLoc(SM.getLocForStartOfFile(FID)), Features(features) {
150 const llvm::MemoryBuffer *FromFile = SM.getBuffer(FID);
151
152 InitLexer(FromFile->getBufferStart(), FromFile->getBufferStart(),
153 FromFile->getBufferEnd());
154
155 // We *are* in raw mode.
156 LexingRawMode = true;
157}
158
Chris Lattner342dccb2007-10-17 20:41:00 +0000159
Chris Lattner4b009652007-07-25 00:24:17 +0000160/// Stringify - Convert the specified string into a C string, with surrounding
161/// ""'s, and with escaped \ and " characters.
162std::string Lexer::Stringify(const std::string &Str, bool Charify) {
163 std::string Result = Str;
164 char Quote = Charify ? '\'' : '"';
165 for (unsigned i = 0, e = Result.size(); i != e; ++i) {
166 if (Result[i] == '\\' || Result[i] == Quote) {
167 Result.insert(Result.begin()+i, '\\');
168 ++i; ++e;
169 }
170 }
171 return Result;
172}
173
174/// Stringify - Convert the specified string into a C string by escaping '\'
175/// and " characters. This does not add surrounding ""'s to the string.
176void Lexer::Stringify(llvm::SmallVectorImpl<char> &Str) {
177 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
178 if (Str[i] == '\\' || Str[i] == '"') {
179 Str.insert(Str.begin()+i, '\\');
180 ++i; ++e;
181 }
182 }
183}
184
185
Chris Lattner761d76b2007-10-17 21:18:47 +0000186/// MeasureTokenLength - Relex the token at the specified location and return
187/// its length in bytes in the input file. If the token needs cleaning (e.g.
188/// includes a trigraph or an escaped newline) then this count includes bytes
189/// that are part of that.
190unsigned Lexer::MeasureTokenLength(SourceLocation Loc,
191 const SourceManager &SM) {
192 // If this comes from a macro expansion, we really do want the macro name, not
193 // the token this macro expanded to.
Chris Lattner18c8dc02009-01-16 07:36:28 +0000194 Loc = SM.getInstantiationLoc(Loc);
Chris Lattner761d76b2007-10-17 21:18:47 +0000195
196 const char *StrData = SM.getCharacterData(Loc);
197
198 // TODO: this could be special cased for common tokens like identifiers, ')',
199 // etc to make this faster, if it mattered. Just look at StrData[0] to handle
200 // all obviously single-char tokens. This could use
201 // Lexer::isObviouslySimpleCharacter for example to handle identifiers or
202 // something.
Chris Lattnerded7b322009-01-17 07:42:27 +0000203 std::pair<const char *,const char *> Buffer = SM.getBufferData(Loc);
Chris Lattner761d76b2007-10-17 21:18:47 +0000204
205 // Create a langops struct and enable trigraphs. This is sufficient for
206 // measuring tokens.
207 LangOptions LangOpts;
208 LangOpts.Trigraphs = true;
209
210 // Create a lexer starting at the beginning of this token.
Chris Lattnerded7b322009-01-17 07:42:27 +0000211 Lexer TheLexer(Loc, LangOpts, Buffer.first, StrData, Buffer.second);
Chris Lattner761d76b2007-10-17 21:18:47 +0000212 Token TheTok;
Chris Lattner0b5892e2008-10-12 01:15:46 +0000213 TheLexer.LexFromRawLexer(TheTok);
Chris Lattner761d76b2007-10-17 21:18:47 +0000214 return TheTok.getLength();
215}
216
Chris Lattner4b009652007-07-25 00:24:17 +0000217//===----------------------------------------------------------------------===//
218// Character information.
219//===----------------------------------------------------------------------===//
220
221static unsigned char CharInfo[256];
222
223enum {
224 CHAR_HORZ_WS = 0x01, // ' ', '\t', '\f', '\v'. Note, no '\0'
225 CHAR_VERT_WS = 0x02, // '\r', '\n'
226 CHAR_LETTER = 0x04, // a-z,A-Z
227 CHAR_NUMBER = 0x08, // 0-9
228 CHAR_UNDER = 0x10, // _
229 CHAR_PERIOD = 0x20 // .
230};
231
232static void InitCharacterInfo() {
233 static bool isInited = false;
234 if (isInited) return;
235 isInited = true;
236
237 // Intiialize the CharInfo table.
238 // TODO: statically initialize this.
239 CharInfo[(int)' '] = CharInfo[(int)'\t'] =
240 CharInfo[(int)'\f'] = CharInfo[(int)'\v'] = CHAR_HORZ_WS;
241 CharInfo[(int)'\n'] = CharInfo[(int)'\r'] = CHAR_VERT_WS;
242
243 CharInfo[(int)'_'] = CHAR_UNDER;
244 CharInfo[(int)'.'] = CHAR_PERIOD;
245 for (unsigned i = 'a'; i <= 'z'; ++i)
246 CharInfo[i] = CharInfo[i+'A'-'a'] = CHAR_LETTER;
247 for (unsigned i = '0'; i <= '9'; ++i)
248 CharInfo[i] = CHAR_NUMBER;
249}
250
251/// isIdentifierBody - Return true if this is the body character of an
252/// identifier, which is [a-zA-Z0-9_].
253static inline bool isIdentifierBody(unsigned char c) {
Hartmut Kaiserc62f6b92007-10-18 12:47:01 +0000254 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER)) ? true : false;
Chris Lattner4b009652007-07-25 00:24:17 +0000255}
256
257/// isHorizontalWhitespace - Return true if this character is horizontal
258/// whitespace: ' ', '\t', '\f', '\v'. Note that this returns false for '\0'.
259static inline bool isHorizontalWhitespace(unsigned char c) {
Hartmut Kaiserc62f6b92007-10-18 12:47:01 +0000260 return (CharInfo[c] & CHAR_HORZ_WS) ? true : false;
Chris Lattner4b009652007-07-25 00:24:17 +0000261}
262
263/// isWhitespace - Return true if this character is horizontal or vertical
264/// whitespace: ' ', '\t', '\f', '\v', '\n', '\r'. Note that this returns false
265/// for '\0'.
266static inline bool isWhitespace(unsigned char c) {
Hartmut Kaiserc62f6b92007-10-18 12:47:01 +0000267 return (CharInfo[c] & (CHAR_HORZ_WS|CHAR_VERT_WS)) ? true : false;
Chris Lattner4b009652007-07-25 00:24:17 +0000268}
269
270/// isNumberBody - Return true if this is the body character of an
271/// preprocessing number, which is [a-zA-Z0-9_.].
272static inline bool isNumberBody(unsigned char c) {
Hartmut Kaiserc62f6b92007-10-18 12:47:01 +0000273 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER|CHAR_PERIOD)) ?
274 true : false;
Chris Lattner4b009652007-07-25 00:24:17 +0000275}
276
277
278//===----------------------------------------------------------------------===//
279// Diagnostics forwarding code.
280//===----------------------------------------------------------------------===//
281
282/// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
283/// lexer buffer was all instantiated at a single point, perform the mapping.
284/// This is currently only used for _Pragma implementation, so it is the slow
285/// path of the hot getSourceLocation method. Do not allow it to be inlined.
286static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
287 SourceLocation FileLoc,
288 unsigned CharNo) DISABLE_INLINE;
289static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
290 SourceLocation FileLoc,
291 unsigned CharNo) {
292 // Otherwise, we're lexing "mapped tokens". This is used for things like
293 // _Pragma handling. Combine the instantiation location of FileLoc with the
Chris Lattnercdf600e2009-01-16 07:00:02 +0000294 // spelling location.
Chris Lattner4b009652007-07-25 00:24:17 +0000295 SourceManager &SourceMgr = PP.getSourceManager();
296
Chris Lattner18c8dc02009-01-16 07:36:28 +0000297 // Create a new SLoc which is expanded from Instantiation(FileLoc) but whose
Chris Lattnercdf600e2009-01-16 07:00:02 +0000298 // characters come from spelling(FileLoc)+Offset.
Chris Lattner18c8dc02009-01-16 07:36:28 +0000299 SourceLocation InstLoc = SourceMgr.getInstantiationLoc(FileLoc);
Chris Lattnercdf600e2009-01-16 07:00:02 +0000300 SourceLocation SpellingLoc = SourceMgr.getSpellingLoc(FileLoc);
301 SpellingLoc = SourceLocation::getFileLoc(SpellingLoc.getFileID(), CharNo);
Chris Lattner18c8dc02009-01-16 07:36:28 +0000302 return SourceMgr.getInstantiationLoc(SpellingLoc, InstLoc);
Chris Lattner4b009652007-07-25 00:24:17 +0000303}
304
305/// getSourceLocation - Return a source location identifier for the specified
306/// offset in the current file.
307SourceLocation Lexer::getSourceLocation(const char *Loc) const {
308 assert(Loc >= BufferStart && Loc <= BufferEnd &&
309 "Location out of range for this buffer!");
310
311 // In the normal case, we're just lexing from a simple file buffer, return
312 // the file id from FileLoc with the offset specified.
313 unsigned CharNo = Loc-BufferStart;
314 if (FileLoc.isFileID())
315 return SourceLocation::getFileLoc(FileLoc.getFileID(), CharNo);
316
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000317 // Otherwise, this is the _Pragma lexer case, which pretends that all of the
318 // tokens are lexed from where the _Pragma was defined.
Chris Lattner342dccb2007-10-17 20:41:00 +0000319 assert(PP && "This doesn't work on raw lexers");
320 return GetMappedTokenLoc(*PP, FileLoc, CharNo);
Chris Lattner4b009652007-07-25 00:24:17 +0000321}
322
323/// Diag - Forwarding function for diagnostics. This translate a source
324/// position in the current buffer into a SourceLocation object for rendering.
Chris Lattner9943e982008-11-22 00:59:29 +0000325DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
Chris Lattner0370d6b2008-11-18 07:59:24 +0000326 return PP->Diag(getSourceLocation(Loc), DiagID);
Chris Lattner4b009652007-07-25 00:24:17 +0000327}
Chris Lattner4b009652007-07-25 00:24:17 +0000328
329//===----------------------------------------------------------------------===//
330// Trigraph and Escaped Newline Handling Code.
331//===----------------------------------------------------------------------===//
332
333/// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
334/// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
335static char GetTrigraphCharForLetter(char Letter) {
336 switch (Letter) {
337 default: return 0;
338 case '=': return '#';
339 case ')': return ']';
340 case '(': return '[';
341 case '!': return '|';
342 case '\'': return '^';
343 case '>': return '}';
344 case '/': return '\\';
345 case '<': return '{';
346 case '-': return '~';
347 }
348}
349
350/// DecodeTrigraphChar - If the specified character is a legal trigraph when
351/// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
352/// return the result character. Finally, emit a warning about trigraph use
353/// whether trigraphs are enabled or not.
354static char DecodeTrigraphChar(const char *CP, Lexer *L) {
355 char Res = GetTrigraphCharForLetter(*CP);
Chris Lattner0370d6b2008-11-18 07:59:24 +0000356 if (!Res || !L) return Res;
357
358 if (!L->getFeatures().Trigraphs) {
Chris Lattnerf9c62772008-11-22 02:02:22 +0000359 if (!L->isLexingRawMode())
360 L->Diag(CP-2, diag::trigraph_ignored);
Chris Lattner0370d6b2008-11-18 07:59:24 +0000361 return 0;
Chris Lattner4b009652007-07-25 00:24:17 +0000362 }
Chris Lattner0370d6b2008-11-18 07:59:24 +0000363
Chris Lattnerf9c62772008-11-22 02:02:22 +0000364 if (!L->isLexingRawMode())
365 L->Diag(CP-2, diag::trigraph_converted) << std::string()+Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000366 return Res;
367}
368
369/// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
370/// get its size, and return it. This is tricky in several cases:
371/// 1. If currently at the start of a trigraph, we warn about the trigraph,
372/// then either return the trigraph (skipping 3 chars) or the '?',
373/// depending on whether trigraphs are enabled or not.
374/// 2. If this is an escaped newline (potentially with whitespace between
375/// the backslash and newline), implicitly skip the newline and return
376/// the char after it.
377/// 3. If this is a UCN, return it. FIXME: C++ UCN's?
378///
379/// This handles the slow/uncommon case of the getCharAndSize method. Here we
380/// know that we can accumulate into Size, and that we have already incremented
381/// Ptr by Size bytes.
382///
383/// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
384/// be updated to match.
385///
386char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
387 Token *Tok) {
388 // If we have a slash, look for an escaped newline.
389 if (Ptr[0] == '\\') {
390 ++Size;
391 ++Ptr;
392Slash:
393 // Common case, backslash-char where the char is not whitespace.
394 if (!isWhitespace(Ptr[0])) return '\\';
395
396 // See if we have optional whitespace characters followed by a newline.
397 {
398 unsigned SizeTmp = 0;
399 do {
400 ++SizeTmp;
401 if (Ptr[SizeTmp-1] == '\n' || Ptr[SizeTmp-1] == '\r') {
402 // Remember that this token needs to be cleaned.
403 if (Tok) Tok->setFlag(Token::NeedsCleaning);
404
405 // Warn if there was whitespace between the backslash and newline.
Chris Lattnerf9c62772008-11-22 02:02:22 +0000406 if (SizeTmp != 1 && Tok && !isLexingRawMode())
Chris Lattner4b009652007-07-25 00:24:17 +0000407 Diag(Ptr, diag::backslash_newline_space);
408
409 // If this is a \r\n or \n\r, skip the newlines.
410 if ((Ptr[SizeTmp] == '\r' || Ptr[SizeTmp] == '\n') &&
411 Ptr[SizeTmp-1] != Ptr[SizeTmp])
412 ++SizeTmp;
413
414 // Found backslash<whitespace><newline>. Parse the char after it.
415 Size += SizeTmp;
416 Ptr += SizeTmp;
417 // Use slow version to accumulate a correct size field.
418 return getCharAndSizeSlow(Ptr, Size, Tok);
419 }
420 } while (isWhitespace(Ptr[SizeTmp]));
421 }
422
423 // Otherwise, this is not an escaped newline, just return the slash.
424 return '\\';
425 }
426
427 // If this is a trigraph, process it.
428 if (Ptr[0] == '?' && Ptr[1] == '?') {
429 // If this is actually a legal trigraph (not something like "??x"), emit
430 // a trigraph warning. If so, and if trigraphs are enabled, return it.
431 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : 0)) {
432 // Remember that this token needs to be cleaned.
433 if (Tok) Tok->setFlag(Token::NeedsCleaning);
434
435 Ptr += 3;
436 Size += 3;
437 if (C == '\\') goto Slash;
438 return C;
439 }
440 }
441
442 // If this is neither, return a single character.
443 ++Size;
444 return *Ptr;
445}
446
447
448/// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
449/// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
450/// and that we have already incremented Ptr by Size bytes.
451///
452/// NOTE: When this method is updated, getCharAndSizeSlow (above) should
453/// be updated to match.
454char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
455 const LangOptions &Features) {
456 // If we have a slash, look for an escaped newline.
457 if (Ptr[0] == '\\') {
458 ++Size;
459 ++Ptr;
460Slash:
461 // Common case, backslash-char where the char is not whitespace.
462 if (!isWhitespace(Ptr[0])) return '\\';
463
464 // See if we have optional whitespace characters followed by a newline.
465 {
466 unsigned SizeTmp = 0;
467 do {
468 ++SizeTmp;
469 if (Ptr[SizeTmp-1] == '\n' || Ptr[SizeTmp-1] == '\r') {
470
471 // If this is a \r\n or \n\r, skip the newlines.
472 if ((Ptr[SizeTmp] == '\r' || Ptr[SizeTmp] == '\n') &&
473 Ptr[SizeTmp-1] != Ptr[SizeTmp])
474 ++SizeTmp;
475
476 // Found backslash<whitespace><newline>. Parse the char after it.
477 Size += SizeTmp;
478 Ptr += SizeTmp;
479
480 // Use slow version to accumulate a correct size field.
481 return getCharAndSizeSlowNoWarn(Ptr, Size, Features);
482 }
483 } while (isWhitespace(Ptr[SizeTmp]));
484 }
485
486 // Otherwise, this is not an escaped newline, just return the slash.
487 return '\\';
488 }
489
490 // If this is a trigraph, process it.
491 if (Features.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
492 // If this is actually a legal trigraph (not something like "??x"), return
493 // it.
494 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
495 Ptr += 3;
496 Size += 3;
497 if (C == '\\') goto Slash;
498 return C;
499 }
500 }
501
502 // If this is neither, return a single character.
503 ++Size;
504 return *Ptr;
505}
506
507//===----------------------------------------------------------------------===//
508// Helper methods for lexing.
509//===----------------------------------------------------------------------===//
510
511void Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
512 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
513 unsigned Size;
514 unsigned char C = *CurPtr++;
515 while (isIdentifierBody(C)) {
516 C = *CurPtr++;
517 }
518 --CurPtr; // Back up over the skipped character.
519
520 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
521 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
522 // FIXME: UCNs.
523 if (C != '\\' && C != '?' && (C != '$' || !Features.DollarIdents)) {
524FinishIdentifier:
525 const char *IdStart = BufferPtr;
Chris Lattner0344cc72008-10-12 04:51:35 +0000526 FormTokenWithChars(Result, CurPtr, tok::identifier);
Chris Lattner4b009652007-07-25 00:24:17 +0000527
528 // If we are in raw mode, return this identifier raw. There is no need to
529 // look up identifier information or attempt to macro expand it.
530 if (LexingRawMode) return;
531
532 // Fill in Result.IdentifierInfo, looking up the identifier in the
533 // identifier table.
Chris Lattner342dccb2007-10-17 20:41:00 +0000534 PP->LookUpIdentifierInfo(Result, IdStart);
Chris Lattner4b009652007-07-25 00:24:17 +0000535
536 // Finally, now that we know we have an identifier, pass this off to the
537 // preprocessor, which may macro expand it or something.
Chris Lattner342dccb2007-10-17 20:41:00 +0000538 return PP->HandleIdentifier(Result);
Chris Lattner4b009652007-07-25 00:24:17 +0000539 }
540
541 // Otherwise, $,\,? in identifier found. Enter slower path.
542
543 C = getCharAndSize(CurPtr, Size);
544 while (1) {
545 if (C == '$') {
546 // If we hit a $ and they are not supported in identifiers, we are done.
547 if (!Features.DollarIdents) goto FinishIdentifier;
548
549 // Otherwise, emit a diagnostic and continue.
Chris Lattnerf9c62772008-11-22 02:02:22 +0000550 if (!isLexingRawMode())
551 Diag(CurPtr, diag::ext_dollar_in_identifier);
Chris Lattner4b009652007-07-25 00:24:17 +0000552 CurPtr = ConsumeChar(CurPtr, Size, Result);
553 C = getCharAndSize(CurPtr, Size);
554 continue;
555 } else if (!isIdentifierBody(C)) { // FIXME: UCNs.
556 // Found end of identifier.
557 goto FinishIdentifier;
558 }
559
560 // Otherwise, this character is good, consume it.
561 CurPtr = ConsumeChar(CurPtr, Size, Result);
562
563 C = getCharAndSize(CurPtr, Size);
564 while (isIdentifierBody(C)) { // FIXME: UCNs.
565 CurPtr = ConsumeChar(CurPtr, Size, Result);
566 C = getCharAndSize(CurPtr, Size);
567 }
568 }
569}
570
571
Nate Begeman937cac72008-04-14 02:26:39 +0000572/// LexNumericConstant - Lex the remainder of a integer or floating point
Chris Lattner4b009652007-07-25 00:24:17 +0000573/// constant. From[-1] is the first character lexed. Return the end of the
574/// constant.
575void Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
576 unsigned Size;
577 char C = getCharAndSize(CurPtr, Size);
578 char PrevCh = 0;
579 while (isNumberBody(C)) { // FIXME: UCNs?
580 CurPtr = ConsumeChar(CurPtr, Size, Result);
581 PrevCh = C;
582 C = getCharAndSize(CurPtr, Size);
583 }
584
585 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
586 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e'))
587 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
588
589 // If we have a hex FP constant, continue.
Chris Lattner9ba63822008-11-22 07:39:03 +0000590 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p') &&
591 (Features.HexFloats || !Features.NoExtensions))
Chris Lattner4b009652007-07-25 00:24:17 +0000592 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
593
Chris Lattner4b009652007-07-25 00:24:17 +0000594 // Update the location of token as well as BufferPtr.
Chris Lattner0344cc72008-10-12 04:51:35 +0000595 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
Chris Lattner4b009652007-07-25 00:24:17 +0000596}
597
598/// LexStringLiteral - Lex the remainder of a string literal, after having lexed
599/// either " or L".
Chris Lattner867a87b2008-10-12 04:05:48 +0000600void Lexer::LexStringLiteral(Token &Result, const char *CurPtr, bool Wide) {
Chris Lattner4b009652007-07-25 00:24:17 +0000601 const char *NulCharacter = 0; // Does this string contain the \0 character?
602
603 char C = getAndAdvanceChar(CurPtr, Result);
604 while (C != '"') {
605 // Skip escaped characters.
606 if (C == '\\') {
607 // Skip the escaped character.
608 C = getAndAdvanceChar(CurPtr, Result);
609 } else if (C == '\n' || C == '\r' || // Newline.
610 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Chris Lattnerf9c62772008-11-22 02:02:22 +0000611 if (!isLexingRawMode())
612 Diag(BufferPtr, diag::err_unterminated_string);
Chris Lattner0344cc72008-10-12 04:51:35 +0000613 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Chris Lattner4b009652007-07-25 00:24:17 +0000614 return;
615 } else if (C == 0) {
616 NulCharacter = CurPtr-1;
617 }
618 C = getAndAdvanceChar(CurPtr, Result);
619 }
620
621 // If a nul character existed in the string, warn about it.
Chris Lattnerf9c62772008-11-22 02:02:22 +0000622 if (NulCharacter && !isLexingRawMode())
623 Diag(NulCharacter, diag::null_in_string);
Chris Lattner4b009652007-07-25 00:24:17 +0000624
Chris Lattner4b009652007-07-25 00:24:17 +0000625 // Update the location of the token as well as the BufferPtr instance var.
Chris Lattner0344cc72008-10-12 04:51:35 +0000626 FormTokenWithChars(Result, CurPtr,
627 Wide ? tok::wide_string_literal : tok::string_literal);
Chris Lattner4b009652007-07-25 00:24:17 +0000628}
629
630/// LexAngledStringLiteral - Lex the remainder of an angled string literal,
631/// after having lexed the '<' character. This is used for #include filenames.
632void Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
633 const char *NulCharacter = 0; // Does this string contain the \0 character?
634
635 char C = getAndAdvanceChar(CurPtr, Result);
636 while (C != '>') {
637 // Skip escaped characters.
638 if (C == '\\') {
639 // Skip the escaped character.
640 C = getAndAdvanceChar(CurPtr, Result);
641 } else if (C == '\n' || C == '\r' || // Newline.
642 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Chris Lattnerf9c62772008-11-22 02:02:22 +0000643 if (!isLexingRawMode())
644 Diag(BufferPtr, diag::err_unterminated_string);
Chris Lattner0344cc72008-10-12 04:51:35 +0000645 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Chris Lattner4b009652007-07-25 00:24:17 +0000646 return;
647 } else if (C == 0) {
648 NulCharacter = CurPtr-1;
649 }
650 C = getAndAdvanceChar(CurPtr, Result);
651 }
652
653 // If a nul character existed in the string, warn about it.
Chris Lattnerf9c62772008-11-22 02:02:22 +0000654 if (NulCharacter && !isLexingRawMode())
655 Diag(NulCharacter, diag::null_in_string);
Chris Lattner4b009652007-07-25 00:24:17 +0000656
Chris Lattner4b009652007-07-25 00:24:17 +0000657 // Update the location of token as well as BufferPtr.
Chris Lattner0344cc72008-10-12 04:51:35 +0000658 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
Chris Lattner4b009652007-07-25 00:24:17 +0000659}
660
661
662/// LexCharConstant - Lex the remainder of a character constant, after having
663/// lexed either ' or L'.
664void Lexer::LexCharConstant(Token &Result, const char *CurPtr) {
665 const char *NulCharacter = 0; // Does this character contain the \0 character?
666
667 // Handle the common case of 'x' and '\y' efficiently.
668 char C = getAndAdvanceChar(CurPtr, Result);
669 if (C == '\'') {
Chris Lattnerf9c62772008-11-22 02:02:22 +0000670 if (!isLexingRawMode())
671 Diag(BufferPtr, diag::err_empty_character);
Chris Lattner0344cc72008-10-12 04:51:35 +0000672 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner4b009652007-07-25 00:24:17 +0000673 return;
674 } else if (C == '\\') {
675 // Skip the escaped character.
676 // FIXME: UCN's.
677 C = getAndAdvanceChar(CurPtr, Result);
678 }
679
680 if (C && C != '\n' && C != '\r' && CurPtr[0] == '\'') {
681 ++CurPtr;
682 } else {
683 // Fall back on generic code for embedded nulls, newlines, wide chars.
684 do {
685 // Skip escaped characters.
686 if (C == '\\') {
687 // Skip the escaped character.
688 C = getAndAdvanceChar(CurPtr, Result);
689 } else if (C == '\n' || C == '\r' || // Newline.
690 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Chris Lattnerf9c62772008-11-22 02:02:22 +0000691 if (!isLexingRawMode())
692 Diag(BufferPtr, diag::err_unterminated_char);
Chris Lattner0344cc72008-10-12 04:51:35 +0000693 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Chris Lattner4b009652007-07-25 00:24:17 +0000694 return;
695 } else if (C == 0) {
696 NulCharacter = CurPtr-1;
697 }
698 C = getAndAdvanceChar(CurPtr, Result);
699 } while (C != '\'');
700 }
701
Chris Lattnerf9c62772008-11-22 02:02:22 +0000702 if (NulCharacter && !isLexingRawMode())
703 Diag(NulCharacter, diag::null_in_char);
Chris Lattner4b009652007-07-25 00:24:17 +0000704
Chris Lattner4b009652007-07-25 00:24:17 +0000705 // Update the location of token as well as BufferPtr.
Chris Lattner0344cc72008-10-12 04:51:35 +0000706 FormTokenWithChars(Result, CurPtr, tok::char_constant);
Chris Lattner4b009652007-07-25 00:24:17 +0000707}
708
709/// SkipWhitespace - Efficiently skip over a series of whitespace characters.
710/// Update BufferPtr to point to the next non-whitespace character and return.
Chris Lattner867a87b2008-10-12 04:05:48 +0000711///
712/// This method forms a token and returns true if KeepWhitespaceMode is enabled.
713///
714bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr) {
Chris Lattner4b009652007-07-25 00:24:17 +0000715 // Whitespace - Skip it, then return the token after the whitespace.
716 unsigned char Char = *CurPtr; // Skip consequtive spaces efficiently.
717 while (1) {
718 // Skip horizontal whitespace very aggressively.
719 while (isHorizontalWhitespace(Char))
720 Char = *++CurPtr;
721
Daniel Dunbara2208392008-11-25 00:20:22 +0000722 // Otherwise if we have something other than whitespace, we're done.
Chris Lattner4b009652007-07-25 00:24:17 +0000723 if (Char != '\n' && Char != '\r')
724 break;
725
726 if (ParsingPreprocessorDirective) {
727 // End of preprocessor directive line, let LexTokenInternal handle this.
728 BufferPtr = CurPtr;
Chris Lattner867a87b2008-10-12 04:05:48 +0000729 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000730 }
731
732 // ok, but handle newline.
733 // The returned token is at the start of the line.
734 Result.setFlag(Token::StartOfLine);
735 // No leading whitespace seen so far.
736 Result.clearFlag(Token::LeadingSpace);
737 Char = *++CurPtr;
738 }
739
740 // If this isn't immediately after a newline, there is leading space.
741 char PrevChar = CurPtr[-1];
742 if (PrevChar != '\n' && PrevChar != '\r')
743 Result.setFlag(Token::LeadingSpace);
744
Chris Lattner867a87b2008-10-12 04:05:48 +0000745 // If the client wants us to return whitespace, return it now.
746 if (isKeepWhitespaceMode()) {
Chris Lattner0344cc72008-10-12 04:51:35 +0000747 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner867a87b2008-10-12 04:05:48 +0000748 return true;
749 }
750
Chris Lattner4b009652007-07-25 00:24:17 +0000751 BufferPtr = CurPtr;
Chris Lattner867a87b2008-10-12 04:05:48 +0000752 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000753}
754
755// SkipBCPLComment - We have just read the // characters from input. Skip until
756// we find the newline character thats terminate the comment. Then update
Chris Lattnerf03b00c2008-10-12 04:15:42 +0000757/// BufferPtr and return. If we're in KeepCommentMode, this will form the token
758/// and return true.
Chris Lattner4b009652007-07-25 00:24:17 +0000759bool Lexer::SkipBCPLComment(Token &Result, const char *CurPtr) {
760 // If BCPL comments aren't explicitly enabled for this language, emit an
761 // extension warning.
Chris Lattnerf9c62772008-11-22 02:02:22 +0000762 if (!Features.BCPLComment && !isLexingRawMode()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000763 Diag(BufferPtr, diag::ext_bcpl_comment);
764
765 // Mark them enabled so we only emit one warning for this translation
766 // unit.
767 Features.BCPLComment = true;
768 }
769
770 // Scan over the body of the comment. The common case, when scanning, is that
771 // the comment contains normal ascii characters with nothing interesting in
772 // them. As such, optimize for this case with the inner loop.
773 char C;
774 do {
775 C = *CurPtr;
776 // FIXME: Speedup BCPL comment lexing. Just scan for a \n or \r character.
777 // If we find a \n character, scan backwards, checking to see if it's an
778 // escaped newline, like we do for block comments.
779
780 // Skip over characters in the fast loop.
781 while (C != 0 && // Potentially EOF.
782 C != '\\' && // Potentially escaped newline.
783 C != '?' && // Potentially trigraph.
784 C != '\n' && C != '\r') // Newline or DOS-style newline.
785 C = *++CurPtr;
786
787 // If this is a newline, we're done.
788 if (C == '\n' || C == '\r')
789 break; // Found the newline? Break out!
790
791 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
Chris Lattnerc3697802008-12-12 07:34:39 +0000792 // properly decode the character. Read it in raw mode to avoid emitting
793 // diagnostics about things like trigraphs. If we see an escaped newline,
794 // we'll handle it below.
Chris Lattner4b009652007-07-25 00:24:17 +0000795 const char *OldPtr = CurPtr;
Chris Lattnerc3697802008-12-12 07:34:39 +0000796 bool OldRawMode = isLexingRawMode();
797 LexingRawMode = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000798 C = getAndAdvanceChar(CurPtr, Result);
Chris Lattnerc3697802008-12-12 07:34:39 +0000799 LexingRawMode = OldRawMode;
Chris Lattner4b009652007-07-25 00:24:17 +0000800
801 // If we read multiple characters, and one of those characters was a \r or
802 // \n, then we had an escaped newline within the comment. Emit diagnostic
803 // unless the next line is also a // comment.
804 if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') {
805 for (; OldPtr != CurPtr; ++OldPtr)
806 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
807 // Okay, we found a // comment that ends in a newline, if the next
808 // line is also a // comment, but has spaces, don't emit a diagnostic.
809 if (isspace(C)) {
810 const char *ForwardPtr = CurPtr;
811 while (isspace(*ForwardPtr)) // Skip whitespace.
812 ++ForwardPtr;
813 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
814 break;
815 }
816
Chris Lattnerf9c62772008-11-22 02:02:22 +0000817 if (!isLexingRawMode())
818 Diag(OldPtr-1, diag::ext_multi_line_bcpl_comment);
Chris Lattner4b009652007-07-25 00:24:17 +0000819 break;
820 }
821 }
822
823 if (CurPtr == BufferEnd+1) { --CurPtr; break; }
824 } while (C != '\n' && C != '\r');
825
826 // Found but did not consume the newline.
827
828 // If we are returning comments as tokens, return this comment as a token.
Chris Lattner170adb12008-10-12 03:22:02 +0000829 if (inKeepCommentMode())
Chris Lattner4b009652007-07-25 00:24:17 +0000830 return SaveBCPLComment(Result, CurPtr);
831
832 // If we are inside a preprocessor directive and we see the end of line,
833 // return immediately, so that the lexer can return this as an EOM token.
834 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
835 BufferPtr = CurPtr;
Chris Lattnerf03b00c2008-10-12 04:15:42 +0000836 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000837 }
838
839 // Otherwise, eat the \n character. We don't care if this is a \n\r or
Chris Lattner43d38202008-10-12 00:23:07 +0000840 // \r\n sequence. This is an efficiency hack (because we know the \n can't
Chris Lattner867a87b2008-10-12 04:05:48 +0000841 // contribute to another token), it isn't needed for correctness. Note that
842 // this is ok even in KeepWhitespaceMode, because we would have returned the
843 /// comment above in that mode.
Chris Lattner4b009652007-07-25 00:24:17 +0000844 ++CurPtr;
845
846 // The next returned token is at the start of the line.
847 Result.setFlag(Token::StartOfLine);
848 // No leading whitespace seen so far.
849 Result.clearFlag(Token::LeadingSpace);
850 BufferPtr = CurPtr;
Chris Lattnerf03b00c2008-10-12 04:15:42 +0000851 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000852}
853
854/// SaveBCPLComment - If in save-comment mode, package up this BCPL comment in
855/// an appropriate way and return it.
856bool Lexer::SaveBCPLComment(Token &Result, const char *CurPtr) {
Chris Lattner0344cc72008-10-12 04:51:35 +0000857 // If we're not in a preprocessor directive, just return the // comment
858 // directly.
859 FormTokenWithChars(Result, CurPtr, tok::comment);
Chris Lattner4b009652007-07-25 00:24:17 +0000860
Chris Lattner0344cc72008-10-12 04:51:35 +0000861 if (!ParsingPreprocessorDirective)
862 return true;
863
864 // If this BCPL-style comment is in a macro definition, transmogrify it into
865 // a C-style block comment.
866 std::string Spelling = PP->getSpelling(Result);
867 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not bcpl comment?");
868 Spelling[1] = '*'; // Change prefix to "/*".
869 Spelling += "*/"; // add suffix.
870
871 Result.setKind(tok::comment);
872 Result.setLocation(PP->CreateString(&Spelling[0], Spelling.size(),
873 Result.getLocation()));
874 Result.setLength(Spelling.size());
Chris Lattnerf03b00c2008-10-12 04:15:42 +0000875 return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000876}
877
878/// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
879/// character (either \n or \r) is part of an escaped newline sequence. Issue a
Chris Lattnerb3872872008-12-12 07:14:34 +0000880/// diagnostic if so. We know that the newline is inside of a block comment.
Chris Lattner4b009652007-07-25 00:24:17 +0000881static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
882 Lexer *L) {
883 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
884
885 // Back up off the newline.
886 --CurPtr;
887
888 // If this is a two-character newline sequence, skip the other character.
889 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
890 // \n\n or \r\r -> not escaped newline.
891 if (CurPtr[0] == CurPtr[1])
892 return false;
893 // \n\r or \r\n -> skip the newline.
894 --CurPtr;
895 }
896
897 // If we have horizontal whitespace, skip over it. We allow whitespace
898 // between the slash and newline.
899 bool HasSpace = false;
900 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
901 --CurPtr;
902 HasSpace = true;
903 }
904
905 // If we have a slash, we know this is an escaped newline.
906 if (*CurPtr == '\\') {
907 if (CurPtr[-1] != '*') return false;
908 } else {
909 // It isn't a slash, is it the ?? / trigraph?
910 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
911 CurPtr[-3] != '*')
912 return false;
913
914 // This is the trigraph ending the comment. Emit a stern warning!
915 CurPtr -= 2;
916
917 // If no trigraphs are enabled, warn that we ignored this trigraph and
918 // ignore this * character.
919 if (!L->getFeatures().Trigraphs) {
Chris Lattnerf9c62772008-11-22 02:02:22 +0000920 if (!L->isLexingRawMode())
921 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
Chris Lattner4b009652007-07-25 00:24:17 +0000922 return false;
923 }
Chris Lattnerf9c62772008-11-22 02:02:22 +0000924 if (!L->isLexingRawMode())
925 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
Chris Lattner4b009652007-07-25 00:24:17 +0000926 }
927
928 // Warn about having an escaped newline between the */ characters.
Chris Lattnerf9c62772008-11-22 02:02:22 +0000929 if (!L->isLexingRawMode())
930 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
Chris Lattner4b009652007-07-25 00:24:17 +0000931
932 // If there was space between the backslash and newline, warn about it.
Chris Lattnerf9c62772008-11-22 02:02:22 +0000933 if (HasSpace && !L->isLexingRawMode())
934 L->Diag(CurPtr, diag::backslash_newline_space);
Chris Lattner4b009652007-07-25 00:24:17 +0000935
936 return true;
937}
938
939#ifdef __SSE2__
940#include <emmintrin.h>
941#elif __ALTIVEC__
942#include <altivec.h>
943#undef bool
944#endif
945
946/// SkipBlockComment - We have just read the /* characters from input. Read
947/// until we find the */ characters that terminate the comment. Note that we
948/// don't bother decoding trigraphs or escaped newlines in block comments,
949/// because they cannot cause the comment to end. The only thing that can
950/// happen is the comment could end with an escaped newline between the */ end
951/// of comment.
Chris Lattnerf03b00c2008-10-12 04:15:42 +0000952///
953/// If KeepCommentMode is enabled, this forms a token from the comment and
954/// returns true.
Chris Lattner4b009652007-07-25 00:24:17 +0000955bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr) {
956 // Scan one character past where we should, looking for a '/' character. Once
957 // we find it, check to see if it was preceeded by a *. This common
958 // optimization helps people who like to put a lot of * characters in their
959 // comments.
960
961 // The first character we get with newlines and trigraphs skipped to handle
962 // the degenerate /*/ case below correctly if the * has an escaped newline
963 // after it.
964 unsigned CharSize;
965 unsigned char C = getCharAndSize(CurPtr, CharSize);
966 CurPtr += CharSize;
967 if (C == 0 && CurPtr == BufferEnd+1) {
Chris Lattnerf9c62772008-11-22 02:02:22 +0000968 if (!isLexingRawMode())
Chris Lattnere5eca952008-10-12 01:31:51 +0000969 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattnerd66f4542008-10-12 04:19:49 +0000970 --CurPtr;
971
972 // KeepWhitespaceMode should return this broken comment as a token. Since
973 // it isn't a well formed comment, just return it as an 'unknown' token.
974 if (isKeepWhitespaceMode()) {
Chris Lattner0344cc72008-10-12 04:51:35 +0000975 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd66f4542008-10-12 04:19:49 +0000976 return true;
977 }
978
979 BufferPtr = CurPtr;
Chris Lattnerf03b00c2008-10-12 04:15:42 +0000980 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000981 }
982
983 // Check to see if the first character after the '/*' is another /. If so,
984 // then this slash does not end the block comment, it is part of it.
985 if (C == '/')
986 C = *CurPtr++;
987
988 while (1) {
989 // Skip over all non-interesting characters until we find end of buffer or a
990 // (probably ending) '/' character.
991 if (CurPtr + 24 < BufferEnd) {
992 // While not aligned to a 16-byte boundary.
993 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
994 C = *CurPtr++;
995
996 if (C == '/') goto FoundSlash;
997
998#ifdef __SSE2__
999 __m128i Slashes = _mm_set_epi8('/', '/', '/', '/', '/', '/', '/', '/',
1000 '/', '/', '/', '/', '/', '/', '/', '/');
1001 while (CurPtr+16 <= BufferEnd &&
1002 _mm_movemask_epi8(_mm_cmpeq_epi8(*(__m128i*)CurPtr, Slashes)) == 0)
1003 CurPtr += 16;
1004#elif __ALTIVEC__
1005 __vector unsigned char Slashes = {
1006 '/', '/', '/', '/', '/', '/', '/', '/',
1007 '/', '/', '/', '/', '/', '/', '/', '/'
1008 };
1009 while (CurPtr+16 <= BufferEnd &&
1010 !vec_any_eq(*(vector unsigned char*)CurPtr, Slashes))
1011 CurPtr += 16;
1012#else
1013 // Scan for '/' quickly. Many block comments are very large.
1014 while (CurPtr[0] != '/' &&
1015 CurPtr[1] != '/' &&
1016 CurPtr[2] != '/' &&
1017 CurPtr[3] != '/' &&
1018 CurPtr+4 < BufferEnd) {
1019 CurPtr += 4;
1020 }
1021#endif
1022
1023 // It has to be one of the bytes scanned, increment to it and read one.
1024 C = *CurPtr++;
1025 }
1026
1027 // Loop to scan the remainder.
1028 while (C != '/' && C != '\0')
1029 C = *CurPtr++;
1030
1031 FoundSlash:
1032 if (C == '/') {
1033 if (CurPtr[-2] == '*') // We found the final */. We're done!
1034 break;
1035
1036 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
1037 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
1038 // We found the final */, though it had an escaped newline between the
1039 // * and /. We're done!
1040 break;
1041 }
1042 }
1043 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
1044 // If this is a /* inside of the comment, emit a warning. Don't do this
1045 // if this is a /*/, which will end the comment. This misses cases with
1046 // embedded escaped newlines, but oh well.
Chris Lattnerf9c62772008-11-22 02:02:22 +00001047 if (!isLexingRawMode())
1048 Diag(CurPtr-1, diag::warn_nested_block_comment);
Chris Lattner4b009652007-07-25 00:24:17 +00001049 }
1050 } else if (C == 0 && CurPtr == BufferEnd+1) {
Chris Lattnerf9c62772008-11-22 02:02:22 +00001051 if (!isLexingRawMode())
1052 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner4b009652007-07-25 00:24:17 +00001053 // Note: the user probably forgot a */. We could continue immediately
1054 // after the /*, but this would involve lexing a lot of what really is the
1055 // comment, which surely would confuse the parser.
Chris Lattnerd66f4542008-10-12 04:19:49 +00001056 --CurPtr;
1057
1058 // KeepWhitespaceMode should return this broken comment as a token. Since
1059 // it isn't a well formed comment, just return it as an 'unknown' token.
1060 if (isKeepWhitespaceMode()) {
Chris Lattner0344cc72008-10-12 04:51:35 +00001061 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd66f4542008-10-12 04:19:49 +00001062 return true;
1063 }
1064
1065 BufferPtr = CurPtr;
Chris Lattnerf03b00c2008-10-12 04:15:42 +00001066 return false;
Chris Lattner4b009652007-07-25 00:24:17 +00001067 }
1068 C = *CurPtr++;
1069 }
1070
1071 // If we are returning comments as tokens, return this comment as a token.
Chris Lattner170adb12008-10-12 03:22:02 +00001072 if (inKeepCommentMode()) {
Chris Lattner0344cc72008-10-12 04:51:35 +00001073 FormTokenWithChars(Result, CurPtr, tok::comment);
Chris Lattnerf03b00c2008-10-12 04:15:42 +00001074 return true;
Chris Lattner4b009652007-07-25 00:24:17 +00001075 }
1076
1077 // It is common for the tokens immediately after a /**/ comment to be
1078 // whitespace. Instead of going through the big switch, handle it
Chris Lattner867a87b2008-10-12 04:05:48 +00001079 // efficiently now. This is safe even in KeepWhitespaceMode because we would
1080 // have already returned above with the comment as a token.
Chris Lattner4b009652007-07-25 00:24:17 +00001081 if (isHorizontalWhitespace(*CurPtr)) {
1082 Result.setFlag(Token::LeadingSpace);
1083 SkipWhitespace(Result, CurPtr+1);
Chris Lattnerf03b00c2008-10-12 04:15:42 +00001084 return false;
Chris Lattner4b009652007-07-25 00:24:17 +00001085 }
1086
1087 // Otherwise, just return so that the next character will be lexed as a token.
1088 BufferPtr = CurPtr;
1089 Result.setFlag(Token::LeadingSpace);
Chris Lattnerf03b00c2008-10-12 04:15:42 +00001090 return false;
Chris Lattner4b009652007-07-25 00:24:17 +00001091}
1092
1093//===----------------------------------------------------------------------===//
1094// Primary Lexing Entry Points
1095//===----------------------------------------------------------------------===//
1096
Chris Lattner4b009652007-07-25 00:24:17 +00001097/// ReadToEndOfLine - Read the rest of the current preprocessor line as an
1098/// uninterpreted string. This switches the lexer out of directive mode.
1099std::string Lexer::ReadToEndOfLine() {
1100 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
1101 "Must be in a preprocessing directive!");
1102 std::string Result;
1103 Token Tmp;
1104
1105 // CurPtr - Cache BufferPtr in an automatic variable.
1106 const char *CurPtr = BufferPtr;
1107 while (1) {
1108 char Char = getAndAdvanceChar(CurPtr, Tmp);
1109 switch (Char) {
1110 default:
1111 Result += Char;
1112 break;
1113 case 0: // Null.
1114 // Found end of file?
1115 if (CurPtr-1 != BufferEnd) {
1116 // Nope, normal character, continue.
1117 Result += Char;
1118 break;
1119 }
1120 // FALL THROUGH.
1121 case '\r':
1122 case '\n':
1123 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
1124 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
1125 BufferPtr = CurPtr-1;
1126
1127 // Next, lex the character, which should handle the EOM transition.
1128 Lex(Tmp);
Chris Lattnercb8e41c2007-10-09 18:02:16 +00001129 assert(Tmp.is(tok::eom) && "Unexpected token!");
Chris Lattner4b009652007-07-25 00:24:17 +00001130
1131 // Finally, we're done, return the string we found.
1132 return Result;
1133 }
1134 }
1135}
1136
1137/// LexEndOfFile - CurPtr points to the end of this file. Handle this
1138/// condition, reporting diagnostics and handling other edge cases as required.
1139/// This returns true if Result contains a token, false if PP.Lex should be
1140/// called again.
1141bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
1142 // If we hit the end of the file while parsing a preprocessor directive,
1143 // end the preprocessor directive first. The next token returned will
1144 // then be the end of file.
1145 if (ParsingPreprocessorDirective) {
1146 // Done parsing the "line".
1147 ParsingPreprocessorDirective = false;
Chris Lattner4b009652007-07-25 00:24:17 +00001148 // Update the location of token as well as BufferPtr.
Chris Lattner0344cc72008-10-12 04:51:35 +00001149 FormTokenWithChars(Result, CurPtr, tok::eom);
Chris Lattner4b009652007-07-25 00:24:17 +00001150
1151 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattner1c1bed12008-10-12 03:27:19 +00001152 SetCommentRetentionState(PP->getCommentRetentionState());
Chris Lattner4b009652007-07-25 00:24:17 +00001153 return true; // Have a token.
1154 }
1155
1156 // If we are in raw mode, return this event as an EOF token. Let the caller
1157 // that put us in raw mode handle the event.
Chris Lattnerf9c62772008-11-22 02:02:22 +00001158 if (isLexingRawMode()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001159 Result.startToken();
1160 BufferPtr = BufferEnd;
Chris Lattner0344cc72008-10-12 04:51:35 +00001161 FormTokenWithChars(Result, BufferEnd, tok::eof);
Chris Lattner4b009652007-07-25 00:24:17 +00001162 return true;
1163 }
1164
1165 // Otherwise, issue diagnostics for unterminated #if and missing newline.
1166
1167 // If we are in a #if directive, emit an error.
1168 while (!ConditionalStack.empty()) {
Chris Lattner8ef6cdc2008-11-22 06:22:39 +00001169 PP->Diag(ConditionalStack.back().IfLoc,
1170 diag::err_pp_unterminated_conditional);
Chris Lattner4b009652007-07-25 00:24:17 +00001171 ConditionalStack.pop_back();
1172 }
1173
Chris Lattner5c337fa2008-04-12 05:54:25 +00001174 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
1175 // a pedwarn.
1176 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r'))
Chris Lattner4b009652007-07-25 00:24:17 +00001177 Diag(BufferEnd, diag::ext_no_newline_eof);
1178
1179 BufferPtr = CurPtr;
1180
1181 // Finally, let the preprocessor handle this.
Chris Lattner342dccb2007-10-17 20:41:00 +00001182 return PP->HandleEndOfFile(Result);
Chris Lattner4b009652007-07-25 00:24:17 +00001183}
1184
1185/// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
1186/// the specified lexer will return a tok::l_paren token, 0 if it is something
1187/// else and 2 if there are no more tokens in the buffer controlled by the
1188/// lexer.
1189unsigned Lexer::isNextPPTokenLParen() {
1190 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
1191
1192 // Switch to 'skipping' mode. This will ensure that we can lex a token
1193 // without emitting diagnostics, disables macro expansion, and will cause EOF
1194 // to return an EOF token instead of popping the include stack.
1195 LexingRawMode = true;
1196
1197 // Save state that can be changed while lexing so that we can restore it.
1198 const char *TmpBufferPtr = BufferPtr;
1199
1200 Token Tok;
1201 Tok.startToken();
1202 LexTokenInternal(Tok);
1203
1204 // Restore state that may have changed.
1205 BufferPtr = TmpBufferPtr;
1206
1207 // Restore the lexer back to non-skipping mode.
1208 LexingRawMode = false;
1209
Chris Lattnercb8e41c2007-10-09 18:02:16 +00001210 if (Tok.is(tok::eof))
Chris Lattner4b009652007-07-25 00:24:17 +00001211 return 2;
Chris Lattnercb8e41c2007-10-09 18:02:16 +00001212 return Tok.is(tok::l_paren);
Chris Lattner4b009652007-07-25 00:24:17 +00001213}
1214
1215
1216/// LexTokenInternal - This implements a simple C family lexer. It is an
1217/// extremely performance critical piece of code. This assumes that the buffer
1218/// has a null character at the end of the file. Return true if an error
1219/// occurred and compilation should terminate, false if normal. This returns a
1220/// preprocessing token, not a normal token, as such, it is an internal
1221/// interface. It assumes that the Flags of result have been cleared before
1222/// calling this.
1223void Lexer::LexTokenInternal(Token &Result) {
1224LexNextToken:
1225 // New token, can't need cleaning yet.
1226 Result.clearFlag(Token::NeedsCleaning);
1227 Result.setIdentifierInfo(0);
1228
1229 // CurPtr - Cache BufferPtr in an automatic variable.
1230 const char *CurPtr = BufferPtr;
1231
1232 // Small amounts of horizontal whitespace is very common between tokens.
1233 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
1234 ++CurPtr;
1235 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
1236 ++CurPtr;
Chris Lattner867a87b2008-10-12 04:05:48 +00001237
1238 // If we are keeping whitespace and other tokens, just return what we just
1239 // skipped. The next lexer invocation will return the token after the
1240 // whitespace.
1241 if (isKeepWhitespaceMode()) {
Chris Lattner0344cc72008-10-12 04:51:35 +00001242 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner867a87b2008-10-12 04:05:48 +00001243 return;
1244 }
1245
Chris Lattner4b009652007-07-25 00:24:17 +00001246 BufferPtr = CurPtr;
1247 Result.setFlag(Token::LeadingSpace);
1248 }
1249
1250 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
1251
1252 // Read a character, advancing over it.
1253 char Char = getAndAdvanceChar(CurPtr, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001254 tok::TokenKind Kind;
1255
Chris Lattner4b009652007-07-25 00:24:17 +00001256 switch (Char) {
1257 case 0: // Null.
1258 // Found end of file?
1259 if (CurPtr-1 == BufferEnd) {
1260 // Read the PP instance variable into an automatic variable, because
1261 // LexEndOfFile will often delete 'this'.
Chris Lattner342dccb2007-10-17 20:41:00 +00001262 Preprocessor *PPCache = PP;
Chris Lattner4b009652007-07-25 00:24:17 +00001263 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
1264 return; // Got a token to return.
Chris Lattner342dccb2007-10-17 20:41:00 +00001265 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
1266 return PPCache->Lex(Result);
Chris Lattner4b009652007-07-25 00:24:17 +00001267 }
1268
Chris Lattnerf9c62772008-11-22 02:02:22 +00001269 if (!isLexingRawMode())
1270 Diag(CurPtr-1, diag::null_in_file);
Chris Lattner4b009652007-07-25 00:24:17 +00001271 Result.setFlag(Token::LeadingSpace);
Chris Lattner867a87b2008-10-12 04:05:48 +00001272 if (SkipWhitespace(Result, CurPtr))
1273 return; // KeepWhitespaceMode
1274
Chris Lattner4b009652007-07-25 00:24:17 +00001275 goto LexNextToken; // GCC isn't tail call eliminating.
1276 case '\n':
1277 case '\r':
1278 // If we are inside a preprocessor directive and we see the end of line,
1279 // we know we are done with the directive, so return an EOM token.
1280 if (ParsingPreprocessorDirective) {
1281 // Done parsing the "line".
1282 ParsingPreprocessorDirective = false;
1283
1284 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattner1c1bed12008-10-12 03:27:19 +00001285 SetCommentRetentionState(PP->getCommentRetentionState());
Chris Lattner4b009652007-07-25 00:24:17 +00001286
1287 // Since we consumed a newline, we are back at the start of a line.
1288 IsAtStartOfLine = true;
1289
Chris Lattner0344cc72008-10-12 04:51:35 +00001290 Kind = tok::eom;
Chris Lattner4b009652007-07-25 00:24:17 +00001291 break;
1292 }
1293 // The returned token is at the start of the line.
1294 Result.setFlag(Token::StartOfLine);
1295 // No leading whitespace seen so far.
1296 Result.clearFlag(Token::LeadingSpace);
Chris Lattner867a87b2008-10-12 04:05:48 +00001297
1298 if (SkipWhitespace(Result, CurPtr))
1299 return; // KeepWhitespaceMode
Chris Lattner4b009652007-07-25 00:24:17 +00001300 goto LexNextToken; // GCC isn't tail call eliminating.
1301 case ' ':
1302 case '\t':
1303 case '\f':
1304 case '\v':
1305 SkipHorizontalWhitespace:
1306 Result.setFlag(Token::LeadingSpace);
Chris Lattner867a87b2008-10-12 04:05:48 +00001307 if (SkipWhitespace(Result, CurPtr))
1308 return; // KeepWhitespaceMode
Chris Lattner4b009652007-07-25 00:24:17 +00001309
1310 SkipIgnoredUnits:
1311 CurPtr = BufferPtr;
1312
1313 // If the next token is obviously a // or /* */ comment, skip it efficiently
1314 // too (without going through the big switch stmt).
Chris Lattner43e455d2009-01-16 22:39:25 +00001315 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
1316 Features.BCPLComment) {
Chris Lattner4b009652007-07-25 00:24:17 +00001317 SkipBCPLComment(Result, CurPtr+2);
1318 goto SkipIgnoredUnits;
Chris Lattner170adb12008-10-12 03:22:02 +00001319 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001320 SkipBlockComment(Result, CurPtr+2);
1321 goto SkipIgnoredUnits;
1322 } else if (isHorizontalWhitespace(*CurPtr)) {
1323 goto SkipHorizontalWhitespace;
1324 }
1325 goto LexNextToken; // GCC isn't tail call eliminating.
1326
Chris Lattner0ffadcc2008-01-03 17:58:54 +00001327 // C99 6.4.4.1: Integer Constants.
1328 // C99 6.4.4.2: Floating Constants.
1329 case '0': case '1': case '2': case '3': case '4':
1330 case '5': case '6': case '7': case '8': case '9':
1331 // Notify MIOpt that we read a non-whitespace/non-comment token.
1332 MIOpt.ReadToken();
1333 return LexNumericConstant(Result, CurPtr);
1334
1335 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
Chris Lattner4b009652007-07-25 00:24:17 +00001336 // Notify MIOpt that we read a non-whitespace/non-comment token.
1337 MIOpt.ReadToken();
1338 Char = getCharAndSize(CurPtr, SizeTmp);
1339
1340 // Wide string literal.
1341 if (Char == '"')
1342 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
1343 true);
1344
1345 // Wide character constant.
1346 if (Char == '\'')
1347 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
1348 // FALL THROUGH, treating L like the start of an identifier.
1349
1350 // C99 6.4.2: Identifiers.
1351 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
1352 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
1353 case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U':
1354 case 'V': case 'W': case 'X': case 'Y': case 'Z':
1355 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
1356 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
1357 case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u':
1358 case 'v': case 'w': case 'x': case 'y': case 'z':
1359 case '_':
1360 // Notify MIOpt that we read a non-whitespace/non-comment token.
1361 MIOpt.ReadToken();
1362 return LexIdentifier(Result, CurPtr);
Chris Lattner0ffadcc2008-01-03 17:58:54 +00001363
1364 case '$': // $ in identifiers.
1365 if (Features.DollarIdents) {
Chris Lattnerf9c62772008-11-22 02:02:22 +00001366 if (!isLexingRawMode())
1367 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
Chris Lattner0ffadcc2008-01-03 17:58:54 +00001368 // Notify MIOpt that we read a non-whitespace/non-comment token.
1369 MIOpt.ReadToken();
1370 return LexIdentifier(Result, CurPtr);
1371 }
Chris Lattner4b009652007-07-25 00:24:17 +00001372
Chris Lattner0344cc72008-10-12 04:51:35 +00001373 Kind = tok::unknown;
Chris Lattner0ffadcc2008-01-03 17:58:54 +00001374 break;
Chris Lattner4b009652007-07-25 00:24:17 +00001375
1376 // C99 6.4.4: Character Constants.
1377 case '\'':
1378 // Notify MIOpt that we read a non-whitespace/non-comment token.
1379 MIOpt.ReadToken();
1380 return LexCharConstant(Result, CurPtr);
1381
1382 // C99 6.4.5: String Literals.
1383 case '"':
1384 // Notify MIOpt that we read a non-whitespace/non-comment token.
1385 MIOpt.ReadToken();
1386 return LexStringLiteral(Result, CurPtr, false);
1387
1388 // C99 6.4.6: Punctuators.
1389 case '?':
Chris Lattner0344cc72008-10-12 04:51:35 +00001390 Kind = tok::question;
Chris Lattner4b009652007-07-25 00:24:17 +00001391 break;
1392 case '[':
Chris Lattner0344cc72008-10-12 04:51:35 +00001393 Kind = tok::l_square;
Chris Lattner4b009652007-07-25 00:24:17 +00001394 break;
1395 case ']':
Chris Lattner0344cc72008-10-12 04:51:35 +00001396 Kind = tok::r_square;
Chris Lattner4b009652007-07-25 00:24:17 +00001397 break;
1398 case '(':
Chris Lattner0344cc72008-10-12 04:51:35 +00001399 Kind = tok::l_paren;
Chris Lattner4b009652007-07-25 00:24:17 +00001400 break;
1401 case ')':
Chris Lattner0344cc72008-10-12 04:51:35 +00001402 Kind = tok::r_paren;
Chris Lattner4b009652007-07-25 00:24:17 +00001403 break;
1404 case '{':
Chris Lattner0344cc72008-10-12 04:51:35 +00001405 Kind = tok::l_brace;
Chris Lattner4b009652007-07-25 00:24:17 +00001406 break;
1407 case '}':
Chris Lattner0344cc72008-10-12 04:51:35 +00001408 Kind = tok::r_brace;
Chris Lattner4b009652007-07-25 00:24:17 +00001409 break;
1410 case '.':
1411 Char = getCharAndSize(CurPtr, SizeTmp);
1412 if (Char >= '0' && Char <= '9') {
1413 // Notify MIOpt that we read a non-whitespace/non-comment token.
1414 MIOpt.ReadToken();
1415
1416 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
1417 } else if (Features.CPlusPlus && Char == '*') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001418 Kind = tok::periodstar;
Chris Lattner4b009652007-07-25 00:24:17 +00001419 CurPtr += SizeTmp;
1420 } else if (Char == '.' &&
1421 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001422 Kind = tok::ellipsis;
Chris Lattner4b009652007-07-25 00:24:17 +00001423 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1424 SizeTmp2, Result);
1425 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001426 Kind = tok::period;
Chris Lattner4b009652007-07-25 00:24:17 +00001427 }
1428 break;
1429 case '&':
1430 Char = getCharAndSize(CurPtr, SizeTmp);
1431 if (Char == '&') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001432 Kind = tok::ampamp;
Chris Lattner4b009652007-07-25 00:24:17 +00001433 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1434 } else if (Char == '=') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001435 Kind = tok::ampequal;
Chris Lattner4b009652007-07-25 00:24:17 +00001436 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1437 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001438 Kind = tok::amp;
Chris Lattner4b009652007-07-25 00:24:17 +00001439 }
1440 break;
1441 case '*':
1442 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001443 Kind = tok::starequal;
Chris Lattner4b009652007-07-25 00:24:17 +00001444 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1445 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001446 Kind = tok::star;
Chris Lattner4b009652007-07-25 00:24:17 +00001447 }
1448 break;
1449 case '+':
1450 Char = getCharAndSize(CurPtr, SizeTmp);
1451 if (Char == '+') {
Chris Lattner4b009652007-07-25 00:24:17 +00001452 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001453 Kind = tok::plusplus;
Chris Lattner4b009652007-07-25 00:24:17 +00001454 } else if (Char == '=') {
Chris Lattner4b009652007-07-25 00:24:17 +00001455 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001456 Kind = tok::plusequal;
Chris Lattner4b009652007-07-25 00:24:17 +00001457 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001458 Kind = tok::plus;
Chris Lattner4b009652007-07-25 00:24:17 +00001459 }
1460 break;
1461 case '-':
1462 Char = getCharAndSize(CurPtr, SizeTmp);
Chris Lattner0344cc72008-10-12 04:51:35 +00001463 if (Char == '-') { // --
Chris Lattner4b009652007-07-25 00:24:17 +00001464 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001465 Kind = tok::minusminus;
Chris Lattner4b009652007-07-25 00:24:17 +00001466 } else if (Char == '>' && Features.CPlusPlus &&
Chris Lattner0344cc72008-10-12 04:51:35 +00001467 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
Chris Lattner4b009652007-07-25 00:24:17 +00001468 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1469 SizeTmp2, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001470 Kind = tok::arrowstar;
1471 } else if (Char == '>') { // ->
Chris Lattner4b009652007-07-25 00:24:17 +00001472 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001473 Kind = tok::arrow;
1474 } else if (Char == '=') { // -=
Chris Lattner4b009652007-07-25 00:24:17 +00001475 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001476 Kind = tok::minusequal;
Chris Lattner4b009652007-07-25 00:24:17 +00001477 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001478 Kind = tok::minus;
Chris Lattner4b009652007-07-25 00:24:17 +00001479 }
1480 break;
1481 case '~':
Chris Lattner0344cc72008-10-12 04:51:35 +00001482 Kind = tok::tilde;
Chris Lattner4b009652007-07-25 00:24:17 +00001483 break;
1484 case '!':
1485 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001486 Kind = tok::exclaimequal;
Chris Lattner4b009652007-07-25 00:24:17 +00001487 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1488 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001489 Kind = tok::exclaim;
Chris Lattner4b009652007-07-25 00:24:17 +00001490 }
1491 break;
1492 case '/':
1493 // 6.4.9: Comments
1494 Char = getCharAndSize(CurPtr, SizeTmp);
1495 if (Char == '/') { // BCPL comment.
Chris Lattner43e455d2009-01-16 22:39:25 +00001496 // Even if BCPL comments are disabled (e.g. in C89 mode), we generally
1497 // want to lex this as a comment. There is one problem with this though,
1498 // that in one particular corner case, this can change the behavior of the
1499 // resultant program. For example, In "foo //**/ bar", C89 would lex
1500 // this as "foo / bar" and langauges with BCPL comments would lex it as
1501 // "foo". Check to see if the character after the second slash is a '*'.
1502 // If so, we will lex that as a "/" instead of the start of a comment.
1503 if (Features.BCPLComment ||
1504 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*') {
1505 if (SkipBCPLComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
1506 return; // KeepCommentMode
Chris Lattnerf03b00c2008-10-12 04:15:42 +00001507
Chris Lattner43e455d2009-01-16 22:39:25 +00001508 // It is common for the tokens immediately after a // comment to be
1509 // whitespace (indentation for the next line). Instead of going through
1510 // the big switch, handle it efficiently now.
1511 goto SkipIgnoredUnits;
1512 }
1513 }
1514
1515 if (Char == '*') { // /**/ comment.
Chris Lattner4b009652007-07-25 00:24:17 +00001516 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattnerf03b00c2008-10-12 04:15:42 +00001517 return; // KeepCommentMode
1518 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattner43e455d2009-01-16 22:39:25 +00001519 }
1520
1521 if (Char == '=') {
Chris Lattner4b009652007-07-25 00:24:17 +00001522 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001523 Kind = tok::slashequal;
Chris Lattner4b009652007-07-25 00:24:17 +00001524 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001525 Kind = tok::slash;
Chris Lattner4b009652007-07-25 00:24:17 +00001526 }
1527 break;
1528 case '%':
1529 Char = getCharAndSize(CurPtr, SizeTmp);
1530 if (Char == '=') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001531 Kind = tok::percentequal;
Chris Lattner4b009652007-07-25 00:24:17 +00001532 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1533 } else if (Features.Digraphs && Char == '>') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001534 Kind = tok::r_brace; // '%>' -> '}'
Chris Lattner4b009652007-07-25 00:24:17 +00001535 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1536 } else if (Features.Digraphs && Char == ':') {
1537 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1538 Char = getCharAndSize(CurPtr, SizeTmp);
1539 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001540 Kind = tok::hashhash; // '%:%:' -> '##'
Chris Lattner4b009652007-07-25 00:24:17 +00001541 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1542 SizeTmp2, Result);
1543 } else if (Char == '@' && Features.Microsoft) { // %:@ -> #@ -> Charize
Chris Lattner4b009652007-07-25 00:24:17 +00001544 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerf9c62772008-11-22 02:02:22 +00001545 if (!isLexingRawMode())
1546 Diag(BufferPtr, diag::charize_microsoft_ext);
Chris Lattner0344cc72008-10-12 04:51:35 +00001547 Kind = tok::hashat;
Chris Lattner4b009652007-07-25 00:24:17 +00001548 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001549 Kind = tok::hash; // '%:' -> '#'
Chris Lattner4b009652007-07-25 00:24:17 +00001550
1551 // We parsed a # character. If this occurs at the start of the line,
1552 // it's actually the start of a preprocessing directive. Callback to
1553 // the preprocessor to handle it.
1554 // FIXME: -fpreprocessed mode??
1555 if (Result.isAtStartOfLine() && !LexingRawMode) {
1556 BufferPtr = CurPtr;
Chris Lattner342dccb2007-10-17 20:41:00 +00001557 PP->HandleDirective(Result);
Chris Lattner4b009652007-07-25 00:24:17 +00001558
1559 // As an optimization, if the preprocessor didn't switch lexers, tail
1560 // recurse.
Chris Lattner342dccb2007-10-17 20:41:00 +00001561 if (PP->isCurrentLexer(this)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001562 // Start a new token. If this is a #include or something, the PP may
1563 // want us starting at the beginning of the line again. If so, set
1564 // the StartOfLine flag.
1565 if (IsAtStartOfLine) {
1566 Result.setFlag(Token::StartOfLine);
1567 IsAtStartOfLine = false;
1568 }
1569 goto LexNextToken; // GCC isn't tail call eliminating.
1570 }
1571
Chris Lattner342dccb2007-10-17 20:41:00 +00001572 return PP->Lex(Result);
Chris Lattner4b009652007-07-25 00:24:17 +00001573 }
1574 }
1575 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001576 Kind = tok::percent;
Chris Lattner4b009652007-07-25 00:24:17 +00001577 }
1578 break;
1579 case '<':
1580 Char = getCharAndSize(CurPtr, SizeTmp);
1581 if (ParsingFilename) {
1582 return LexAngledStringLiteral(Result, CurPtr+SizeTmp);
1583 } else if (Char == '<' &&
1584 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '=') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001585 Kind = tok::lesslessequal;
Chris Lattner4b009652007-07-25 00:24:17 +00001586 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1587 SizeTmp2, Result);
1588 } else if (Char == '<') {
Chris Lattner4b009652007-07-25 00:24:17 +00001589 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001590 Kind = tok::lessless;
Chris Lattner4b009652007-07-25 00:24:17 +00001591 } else if (Char == '=') {
Chris Lattner4b009652007-07-25 00:24:17 +00001592 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001593 Kind = tok::lessequal;
1594 } else if (Features.Digraphs && Char == ':') { // '<:' -> '['
Chris Lattner4b009652007-07-25 00:24:17 +00001595 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001596 Kind = tok::l_square;
1597 } else if (Features.Digraphs && Char == '%') { // '<%' -> '{'
Chris Lattner4b009652007-07-25 00:24:17 +00001598 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001599 Kind = tok::l_brace;
Chris Lattner4b009652007-07-25 00:24:17 +00001600 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001601 Kind = tok::less;
Chris Lattner4b009652007-07-25 00:24:17 +00001602 }
1603 break;
1604 case '>':
1605 Char = getCharAndSize(CurPtr, SizeTmp);
1606 if (Char == '=') {
Chris Lattner4b009652007-07-25 00:24:17 +00001607 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001608 Kind = tok::greaterequal;
Chris Lattner4b009652007-07-25 00:24:17 +00001609 } else if (Char == '>' &&
1610 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '=') {
Chris Lattner4b009652007-07-25 00:24:17 +00001611 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1612 SizeTmp2, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001613 Kind = tok::greatergreaterequal;
Chris Lattner4b009652007-07-25 00:24:17 +00001614 } else if (Char == '>') {
Chris Lattner4b009652007-07-25 00:24:17 +00001615 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001616 Kind = tok::greatergreater;
Chris Lattner4b009652007-07-25 00:24:17 +00001617 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001618 Kind = tok::greater;
Chris Lattner4b009652007-07-25 00:24:17 +00001619 }
1620 break;
1621 case '^':
1622 Char = getCharAndSize(CurPtr, SizeTmp);
1623 if (Char == '=') {
Chris Lattner4b009652007-07-25 00:24:17 +00001624 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001625 Kind = tok::caretequal;
Chris Lattner4b009652007-07-25 00:24:17 +00001626 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001627 Kind = tok::caret;
Chris Lattner4b009652007-07-25 00:24:17 +00001628 }
1629 break;
1630 case '|':
1631 Char = getCharAndSize(CurPtr, SizeTmp);
1632 if (Char == '=') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001633 Kind = tok::pipeequal;
Chris Lattner4b009652007-07-25 00:24:17 +00001634 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1635 } else if (Char == '|') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001636 Kind = tok::pipepipe;
Chris Lattner4b009652007-07-25 00:24:17 +00001637 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1638 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001639 Kind = tok::pipe;
Chris Lattner4b009652007-07-25 00:24:17 +00001640 }
1641 break;
1642 case ':':
1643 Char = getCharAndSize(CurPtr, SizeTmp);
1644 if (Features.Digraphs && Char == '>') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001645 Kind = tok::r_square; // ':>' -> ']'
Chris Lattner4b009652007-07-25 00:24:17 +00001646 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1647 } else if (Features.CPlusPlus && Char == ':') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001648 Kind = tok::coloncolon;
Chris Lattner4b009652007-07-25 00:24:17 +00001649 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1650 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001651 Kind = tok::colon;
Chris Lattner4b009652007-07-25 00:24:17 +00001652 }
1653 break;
1654 case ';':
Chris Lattner0344cc72008-10-12 04:51:35 +00001655 Kind = tok::semi;
Chris Lattner4b009652007-07-25 00:24:17 +00001656 break;
1657 case '=':
1658 Char = getCharAndSize(CurPtr, SizeTmp);
1659 if (Char == '=') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001660 Kind = tok::equalequal;
Chris Lattner4b009652007-07-25 00:24:17 +00001661 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1662 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001663 Kind = tok::equal;
Chris Lattner4b009652007-07-25 00:24:17 +00001664 }
1665 break;
1666 case ',':
Chris Lattner0344cc72008-10-12 04:51:35 +00001667 Kind = tok::comma;
Chris Lattner4b009652007-07-25 00:24:17 +00001668 break;
1669 case '#':
1670 Char = getCharAndSize(CurPtr, SizeTmp);
1671 if (Char == '#') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001672 Kind = tok::hashhash;
Chris Lattner4b009652007-07-25 00:24:17 +00001673 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1674 } else if (Char == '@' && Features.Microsoft) { // #@ -> Charize
Chris Lattner0344cc72008-10-12 04:51:35 +00001675 Kind = tok::hashat;
Chris Lattnerf9c62772008-11-22 02:02:22 +00001676 if (!isLexingRawMode())
1677 Diag(BufferPtr, diag::charize_microsoft_ext);
Chris Lattner4b009652007-07-25 00:24:17 +00001678 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1679 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001680 Kind = tok::hash;
Chris Lattner4b009652007-07-25 00:24:17 +00001681 // We parsed a # character. If this occurs at the start of the line,
1682 // it's actually the start of a preprocessing directive. Callback to
1683 // the preprocessor to handle it.
1684 // FIXME: -fpreprocessed mode??
1685 if (Result.isAtStartOfLine() && !LexingRawMode) {
1686 BufferPtr = CurPtr;
Chris Lattner342dccb2007-10-17 20:41:00 +00001687 PP->HandleDirective(Result);
Chris Lattner4b009652007-07-25 00:24:17 +00001688
1689 // As an optimization, if the preprocessor didn't switch lexers, tail
1690 // recurse.
Chris Lattner342dccb2007-10-17 20:41:00 +00001691 if (PP->isCurrentLexer(this)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001692 // Start a new token. If this is a #include or something, the PP may
1693 // want us starting at the beginning of the line again. If so, set
1694 // the StartOfLine flag.
1695 if (IsAtStartOfLine) {
1696 Result.setFlag(Token::StartOfLine);
1697 IsAtStartOfLine = false;
1698 }
1699 goto LexNextToken; // GCC isn't tail call eliminating.
1700 }
Chris Lattner342dccb2007-10-17 20:41:00 +00001701 return PP->Lex(Result);
Chris Lattner4b009652007-07-25 00:24:17 +00001702 }
1703 }
1704 break;
1705
Chris Lattner0ffadcc2008-01-03 17:58:54 +00001706 case '@':
1707 // Objective C support.
1708 if (CurPtr[-1] == '@' && Features.ObjC1)
Chris Lattner0344cc72008-10-12 04:51:35 +00001709 Kind = tok::at;
Chris Lattner0ffadcc2008-01-03 17:58:54 +00001710 else
Chris Lattner0344cc72008-10-12 04:51:35 +00001711 Kind = tok::unknown;
Chris Lattner0ffadcc2008-01-03 17:58:54 +00001712 break;
1713
Chris Lattner4b009652007-07-25 00:24:17 +00001714 case '\\':
1715 // FIXME: UCN's.
1716 // FALL THROUGH.
1717 default:
Chris Lattner0344cc72008-10-12 04:51:35 +00001718 Kind = tok::unknown;
Chris Lattner4b009652007-07-25 00:24:17 +00001719 break;
1720 }
1721
1722 // Notify MIOpt that we read a non-whitespace/non-comment token.
1723 MIOpt.ReadToken();
1724
1725 // Update the location of token as well as BufferPtr.
Chris Lattner0344cc72008-10-12 04:51:35 +00001726 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner4b009652007-07-25 00:24:17 +00001727}