blob: e89815029dc39326eed1bd28ed89210c7e31ba25 [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 Lattneraa9bdf12007-10-07 08:47:24 +000093
Chris Lattner342dccb2007-10-17 20:41:00 +000094/// Lexer constructor - Create a new lexer object for the specified buffer
95/// with the specified preprocessor managing the lexing process. This lexer
96/// assumes that the associated file buffer and Preprocessor objects will
97/// outlive it, so it doesn't take ownership of either of them.
Chris Lattnerf4f776a2009-01-17 06:22:33 +000098Lexer::Lexer(SourceLocation fileloc, Preprocessor &PP,
Chris Lattner9bb53672009-01-17 06:55:17 +000099 const char *BufPtr, const char *BufEnd)
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000100// FIXME: This is really horrible and only needed for _Pragma lexers, split this
101// out of the main lexer path!
102 : PreprocessorLexer(&PP,
103 PP.getSourceManager().getCanonicalFileID(
104 PP.getSourceManager().getSpellingLoc(fileloc))),
105 FileLoc(fileloc),
106 Features(PP.getLangOptions()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000107
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000108 SourceManager &SourceMgr = PP.getSourceManager();
109 const llvm::MemoryBuffer *InputFile = SourceMgr.getBuffer(getFileID());
Chris Lattner4b009652007-07-25 00:24:17 +0000110
Chris Lattner4b009652007-07-25 00:24:17 +0000111 // BufferPtr and BufferEnd can start out somewhere inside the current buffer.
112 // If unspecified, they starts at the start/end of the buffer.
Chris Lattner9bb53672009-01-17 06:55:17 +0000113 const char *BufStart = InputFile->getBufferStart();
114 if (BufPtr == 0) BufPtr = BufStart;
115 if (BufEnd == 0) BufEnd = InputFile->getBufferEnd();
116
117 InitLexer(BufStart, BufPtr, BufEnd);
Chris Lattner4b009652007-07-25 00:24:17 +0000118
Chris Lattner867a87b2008-10-12 04:05:48 +0000119 // Default to keeping comments if the preprocessor wants them.
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000120 SetCommentRetentionState(PP.getCommentRetentionState());
Chris Lattner4b009652007-07-25 00:24:17 +0000121}
122
Chris Lattner342dccb2007-10-17 20:41:00 +0000123/// Lexer constructor - Create a new raw lexer object. This object is only
Chris Lattner0b5892e2008-10-12 01:15:46 +0000124/// suitable for calls to 'LexRawToken'. This lexer assumes that the text
125/// range will outlive it, so it doesn't take ownership of it.
Chris Lattner342dccb2007-10-17 20:41:00 +0000126Lexer::Lexer(SourceLocation fileloc, const LangOptions &features,
Chris Lattner9bb53672009-01-17 06:55:17 +0000127 const char *BufPtr, const char *BufEnd,
Chris Lattner0b5892e2008-10-12 01:15:46 +0000128 const llvm::MemoryBuffer *FromFile)
Chris Lattneref63fd52009-01-17 03:48:08 +0000129 : FileLoc(fileloc), Features(features) {
Ted Kremenek56758d22008-11-19 21:57:25 +0000130
Chris Lattner9bb53672009-01-17 06:55:17 +0000131
Chris Lattner88ad2ac2008-10-12 01:23:27 +0000132 // If a MemoryBuffer was specified, use its start as BufferStart. This affects
133 // the source location objects produced by this lexer.
Chris Lattner9bb53672009-01-17 06:55:17 +0000134 const char *BufStart = BufPtr;
135 if (FromFile) BufStart = FromFile->getBufferStart();
136
137 InitLexer(BufStart, BufPtr, BufEnd);
Chris Lattner342dccb2007-10-17 20:41:00 +0000138
139 // We *are* in raw mode.
140 LexingRawMode = true;
Chris Lattner342dccb2007-10-17 20:41:00 +0000141}
142
143
Chris Lattner4b009652007-07-25 00:24:17 +0000144/// Stringify - Convert the specified string into a C string, with surrounding
145/// ""'s, and with escaped \ and " characters.
146std::string Lexer::Stringify(const std::string &Str, bool Charify) {
147 std::string Result = Str;
148 char Quote = Charify ? '\'' : '"';
149 for (unsigned i = 0, e = Result.size(); i != e; ++i) {
150 if (Result[i] == '\\' || Result[i] == Quote) {
151 Result.insert(Result.begin()+i, '\\');
152 ++i; ++e;
153 }
154 }
155 return Result;
156}
157
158/// Stringify - Convert the specified string into a C string by escaping '\'
159/// and " characters. This does not add surrounding ""'s to the string.
160void Lexer::Stringify(llvm::SmallVectorImpl<char> &Str) {
161 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
162 if (Str[i] == '\\' || Str[i] == '"') {
163 Str.insert(Str.begin()+i, '\\');
164 ++i; ++e;
165 }
166 }
167}
168
169
Chris Lattner761d76b2007-10-17 21:18:47 +0000170/// MeasureTokenLength - Relex the token at the specified location and return
171/// its length in bytes in the input file. If the token needs cleaning (e.g.
172/// includes a trigraph or an escaped newline) then this count includes bytes
173/// that are part of that.
174unsigned Lexer::MeasureTokenLength(SourceLocation Loc,
175 const SourceManager &SM) {
176 // If this comes from a macro expansion, we really do want the macro name, not
177 // the token this macro expanded to.
Chris Lattner18c8dc02009-01-16 07:36:28 +0000178 Loc = SM.getInstantiationLoc(Loc);
Chris Lattner761d76b2007-10-17 21:18:47 +0000179
180 const char *StrData = SM.getCharacterData(Loc);
181
182 // TODO: this could be special cased for common tokens like identifiers, ')',
183 // etc to make this faster, if it mattered. Just look at StrData[0] to handle
184 // all obviously single-char tokens. This could use
185 // Lexer::isObviouslySimpleCharacter for example to handle identifiers or
186 // something.
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000187 const char *BufEnd = SM.getBufferData(Loc).second;
Chris Lattner761d76b2007-10-17 21:18:47 +0000188
189 // Create a langops struct and enable trigraphs. This is sufficient for
190 // measuring tokens.
191 LangOptions LangOpts;
192 LangOpts.Trigraphs = true;
193
194 // Create a lexer starting at the beginning of this token.
195 Lexer TheLexer(Loc, LangOpts, StrData, BufEnd);
196 Token TheTok;
Chris Lattner0b5892e2008-10-12 01:15:46 +0000197 TheLexer.LexFromRawLexer(TheTok);
Chris Lattner761d76b2007-10-17 21:18:47 +0000198 return TheTok.getLength();
199}
200
Chris Lattner4b009652007-07-25 00:24:17 +0000201//===----------------------------------------------------------------------===//
202// Character information.
203//===----------------------------------------------------------------------===//
204
205static unsigned char CharInfo[256];
206
207enum {
208 CHAR_HORZ_WS = 0x01, // ' ', '\t', '\f', '\v'. Note, no '\0'
209 CHAR_VERT_WS = 0x02, // '\r', '\n'
210 CHAR_LETTER = 0x04, // a-z,A-Z
211 CHAR_NUMBER = 0x08, // 0-9
212 CHAR_UNDER = 0x10, // _
213 CHAR_PERIOD = 0x20 // .
214};
215
216static void InitCharacterInfo() {
217 static bool isInited = false;
218 if (isInited) return;
219 isInited = true;
220
221 // Intiialize the CharInfo table.
222 // TODO: statically initialize this.
223 CharInfo[(int)' '] = CharInfo[(int)'\t'] =
224 CharInfo[(int)'\f'] = CharInfo[(int)'\v'] = CHAR_HORZ_WS;
225 CharInfo[(int)'\n'] = CharInfo[(int)'\r'] = CHAR_VERT_WS;
226
227 CharInfo[(int)'_'] = CHAR_UNDER;
228 CharInfo[(int)'.'] = CHAR_PERIOD;
229 for (unsigned i = 'a'; i <= 'z'; ++i)
230 CharInfo[i] = CharInfo[i+'A'-'a'] = CHAR_LETTER;
231 for (unsigned i = '0'; i <= '9'; ++i)
232 CharInfo[i] = CHAR_NUMBER;
233}
234
235/// isIdentifierBody - Return true if this is the body character of an
236/// identifier, which is [a-zA-Z0-9_].
237static inline bool isIdentifierBody(unsigned char c) {
Hartmut Kaiserc62f6b92007-10-18 12:47:01 +0000238 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER)) ? true : false;
Chris Lattner4b009652007-07-25 00:24:17 +0000239}
240
241/// isHorizontalWhitespace - Return true if this character is horizontal
242/// whitespace: ' ', '\t', '\f', '\v'. Note that this returns false for '\0'.
243static inline bool isHorizontalWhitespace(unsigned char c) {
Hartmut Kaiserc62f6b92007-10-18 12:47:01 +0000244 return (CharInfo[c] & CHAR_HORZ_WS) ? true : false;
Chris Lattner4b009652007-07-25 00:24:17 +0000245}
246
247/// isWhitespace - Return true if this character is horizontal or vertical
248/// whitespace: ' ', '\t', '\f', '\v', '\n', '\r'. Note that this returns false
249/// for '\0'.
250static inline bool isWhitespace(unsigned char c) {
Hartmut Kaiserc62f6b92007-10-18 12:47:01 +0000251 return (CharInfo[c] & (CHAR_HORZ_WS|CHAR_VERT_WS)) ? true : false;
Chris Lattner4b009652007-07-25 00:24:17 +0000252}
253
254/// isNumberBody - Return true if this is the body character of an
255/// preprocessing number, which is [a-zA-Z0-9_.].
256static inline bool isNumberBody(unsigned char c) {
Hartmut Kaiserc62f6b92007-10-18 12:47:01 +0000257 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER|CHAR_PERIOD)) ?
258 true : false;
Chris Lattner4b009652007-07-25 00:24:17 +0000259}
260
261
262//===----------------------------------------------------------------------===//
263// Diagnostics forwarding code.
264//===----------------------------------------------------------------------===//
265
266/// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
267/// lexer buffer was all instantiated at a single point, perform the mapping.
268/// This is currently only used for _Pragma implementation, so it is the slow
269/// path of the hot getSourceLocation method. Do not allow it to be inlined.
270static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
271 SourceLocation FileLoc,
272 unsigned CharNo) DISABLE_INLINE;
273static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
274 SourceLocation FileLoc,
275 unsigned CharNo) {
276 // Otherwise, we're lexing "mapped tokens". This is used for things like
277 // _Pragma handling. Combine the instantiation location of FileLoc with the
Chris Lattnercdf600e2009-01-16 07:00:02 +0000278 // spelling location.
Chris Lattner4b009652007-07-25 00:24:17 +0000279 SourceManager &SourceMgr = PP.getSourceManager();
280
Chris Lattner18c8dc02009-01-16 07:36:28 +0000281 // Create a new SLoc which is expanded from Instantiation(FileLoc) but whose
Chris Lattnercdf600e2009-01-16 07:00:02 +0000282 // characters come from spelling(FileLoc)+Offset.
Chris Lattner18c8dc02009-01-16 07:36:28 +0000283 SourceLocation InstLoc = SourceMgr.getInstantiationLoc(FileLoc);
Chris Lattnercdf600e2009-01-16 07:00:02 +0000284 SourceLocation SpellingLoc = SourceMgr.getSpellingLoc(FileLoc);
285 SpellingLoc = SourceLocation::getFileLoc(SpellingLoc.getFileID(), CharNo);
Chris Lattner18c8dc02009-01-16 07:36:28 +0000286 return SourceMgr.getInstantiationLoc(SpellingLoc, InstLoc);
Chris Lattner4b009652007-07-25 00:24:17 +0000287}
288
289/// getSourceLocation - Return a source location identifier for the specified
290/// offset in the current file.
291SourceLocation Lexer::getSourceLocation(const char *Loc) const {
292 assert(Loc >= BufferStart && Loc <= BufferEnd &&
293 "Location out of range for this buffer!");
294
295 // In the normal case, we're just lexing from a simple file buffer, return
296 // the file id from FileLoc with the offset specified.
297 unsigned CharNo = Loc-BufferStart;
298 if (FileLoc.isFileID())
299 return SourceLocation::getFileLoc(FileLoc.getFileID(), CharNo);
300
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000301 // Otherwise, this is the _Pragma lexer case, which pretends that all of the
302 // tokens are lexed from where the _Pragma was defined.
Chris Lattner342dccb2007-10-17 20:41:00 +0000303 assert(PP && "This doesn't work on raw lexers");
304 return GetMappedTokenLoc(*PP, FileLoc, CharNo);
Chris Lattner4b009652007-07-25 00:24:17 +0000305}
306
307/// Diag - Forwarding function for diagnostics. This translate a source
308/// position in the current buffer into a SourceLocation object for rendering.
Chris Lattner9943e982008-11-22 00:59:29 +0000309DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
Chris Lattner0370d6b2008-11-18 07:59:24 +0000310 return PP->Diag(getSourceLocation(Loc), DiagID);
Chris Lattner4b009652007-07-25 00:24:17 +0000311}
Chris Lattner4b009652007-07-25 00:24:17 +0000312
313//===----------------------------------------------------------------------===//
314// Trigraph and Escaped Newline Handling Code.
315//===----------------------------------------------------------------------===//
316
317/// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
318/// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
319static char GetTrigraphCharForLetter(char Letter) {
320 switch (Letter) {
321 default: return 0;
322 case '=': return '#';
323 case ')': return ']';
324 case '(': return '[';
325 case '!': return '|';
326 case '\'': return '^';
327 case '>': return '}';
328 case '/': return '\\';
329 case '<': return '{';
330 case '-': return '~';
331 }
332}
333
334/// DecodeTrigraphChar - If the specified character is a legal trigraph when
335/// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
336/// return the result character. Finally, emit a warning about trigraph use
337/// whether trigraphs are enabled or not.
338static char DecodeTrigraphChar(const char *CP, Lexer *L) {
339 char Res = GetTrigraphCharForLetter(*CP);
Chris Lattner0370d6b2008-11-18 07:59:24 +0000340 if (!Res || !L) return Res;
341
342 if (!L->getFeatures().Trigraphs) {
Chris Lattnerf9c62772008-11-22 02:02:22 +0000343 if (!L->isLexingRawMode())
344 L->Diag(CP-2, diag::trigraph_ignored);
Chris Lattner0370d6b2008-11-18 07:59:24 +0000345 return 0;
Chris Lattner4b009652007-07-25 00:24:17 +0000346 }
Chris Lattner0370d6b2008-11-18 07:59:24 +0000347
Chris Lattnerf9c62772008-11-22 02:02:22 +0000348 if (!L->isLexingRawMode())
349 L->Diag(CP-2, diag::trigraph_converted) << std::string()+Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000350 return Res;
351}
352
353/// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
354/// get its size, and return it. This is tricky in several cases:
355/// 1. If currently at the start of a trigraph, we warn about the trigraph,
356/// then either return the trigraph (skipping 3 chars) or the '?',
357/// depending on whether trigraphs are enabled or not.
358/// 2. If this is an escaped newline (potentially with whitespace between
359/// the backslash and newline), implicitly skip the newline and return
360/// the char after it.
361/// 3. If this is a UCN, return it. FIXME: C++ UCN's?
362///
363/// This handles the slow/uncommon case of the getCharAndSize method. Here we
364/// know that we can accumulate into Size, and that we have already incremented
365/// Ptr by Size bytes.
366///
367/// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
368/// be updated to match.
369///
370char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
371 Token *Tok) {
372 // If we have a slash, look for an escaped newline.
373 if (Ptr[0] == '\\') {
374 ++Size;
375 ++Ptr;
376Slash:
377 // Common case, backslash-char where the char is not whitespace.
378 if (!isWhitespace(Ptr[0])) return '\\';
379
380 // See if we have optional whitespace characters followed by a newline.
381 {
382 unsigned SizeTmp = 0;
383 do {
384 ++SizeTmp;
385 if (Ptr[SizeTmp-1] == '\n' || Ptr[SizeTmp-1] == '\r') {
386 // Remember that this token needs to be cleaned.
387 if (Tok) Tok->setFlag(Token::NeedsCleaning);
388
389 // Warn if there was whitespace between the backslash and newline.
Chris Lattnerf9c62772008-11-22 02:02:22 +0000390 if (SizeTmp != 1 && Tok && !isLexingRawMode())
Chris Lattner4b009652007-07-25 00:24:17 +0000391 Diag(Ptr, diag::backslash_newline_space);
392
393 // If this is a \r\n or \n\r, skip the newlines.
394 if ((Ptr[SizeTmp] == '\r' || Ptr[SizeTmp] == '\n') &&
395 Ptr[SizeTmp-1] != Ptr[SizeTmp])
396 ++SizeTmp;
397
398 // Found backslash<whitespace><newline>. Parse the char after it.
399 Size += SizeTmp;
400 Ptr += SizeTmp;
401 // Use slow version to accumulate a correct size field.
402 return getCharAndSizeSlow(Ptr, Size, Tok);
403 }
404 } while (isWhitespace(Ptr[SizeTmp]));
405 }
406
407 // Otherwise, this is not an escaped newline, just return the slash.
408 return '\\';
409 }
410
411 // If this is a trigraph, process it.
412 if (Ptr[0] == '?' && Ptr[1] == '?') {
413 // If this is actually a legal trigraph (not something like "??x"), emit
414 // a trigraph warning. If so, and if trigraphs are enabled, return it.
415 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : 0)) {
416 // Remember that this token needs to be cleaned.
417 if (Tok) Tok->setFlag(Token::NeedsCleaning);
418
419 Ptr += 3;
420 Size += 3;
421 if (C == '\\') goto Slash;
422 return C;
423 }
424 }
425
426 // If this is neither, return a single character.
427 ++Size;
428 return *Ptr;
429}
430
431
432/// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
433/// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
434/// and that we have already incremented Ptr by Size bytes.
435///
436/// NOTE: When this method is updated, getCharAndSizeSlow (above) should
437/// be updated to match.
438char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
439 const LangOptions &Features) {
440 // If we have a slash, look for an escaped newline.
441 if (Ptr[0] == '\\') {
442 ++Size;
443 ++Ptr;
444Slash:
445 // Common case, backslash-char where the char is not whitespace.
446 if (!isWhitespace(Ptr[0])) return '\\';
447
448 // See if we have optional whitespace characters followed by a newline.
449 {
450 unsigned SizeTmp = 0;
451 do {
452 ++SizeTmp;
453 if (Ptr[SizeTmp-1] == '\n' || Ptr[SizeTmp-1] == '\r') {
454
455 // If this is a \r\n or \n\r, skip the newlines.
456 if ((Ptr[SizeTmp] == '\r' || Ptr[SizeTmp] == '\n') &&
457 Ptr[SizeTmp-1] != Ptr[SizeTmp])
458 ++SizeTmp;
459
460 // Found backslash<whitespace><newline>. Parse the char after it.
461 Size += SizeTmp;
462 Ptr += SizeTmp;
463
464 // Use slow version to accumulate a correct size field.
465 return getCharAndSizeSlowNoWarn(Ptr, Size, Features);
466 }
467 } while (isWhitespace(Ptr[SizeTmp]));
468 }
469
470 // Otherwise, this is not an escaped newline, just return the slash.
471 return '\\';
472 }
473
474 // If this is a trigraph, process it.
475 if (Features.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
476 // If this is actually a legal trigraph (not something like "??x"), return
477 // it.
478 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
479 Ptr += 3;
480 Size += 3;
481 if (C == '\\') goto Slash;
482 return C;
483 }
484 }
485
486 // If this is neither, return a single character.
487 ++Size;
488 return *Ptr;
489}
490
491//===----------------------------------------------------------------------===//
492// Helper methods for lexing.
493//===----------------------------------------------------------------------===//
494
495void Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
496 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
497 unsigned Size;
498 unsigned char C = *CurPtr++;
499 while (isIdentifierBody(C)) {
500 C = *CurPtr++;
501 }
502 --CurPtr; // Back up over the skipped character.
503
504 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
505 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
506 // FIXME: UCNs.
507 if (C != '\\' && C != '?' && (C != '$' || !Features.DollarIdents)) {
508FinishIdentifier:
509 const char *IdStart = BufferPtr;
Chris Lattner0344cc72008-10-12 04:51:35 +0000510 FormTokenWithChars(Result, CurPtr, tok::identifier);
Chris Lattner4b009652007-07-25 00:24:17 +0000511
512 // If we are in raw mode, return this identifier raw. There is no need to
513 // look up identifier information or attempt to macro expand it.
514 if (LexingRawMode) return;
515
516 // Fill in Result.IdentifierInfo, looking up the identifier in the
517 // identifier table.
Chris Lattner342dccb2007-10-17 20:41:00 +0000518 PP->LookUpIdentifierInfo(Result, IdStart);
Chris Lattner4b009652007-07-25 00:24:17 +0000519
520 // Finally, now that we know we have an identifier, pass this off to the
521 // preprocessor, which may macro expand it or something.
Chris Lattner342dccb2007-10-17 20:41:00 +0000522 return PP->HandleIdentifier(Result);
Chris Lattner4b009652007-07-25 00:24:17 +0000523 }
524
525 // Otherwise, $,\,? in identifier found. Enter slower path.
526
527 C = getCharAndSize(CurPtr, Size);
528 while (1) {
529 if (C == '$') {
530 // If we hit a $ and they are not supported in identifiers, we are done.
531 if (!Features.DollarIdents) goto FinishIdentifier;
532
533 // Otherwise, emit a diagnostic and continue.
Chris Lattnerf9c62772008-11-22 02:02:22 +0000534 if (!isLexingRawMode())
535 Diag(CurPtr, diag::ext_dollar_in_identifier);
Chris Lattner4b009652007-07-25 00:24:17 +0000536 CurPtr = ConsumeChar(CurPtr, Size, Result);
537 C = getCharAndSize(CurPtr, Size);
538 continue;
539 } else if (!isIdentifierBody(C)) { // FIXME: UCNs.
540 // Found end of identifier.
541 goto FinishIdentifier;
542 }
543
544 // Otherwise, this character is good, consume it.
545 CurPtr = ConsumeChar(CurPtr, Size, Result);
546
547 C = getCharAndSize(CurPtr, Size);
548 while (isIdentifierBody(C)) { // FIXME: UCNs.
549 CurPtr = ConsumeChar(CurPtr, Size, Result);
550 C = getCharAndSize(CurPtr, Size);
551 }
552 }
553}
554
555
Nate Begeman937cac72008-04-14 02:26:39 +0000556/// LexNumericConstant - Lex the remainder of a integer or floating point
Chris Lattner4b009652007-07-25 00:24:17 +0000557/// constant. From[-1] is the first character lexed. Return the end of the
558/// constant.
559void Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
560 unsigned Size;
561 char C = getCharAndSize(CurPtr, Size);
562 char PrevCh = 0;
563 while (isNumberBody(C)) { // FIXME: UCNs?
564 CurPtr = ConsumeChar(CurPtr, Size, Result);
565 PrevCh = C;
566 C = getCharAndSize(CurPtr, Size);
567 }
568
569 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
570 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e'))
571 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
572
573 // If we have a hex FP constant, continue.
Chris Lattner9ba63822008-11-22 07:39:03 +0000574 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p') &&
575 (Features.HexFloats || !Features.NoExtensions))
Chris Lattner4b009652007-07-25 00:24:17 +0000576 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
577
Chris Lattner4b009652007-07-25 00:24:17 +0000578 // Update the location of token as well as BufferPtr.
Chris Lattner0344cc72008-10-12 04:51:35 +0000579 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
Chris Lattner4b009652007-07-25 00:24:17 +0000580}
581
582/// LexStringLiteral - Lex the remainder of a string literal, after having lexed
583/// either " or L".
Chris Lattner867a87b2008-10-12 04:05:48 +0000584void Lexer::LexStringLiteral(Token &Result, const char *CurPtr, bool Wide) {
Chris Lattner4b009652007-07-25 00:24:17 +0000585 const char *NulCharacter = 0; // Does this string contain the \0 character?
586
587 char C = getAndAdvanceChar(CurPtr, Result);
588 while (C != '"') {
589 // Skip escaped characters.
590 if (C == '\\') {
591 // Skip the escaped character.
592 C = getAndAdvanceChar(CurPtr, Result);
593 } else if (C == '\n' || C == '\r' || // Newline.
594 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Chris Lattnerf9c62772008-11-22 02:02:22 +0000595 if (!isLexingRawMode())
596 Diag(BufferPtr, diag::err_unterminated_string);
Chris Lattner0344cc72008-10-12 04:51:35 +0000597 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Chris Lattner4b009652007-07-25 00:24:17 +0000598 return;
599 } else if (C == 0) {
600 NulCharacter = CurPtr-1;
601 }
602 C = getAndAdvanceChar(CurPtr, Result);
603 }
604
605 // If a nul character existed in the string, warn about it.
Chris Lattnerf9c62772008-11-22 02:02:22 +0000606 if (NulCharacter && !isLexingRawMode())
607 Diag(NulCharacter, diag::null_in_string);
Chris Lattner4b009652007-07-25 00:24:17 +0000608
Chris Lattner4b009652007-07-25 00:24:17 +0000609 // Update the location of the token as well as the BufferPtr instance var.
Chris Lattner0344cc72008-10-12 04:51:35 +0000610 FormTokenWithChars(Result, CurPtr,
611 Wide ? tok::wide_string_literal : tok::string_literal);
Chris Lattner4b009652007-07-25 00:24:17 +0000612}
613
614/// LexAngledStringLiteral - Lex the remainder of an angled string literal,
615/// after having lexed the '<' character. This is used for #include filenames.
616void Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
617 const char *NulCharacter = 0; // Does this string contain the \0 character?
618
619 char C = getAndAdvanceChar(CurPtr, Result);
620 while (C != '>') {
621 // Skip escaped characters.
622 if (C == '\\') {
623 // Skip the escaped character.
624 C = getAndAdvanceChar(CurPtr, Result);
625 } else if (C == '\n' || C == '\r' || // Newline.
626 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Chris Lattnerf9c62772008-11-22 02:02:22 +0000627 if (!isLexingRawMode())
628 Diag(BufferPtr, diag::err_unterminated_string);
Chris Lattner0344cc72008-10-12 04:51:35 +0000629 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Chris Lattner4b009652007-07-25 00:24:17 +0000630 return;
631 } else if (C == 0) {
632 NulCharacter = CurPtr-1;
633 }
634 C = getAndAdvanceChar(CurPtr, Result);
635 }
636
637 // If a nul character existed in the string, warn about it.
Chris Lattnerf9c62772008-11-22 02:02:22 +0000638 if (NulCharacter && !isLexingRawMode())
639 Diag(NulCharacter, diag::null_in_string);
Chris Lattner4b009652007-07-25 00:24:17 +0000640
Chris Lattner4b009652007-07-25 00:24:17 +0000641 // Update the location of token as well as BufferPtr.
Chris Lattner0344cc72008-10-12 04:51:35 +0000642 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
Chris Lattner4b009652007-07-25 00:24:17 +0000643}
644
645
646/// LexCharConstant - Lex the remainder of a character constant, after having
647/// lexed either ' or L'.
648void Lexer::LexCharConstant(Token &Result, const char *CurPtr) {
649 const char *NulCharacter = 0; // Does this character contain the \0 character?
650
651 // Handle the common case of 'x' and '\y' efficiently.
652 char C = getAndAdvanceChar(CurPtr, Result);
653 if (C == '\'') {
Chris Lattnerf9c62772008-11-22 02:02:22 +0000654 if (!isLexingRawMode())
655 Diag(BufferPtr, diag::err_empty_character);
Chris Lattner0344cc72008-10-12 04:51:35 +0000656 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner4b009652007-07-25 00:24:17 +0000657 return;
658 } else if (C == '\\') {
659 // Skip the escaped character.
660 // FIXME: UCN's.
661 C = getAndAdvanceChar(CurPtr, Result);
662 }
663
664 if (C && C != '\n' && C != '\r' && CurPtr[0] == '\'') {
665 ++CurPtr;
666 } else {
667 // Fall back on generic code for embedded nulls, newlines, wide chars.
668 do {
669 // Skip escaped characters.
670 if (C == '\\') {
671 // Skip the escaped character.
672 C = getAndAdvanceChar(CurPtr, Result);
673 } else if (C == '\n' || C == '\r' || // Newline.
674 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Chris Lattnerf9c62772008-11-22 02:02:22 +0000675 if (!isLexingRawMode())
676 Diag(BufferPtr, diag::err_unterminated_char);
Chris Lattner0344cc72008-10-12 04:51:35 +0000677 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Chris Lattner4b009652007-07-25 00:24:17 +0000678 return;
679 } else if (C == 0) {
680 NulCharacter = CurPtr-1;
681 }
682 C = getAndAdvanceChar(CurPtr, Result);
683 } while (C != '\'');
684 }
685
Chris Lattnerf9c62772008-11-22 02:02:22 +0000686 if (NulCharacter && !isLexingRawMode())
687 Diag(NulCharacter, diag::null_in_char);
Chris Lattner4b009652007-07-25 00:24:17 +0000688
Chris Lattner4b009652007-07-25 00:24:17 +0000689 // Update the location of token as well as BufferPtr.
Chris Lattner0344cc72008-10-12 04:51:35 +0000690 FormTokenWithChars(Result, CurPtr, tok::char_constant);
Chris Lattner4b009652007-07-25 00:24:17 +0000691}
692
693/// SkipWhitespace - Efficiently skip over a series of whitespace characters.
694/// Update BufferPtr to point to the next non-whitespace character and return.
Chris Lattner867a87b2008-10-12 04:05:48 +0000695///
696/// This method forms a token and returns true if KeepWhitespaceMode is enabled.
697///
698bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr) {
Chris Lattner4b009652007-07-25 00:24:17 +0000699 // Whitespace - Skip it, then return the token after the whitespace.
700 unsigned char Char = *CurPtr; // Skip consequtive spaces efficiently.
701 while (1) {
702 // Skip horizontal whitespace very aggressively.
703 while (isHorizontalWhitespace(Char))
704 Char = *++CurPtr;
705
Daniel Dunbara2208392008-11-25 00:20:22 +0000706 // Otherwise if we have something other than whitespace, we're done.
Chris Lattner4b009652007-07-25 00:24:17 +0000707 if (Char != '\n' && Char != '\r')
708 break;
709
710 if (ParsingPreprocessorDirective) {
711 // End of preprocessor directive line, let LexTokenInternal handle this.
712 BufferPtr = CurPtr;
Chris Lattner867a87b2008-10-12 04:05:48 +0000713 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000714 }
715
716 // ok, but handle newline.
717 // The returned token is at the start of the line.
718 Result.setFlag(Token::StartOfLine);
719 // No leading whitespace seen so far.
720 Result.clearFlag(Token::LeadingSpace);
721 Char = *++CurPtr;
722 }
723
724 // If this isn't immediately after a newline, there is leading space.
725 char PrevChar = CurPtr[-1];
726 if (PrevChar != '\n' && PrevChar != '\r')
727 Result.setFlag(Token::LeadingSpace);
728
Chris Lattner867a87b2008-10-12 04:05:48 +0000729 // If the client wants us to return whitespace, return it now.
730 if (isKeepWhitespaceMode()) {
Chris Lattner0344cc72008-10-12 04:51:35 +0000731 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner867a87b2008-10-12 04:05:48 +0000732 return true;
733 }
734
Chris Lattner4b009652007-07-25 00:24:17 +0000735 BufferPtr = CurPtr;
Chris Lattner867a87b2008-10-12 04:05:48 +0000736 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000737}
738
739// SkipBCPLComment - We have just read the // characters from input. Skip until
740// we find the newline character thats terminate the comment. Then update
Chris Lattnerf03b00c2008-10-12 04:15:42 +0000741/// BufferPtr and return. If we're in KeepCommentMode, this will form the token
742/// and return true.
Chris Lattner4b009652007-07-25 00:24:17 +0000743bool Lexer::SkipBCPLComment(Token &Result, const char *CurPtr) {
744 // If BCPL comments aren't explicitly enabled for this language, emit an
745 // extension warning.
Chris Lattnerf9c62772008-11-22 02:02:22 +0000746 if (!Features.BCPLComment && !isLexingRawMode()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000747 Diag(BufferPtr, diag::ext_bcpl_comment);
748
749 // Mark them enabled so we only emit one warning for this translation
750 // unit.
751 Features.BCPLComment = true;
752 }
753
754 // Scan over the body of the comment. The common case, when scanning, is that
755 // the comment contains normal ascii characters with nothing interesting in
756 // them. As such, optimize for this case with the inner loop.
757 char C;
758 do {
759 C = *CurPtr;
760 // FIXME: Speedup BCPL comment lexing. Just scan for a \n or \r character.
761 // If we find a \n character, scan backwards, checking to see if it's an
762 // escaped newline, like we do for block comments.
763
764 // Skip over characters in the fast loop.
765 while (C != 0 && // Potentially EOF.
766 C != '\\' && // Potentially escaped newline.
767 C != '?' && // Potentially trigraph.
768 C != '\n' && C != '\r') // Newline or DOS-style newline.
769 C = *++CurPtr;
770
771 // If this is a newline, we're done.
772 if (C == '\n' || C == '\r')
773 break; // Found the newline? Break out!
774
775 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
Chris Lattnerc3697802008-12-12 07:34:39 +0000776 // properly decode the character. Read it in raw mode to avoid emitting
777 // diagnostics about things like trigraphs. If we see an escaped newline,
778 // we'll handle it below.
Chris Lattner4b009652007-07-25 00:24:17 +0000779 const char *OldPtr = CurPtr;
Chris Lattnerc3697802008-12-12 07:34:39 +0000780 bool OldRawMode = isLexingRawMode();
781 LexingRawMode = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000782 C = getAndAdvanceChar(CurPtr, Result);
Chris Lattnerc3697802008-12-12 07:34:39 +0000783 LexingRawMode = OldRawMode;
Chris Lattner4b009652007-07-25 00:24:17 +0000784
785 // If we read multiple characters, and one of those characters was a \r or
786 // \n, then we had an escaped newline within the comment. Emit diagnostic
787 // unless the next line is also a // comment.
788 if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') {
789 for (; OldPtr != CurPtr; ++OldPtr)
790 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
791 // Okay, we found a // comment that ends in a newline, if the next
792 // line is also a // comment, but has spaces, don't emit a diagnostic.
793 if (isspace(C)) {
794 const char *ForwardPtr = CurPtr;
795 while (isspace(*ForwardPtr)) // Skip whitespace.
796 ++ForwardPtr;
797 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
798 break;
799 }
800
Chris Lattnerf9c62772008-11-22 02:02:22 +0000801 if (!isLexingRawMode())
802 Diag(OldPtr-1, diag::ext_multi_line_bcpl_comment);
Chris Lattner4b009652007-07-25 00:24:17 +0000803 break;
804 }
805 }
806
807 if (CurPtr == BufferEnd+1) { --CurPtr; break; }
808 } while (C != '\n' && C != '\r');
809
810 // Found but did not consume the newline.
811
812 // If we are returning comments as tokens, return this comment as a token.
Chris Lattner170adb12008-10-12 03:22:02 +0000813 if (inKeepCommentMode())
Chris Lattner4b009652007-07-25 00:24:17 +0000814 return SaveBCPLComment(Result, CurPtr);
815
816 // If we are inside a preprocessor directive and we see the end of line,
817 // return immediately, so that the lexer can return this as an EOM token.
818 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
819 BufferPtr = CurPtr;
Chris Lattnerf03b00c2008-10-12 04:15:42 +0000820 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000821 }
822
823 // Otherwise, eat the \n character. We don't care if this is a \n\r or
Chris Lattner43d38202008-10-12 00:23:07 +0000824 // \r\n sequence. This is an efficiency hack (because we know the \n can't
Chris Lattner867a87b2008-10-12 04:05:48 +0000825 // contribute to another token), it isn't needed for correctness. Note that
826 // this is ok even in KeepWhitespaceMode, because we would have returned the
827 /// comment above in that mode.
Chris Lattner4b009652007-07-25 00:24:17 +0000828 ++CurPtr;
829
830 // The next returned token is at the start of the line.
831 Result.setFlag(Token::StartOfLine);
832 // No leading whitespace seen so far.
833 Result.clearFlag(Token::LeadingSpace);
834 BufferPtr = CurPtr;
Chris Lattnerf03b00c2008-10-12 04:15:42 +0000835 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000836}
837
838/// SaveBCPLComment - If in save-comment mode, package up this BCPL comment in
839/// an appropriate way and return it.
840bool Lexer::SaveBCPLComment(Token &Result, const char *CurPtr) {
Chris Lattner0344cc72008-10-12 04:51:35 +0000841 // If we're not in a preprocessor directive, just return the // comment
842 // directly.
843 FormTokenWithChars(Result, CurPtr, tok::comment);
Chris Lattner4b009652007-07-25 00:24:17 +0000844
Chris Lattner0344cc72008-10-12 04:51:35 +0000845 if (!ParsingPreprocessorDirective)
846 return true;
847
848 // If this BCPL-style comment is in a macro definition, transmogrify it into
849 // a C-style block comment.
850 std::string Spelling = PP->getSpelling(Result);
851 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not bcpl comment?");
852 Spelling[1] = '*'; // Change prefix to "/*".
853 Spelling += "*/"; // add suffix.
854
855 Result.setKind(tok::comment);
856 Result.setLocation(PP->CreateString(&Spelling[0], Spelling.size(),
857 Result.getLocation()));
858 Result.setLength(Spelling.size());
Chris Lattnerf03b00c2008-10-12 04:15:42 +0000859 return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000860}
861
862/// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
863/// character (either \n or \r) is part of an escaped newline sequence. Issue a
Chris Lattnerb3872872008-12-12 07:14:34 +0000864/// diagnostic if so. We know that the newline is inside of a block comment.
Chris Lattner4b009652007-07-25 00:24:17 +0000865static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
866 Lexer *L) {
867 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
868
869 // Back up off the newline.
870 --CurPtr;
871
872 // If this is a two-character newline sequence, skip the other character.
873 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
874 // \n\n or \r\r -> not escaped newline.
875 if (CurPtr[0] == CurPtr[1])
876 return false;
877 // \n\r or \r\n -> skip the newline.
878 --CurPtr;
879 }
880
881 // If we have horizontal whitespace, skip over it. We allow whitespace
882 // between the slash and newline.
883 bool HasSpace = false;
884 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
885 --CurPtr;
886 HasSpace = true;
887 }
888
889 // If we have a slash, we know this is an escaped newline.
890 if (*CurPtr == '\\') {
891 if (CurPtr[-1] != '*') return false;
892 } else {
893 // It isn't a slash, is it the ?? / trigraph?
894 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
895 CurPtr[-3] != '*')
896 return false;
897
898 // This is the trigraph ending the comment. Emit a stern warning!
899 CurPtr -= 2;
900
901 // If no trigraphs are enabled, warn that we ignored this trigraph and
902 // ignore this * character.
903 if (!L->getFeatures().Trigraphs) {
Chris Lattnerf9c62772008-11-22 02:02:22 +0000904 if (!L->isLexingRawMode())
905 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
Chris Lattner4b009652007-07-25 00:24:17 +0000906 return false;
907 }
Chris Lattnerf9c62772008-11-22 02:02:22 +0000908 if (!L->isLexingRawMode())
909 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
Chris Lattner4b009652007-07-25 00:24:17 +0000910 }
911
912 // Warn about having an escaped newline between the */ characters.
Chris Lattnerf9c62772008-11-22 02:02:22 +0000913 if (!L->isLexingRawMode())
914 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
Chris Lattner4b009652007-07-25 00:24:17 +0000915
916 // If there was space between the backslash and newline, warn about it.
Chris Lattnerf9c62772008-11-22 02:02:22 +0000917 if (HasSpace && !L->isLexingRawMode())
918 L->Diag(CurPtr, diag::backslash_newline_space);
Chris Lattner4b009652007-07-25 00:24:17 +0000919
920 return true;
921}
922
923#ifdef __SSE2__
924#include <emmintrin.h>
925#elif __ALTIVEC__
926#include <altivec.h>
927#undef bool
928#endif
929
930/// SkipBlockComment - We have just read the /* characters from input. Read
931/// until we find the */ characters that terminate the comment. Note that we
932/// don't bother decoding trigraphs or escaped newlines in block comments,
933/// because they cannot cause the comment to end. The only thing that can
934/// happen is the comment could end with an escaped newline between the */ end
935/// of comment.
Chris Lattnerf03b00c2008-10-12 04:15:42 +0000936///
937/// If KeepCommentMode is enabled, this forms a token from the comment and
938/// returns true.
Chris Lattner4b009652007-07-25 00:24:17 +0000939bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr) {
940 // Scan one character past where we should, looking for a '/' character. Once
941 // we find it, check to see if it was preceeded by a *. This common
942 // optimization helps people who like to put a lot of * characters in their
943 // comments.
944
945 // The first character we get with newlines and trigraphs skipped to handle
946 // the degenerate /*/ case below correctly if the * has an escaped newline
947 // after it.
948 unsigned CharSize;
949 unsigned char C = getCharAndSize(CurPtr, CharSize);
950 CurPtr += CharSize;
951 if (C == 0 && CurPtr == BufferEnd+1) {
Chris Lattnerf9c62772008-11-22 02:02:22 +0000952 if (!isLexingRawMode())
Chris Lattnere5eca952008-10-12 01:31:51 +0000953 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattnerd66f4542008-10-12 04:19:49 +0000954 --CurPtr;
955
956 // KeepWhitespaceMode should return this broken comment as a token. Since
957 // it isn't a well formed comment, just return it as an 'unknown' token.
958 if (isKeepWhitespaceMode()) {
Chris Lattner0344cc72008-10-12 04:51:35 +0000959 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd66f4542008-10-12 04:19:49 +0000960 return true;
961 }
962
963 BufferPtr = CurPtr;
Chris Lattnerf03b00c2008-10-12 04:15:42 +0000964 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000965 }
966
967 // Check to see if the first character after the '/*' is another /. If so,
968 // then this slash does not end the block comment, it is part of it.
969 if (C == '/')
970 C = *CurPtr++;
971
972 while (1) {
973 // Skip over all non-interesting characters until we find end of buffer or a
974 // (probably ending) '/' character.
975 if (CurPtr + 24 < BufferEnd) {
976 // While not aligned to a 16-byte boundary.
977 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
978 C = *CurPtr++;
979
980 if (C == '/') goto FoundSlash;
981
982#ifdef __SSE2__
983 __m128i Slashes = _mm_set_epi8('/', '/', '/', '/', '/', '/', '/', '/',
984 '/', '/', '/', '/', '/', '/', '/', '/');
985 while (CurPtr+16 <= BufferEnd &&
986 _mm_movemask_epi8(_mm_cmpeq_epi8(*(__m128i*)CurPtr, Slashes)) == 0)
987 CurPtr += 16;
988#elif __ALTIVEC__
989 __vector unsigned char Slashes = {
990 '/', '/', '/', '/', '/', '/', '/', '/',
991 '/', '/', '/', '/', '/', '/', '/', '/'
992 };
993 while (CurPtr+16 <= BufferEnd &&
994 !vec_any_eq(*(vector unsigned char*)CurPtr, Slashes))
995 CurPtr += 16;
996#else
997 // Scan for '/' quickly. Many block comments are very large.
998 while (CurPtr[0] != '/' &&
999 CurPtr[1] != '/' &&
1000 CurPtr[2] != '/' &&
1001 CurPtr[3] != '/' &&
1002 CurPtr+4 < BufferEnd) {
1003 CurPtr += 4;
1004 }
1005#endif
1006
1007 // It has to be one of the bytes scanned, increment to it and read one.
1008 C = *CurPtr++;
1009 }
1010
1011 // Loop to scan the remainder.
1012 while (C != '/' && C != '\0')
1013 C = *CurPtr++;
1014
1015 FoundSlash:
1016 if (C == '/') {
1017 if (CurPtr[-2] == '*') // We found the final */. We're done!
1018 break;
1019
1020 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
1021 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
1022 // We found the final */, though it had an escaped newline between the
1023 // * and /. We're done!
1024 break;
1025 }
1026 }
1027 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
1028 // If this is a /* inside of the comment, emit a warning. Don't do this
1029 // if this is a /*/, which will end the comment. This misses cases with
1030 // embedded escaped newlines, but oh well.
Chris Lattnerf9c62772008-11-22 02:02:22 +00001031 if (!isLexingRawMode())
1032 Diag(CurPtr-1, diag::warn_nested_block_comment);
Chris Lattner4b009652007-07-25 00:24:17 +00001033 }
1034 } else if (C == 0 && CurPtr == BufferEnd+1) {
Chris Lattnerf9c62772008-11-22 02:02:22 +00001035 if (!isLexingRawMode())
1036 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner4b009652007-07-25 00:24:17 +00001037 // Note: the user probably forgot a */. We could continue immediately
1038 // after the /*, but this would involve lexing a lot of what really is the
1039 // comment, which surely would confuse the parser.
Chris Lattnerd66f4542008-10-12 04:19:49 +00001040 --CurPtr;
1041
1042 // KeepWhitespaceMode should return this broken comment as a token. Since
1043 // it isn't a well formed comment, just return it as an 'unknown' token.
1044 if (isKeepWhitespaceMode()) {
Chris Lattner0344cc72008-10-12 04:51:35 +00001045 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd66f4542008-10-12 04:19:49 +00001046 return true;
1047 }
1048
1049 BufferPtr = CurPtr;
Chris Lattnerf03b00c2008-10-12 04:15:42 +00001050 return false;
Chris Lattner4b009652007-07-25 00:24:17 +00001051 }
1052 C = *CurPtr++;
1053 }
1054
1055 // If we are returning comments as tokens, return this comment as a token.
Chris Lattner170adb12008-10-12 03:22:02 +00001056 if (inKeepCommentMode()) {
Chris Lattner0344cc72008-10-12 04:51:35 +00001057 FormTokenWithChars(Result, CurPtr, tok::comment);
Chris Lattnerf03b00c2008-10-12 04:15:42 +00001058 return true;
Chris Lattner4b009652007-07-25 00:24:17 +00001059 }
1060
1061 // It is common for the tokens immediately after a /**/ comment to be
1062 // whitespace. Instead of going through the big switch, handle it
Chris Lattner867a87b2008-10-12 04:05:48 +00001063 // efficiently now. This is safe even in KeepWhitespaceMode because we would
1064 // have already returned above with the comment as a token.
Chris Lattner4b009652007-07-25 00:24:17 +00001065 if (isHorizontalWhitespace(*CurPtr)) {
1066 Result.setFlag(Token::LeadingSpace);
1067 SkipWhitespace(Result, CurPtr+1);
Chris Lattnerf03b00c2008-10-12 04:15:42 +00001068 return false;
Chris Lattner4b009652007-07-25 00:24:17 +00001069 }
1070
1071 // Otherwise, just return so that the next character will be lexed as a token.
1072 BufferPtr = CurPtr;
1073 Result.setFlag(Token::LeadingSpace);
Chris Lattnerf03b00c2008-10-12 04:15:42 +00001074 return false;
Chris Lattner4b009652007-07-25 00:24:17 +00001075}
1076
1077//===----------------------------------------------------------------------===//
1078// Primary Lexing Entry Points
1079//===----------------------------------------------------------------------===//
1080
Chris Lattner4b009652007-07-25 00:24:17 +00001081/// ReadToEndOfLine - Read the rest of the current preprocessor line as an
1082/// uninterpreted string. This switches the lexer out of directive mode.
1083std::string Lexer::ReadToEndOfLine() {
1084 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
1085 "Must be in a preprocessing directive!");
1086 std::string Result;
1087 Token Tmp;
1088
1089 // CurPtr - Cache BufferPtr in an automatic variable.
1090 const char *CurPtr = BufferPtr;
1091 while (1) {
1092 char Char = getAndAdvanceChar(CurPtr, Tmp);
1093 switch (Char) {
1094 default:
1095 Result += Char;
1096 break;
1097 case 0: // Null.
1098 // Found end of file?
1099 if (CurPtr-1 != BufferEnd) {
1100 // Nope, normal character, continue.
1101 Result += Char;
1102 break;
1103 }
1104 // FALL THROUGH.
1105 case '\r':
1106 case '\n':
1107 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
1108 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
1109 BufferPtr = CurPtr-1;
1110
1111 // Next, lex the character, which should handle the EOM transition.
1112 Lex(Tmp);
Chris Lattnercb8e41c2007-10-09 18:02:16 +00001113 assert(Tmp.is(tok::eom) && "Unexpected token!");
Chris Lattner4b009652007-07-25 00:24:17 +00001114
1115 // Finally, we're done, return the string we found.
1116 return Result;
1117 }
1118 }
1119}
1120
1121/// LexEndOfFile - CurPtr points to the end of this file. Handle this
1122/// condition, reporting diagnostics and handling other edge cases as required.
1123/// This returns true if Result contains a token, false if PP.Lex should be
1124/// called again.
1125bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
1126 // If we hit the end of the file while parsing a preprocessor directive,
1127 // end the preprocessor directive first. The next token returned will
1128 // then be the end of file.
1129 if (ParsingPreprocessorDirective) {
1130 // Done parsing the "line".
1131 ParsingPreprocessorDirective = false;
Chris Lattner4b009652007-07-25 00:24:17 +00001132 // Update the location of token as well as BufferPtr.
Chris Lattner0344cc72008-10-12 04:51:35 +00001133 FormTokenWithChars(Result, CurPtr, tok::eom);
Chris Lattner4b009652007-07-25 00:24:17 +00001134
1135 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattner1c1bed12008-10-12 03:27:19 +00001136 SetCommentRetentionState(PP->getCommentRetentionState());
Chris Lattner4b009652007-07-25 00:24:17 +00001137 return true; // Have a token.
1138 }
1139
1140 // If we are in raw mode, return this event as an EOF token. Let the caller
1141 // that put us in raw mode handle the event.
Chris Lattnerf9c62772008-11-22 02:02:22 +00001142 if (isLexingRawMode()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001143 Result.startToken();
1144 BufferPtr = BufferEnd;
Chris Lattner0344cc72008-10-12 04:51:35 +00001145 FormTokenWithChars(Result, BufferEnd, tok::eof);
Chris Lattner4b009652007-07-25 00:24:17 +00001146 return true;
1147 }
1148
1149 // Otherwise, issue diagnostics for unterminated #if and missing newline.
1150
1151 // If we are in a #if directive, emit an error.
1152 while (!ConditionalStack.empty()) {
Chris Lattner8ef6cdc2008-11-22 06:22:39 +00001153 PP->Diag(ConditionalStack.back().IfLoc,
1154 diag::err_pp_unterminated_conditional);
Chris Lattner4b009652007-07-25 00:24:17 +00001155 ConditionalStack.pop_back();
1156 }
1157
Chris Lattner5c337fa2008-04-12 05:54:25 +00001158 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
1159 // a pedwarn.
1160 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r'))
Chris Lattner4b009652007-07-25 00:24:17 +00001161 Diag(BufferEnd, diag::ext_no_newline_eof);
1162
1163 BufferPtr = CurPtr;
1164
1165 // Finally, let the preprocessor handle this.
Chris Lattner342dccb2007-10-17 20:41:00 +00001166 return PP->HandleEndOfFile(Result);
Chris Lattner4b009652007-07-25 00:24:17 +00001167}
1168
1169/// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
1170/// the specified lexer will return a tok::l_paren token, 0 if it is something
1171/// else and 2 if there are no more tokens in the buffer controlled by the
1172/// lexer.
1173unsigned Lexer::isNextPPTokenLParen() {
1174 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
1175
1176 // Switch to 'skipping' mode. This will ensure that we can lex a token
1177 // without emitting diagnostics, disables macro expansion, and will cause EOF
1178 // to return an EOF token instead of popping the include stack.
1179 LexingRawMode = true;
1180
1181 // Save state that can be changed while lexing so that we can restore it.
1182 const char *TmpBufferPtr = BufferPtr;
1183
1184 Token Tok;
1185 Tok.startToken();
1186 LexTokenInternal(Tok);
1187
1188 // Restore state that may have changed.
1189 BufferPtr = TmpBufferPtr;
1190
1191 // Restore the lexer back to non-skipping mode.
1192 LexingRawMode = false;
1193
Chris Lattnercb8e41c2007-10-09 18:02:16 +00001194 if (Tok.is(tok::eof))
Chris Lattner4b009652007-07-25 00:24:17 +00001195 return 2;
Chris Lattnercb8e41c2007-10-09 18:02:16 +00001196 return Tok.is(tok::l_paren);
Chris Lattner4b009652007-07-25 00:24:17 +00001197}
1198
1199
1200/// LexTokenInternal - This implements a simple C family lexer. It is an
1201/// extremely performance critical piece of code. This assumes that the buffer
1202/// has a null character at the end of the file. Return true if an error
1203/// occurred and compilation should terminate, false if normal. This returns a
1204/// preprocessing token, not a normal token, as such, it is an internal
1205/// interface. It assumes that the Flags of result have been cleared before
1206/// calling this.
1207void Lexer::LexTokenInternal(Token &Result) {
1208LexNextToken:
1209 // New token, can't need cleaning yet.
1210 Result.clearFlag(Token::NeedsCleaning);
1211 Result.setIdentifierInfo(0);
1212
1213 // CurPtr - Cache BufferPtr in an automatic variable.
1214 const char *CurPtr = BufferPtr;
1215
1216 // Small amounts of horizontal whitespace is very common between tokens.
1217 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
1218 ++CurPtr;
1219 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
1220 ++CurPtr;
Chris Lattner867a87b2008-10-12 04:05:48 +00001221
1222 // If we are keeping whitespace and other tokens, just return what we just
1223 // skipped. The next lexer invocation will return the token after the
1224 // whitespace.
1225 if (isKeepWhitespaceMode()) {
Chris Lattner0344cc72008-10-12 04:51:35 +00001226 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner867a87b2008-10-12 04:05:48 +00001227 return;
1228 }
1229
Chris Lattner4b009652007-07-25 00:24:17 +00001230 BufferPtr = CurPtr;
1231 Result.setFlag(Token::LeadingSpace);
1232 }
1233
1234 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
1235
1236 // Read a character, advancing over it.
1237 char Char = getAndAdvanceChar(CurPtr, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001238 tok::TokenKind Kind;
1239
Chris Lattner4b009652007-07-25 00:24:17 +00001240 switch (Char) {
1241 case 0: // Null.
1242 // Found end of file?
1243 if (CurPtr-1 == BufferEnd) {
1244 // Read the PP instance variable into an automatic variable, because
1245 // LexEndOfFile will often delete 'this'.
Chris Lattner342dccb2007-10-17 20:41:00 +00001246 Preprocessor *PPCache = PP;
Chris Lattner4b009652007-07-25 00:24:17 +00001247 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
1248 return; // Got a token to return.
Chris Lattner342dccb2007-10-17 20:41:00 +00001249 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
1250 return PPCache->Lex(Result);
Chris Lattner4b009652007-07-25 00:24:17 +00001251 }
1252
Chris Lattnerf9c62772008-11-22 02:02:22 +00001253 if (!isLexingRawMode())
1254 Diag(CurPtr-1, diag::null_in_file);
Chris Lattner4b009652007-07-25 00:24:17 +00001255 Result.setFlag(Token::LeadingSpace);
Chris Lattner867a87b2008-10-12 04:05:48 +00001256 if (SkipWhitespace(Result, CurPtr))
1257 return; // KeepWhitespaceMode
1258
Chris Lattner4b009652007-07-25 00:24:17 +00001259 goto LexNextToken; // GCC isn't tail call eliminating.
1260 case '\n':
1261 case '\r':
1262 // If we are inside a preprocessor directive and we see the end of line,
1263 // we know we are done with the directive, so return an EOM token.
1264 if (ParsingPreprocessorDirective) {
1265 // Done parsing the "line".
1266 ParsingPreprocessorDirective = false;
1267
1268 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattner1c1bed12008-10-12 03:27:19 +00001269 SetCommentRetentionState(PP->getCommentRetentionState());
Chris Lattner4b009652007-07-25 00:24:17 +00001270
1271 // Since we consumed a newline, we are back at the start of a line.
1272 IsAtStartOfLine = true;
1273
Chris Lattner0344cc72008-10-12 04:51:35 +00001274 Kind = tok::eom;
Chris Lattner4b009652007-07-25 00:24:17 +00001275 break;
1276 }
1277 // The returned token is at the start of the line.
1278 Result.setFlag(Token::StartOfLine);
1279 // No leading whitespace seen so far.
1280 Result.clearFlag(Token::LeadingSpace);
Chris Lattner867a87b2008-10-12 04:05:48 +00001281
1282 if (SkipWhitespace(Result, CurPtr))
1283 return; // KeepWhitespaceMode
Chris Lattner4b009652007-07-25 00:24:17 +00001284 goto LexNextToken; // GCC isn't tail call eliminating.
1285 case ' ':
1286 case '\t':
1287 case '\f':
1288 case '\v':
1289 SkipHorizontalWhitespace:
1290 Result.setFlag(Token::LeadingSpace);
Chris Lattner867a87b2008-10-12 04:05:48 +00001291 if (SkipWhitespace(Result, CurPtr))
1292 return; // KeepWhitespaceMode
Chris Lattner4b009652007-07-25 00:24:17 +00001293
1294 SkipIgnoredUnits:
1295 CurPtr = BufferPtr;
1296
1297 // If the next token is obviously a // or /* */ comment, skip it efficiently
1298 // too (without going through the big switch stmt).
Chris Lattner43e455d2009-01-16 22:39:25 +00001299 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
1300 Features.BCPLComment) {
Chris Lattner4b009652007-07-25 00:24:17 +00001301 SkipBCPLComment(Result, CurPtr+2);
1302 goto SkipIgnoredUnits;
Chris Lattner170adb12008-10-12 03:22:02 +00001303 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001304 SkipBlockComment(Result, CurPtr+2);
1305 goto SkipIgnoredUnits;
1306 } else if (isHorizontalWhitespace(*CurPtr)) {
1307 goto SkipHorizontalWhitespace;
1308 }
1309 goto LexNextToken; // GCC isn't tail call eliminating.
1310
Chris Lattner0ffadcc2008-01-03 17:58:54 +00001311 // C99 6.4.4.1: Integer Constants.
1312 // C99 6.4.4.2: Floating Constants.
1313 case '0': case '1': case '2': case '3': case '4':
1314 case '5': case '6': case '7': case '8': case '9':
1315 // Notify MIOpt that we read a non-whitespace/non-comment token.
1316 MIOpt.ReadToken();
1317 return LexNumericConstant(Result, CurPtr);
1318
1319 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
Chris Lattner4b009652007-07-25 00:24:17 +00001320 // Notify MIOpt that we read a non-whitespace/non-comment token.
1321 MIOpt.ReadToken();
1322 Char = getCharAndSize(CurPtr, SizeTmp);
1323
1324 // Wide string literal.
1325 if (Char == '"')
1326 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
1327 true);
1328
1329 // Wide character constant.
1330 if (Char == '\'')
1331 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
1332 // FALL THROUGH, treating L like the start of an identifier.
1333
1334 // C99 6.4.2: Identifiers.
1335 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
1336 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
1337 case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U':
1338 case 'V': case 'W': case 'X': case 'Y': case 'Z':
1339 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
1340 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
1341 case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u':
1342 case 'v': case 'w': case 'x': case 'y': case 'z':
1343 case '_':
1344 // Notify MIOpt that we read a non-whitespace/non-comment token.
1345 MIOpt.ReadToken();
1346 return LexIdentifier(Result, CurPtr);
Chris Lattner0ffadcc2008-01-03 17:58:54 +00001347
1348 case '$': // $ in identifiers.
1349 if (Features.DollarIdents) {
Chris Lattnerf9c62772008-11-22 02:02:22 +00001350 if (!isLexingRawMode())
1351 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
Chris Lattner0ffadcc2008-01-03 17:58:54 +00001352 // Notify MIOpt that we read a non-whitespace/non-comment token.
1353 MIOpt.ReadToken();
1354 return LexIdentifier(Result, CurPtr);
1355 }
Chris Lattner4b009652007-07-25 00:24:17 +00001356
Chris Lattner0344cc72008-10-12 04:51:35 +00001357 Kind = tok::unknown;
Chris Lattner0ffadcc2008-01-03 17:58:54 +00001358 break;
Chris Lattner4b009652007-07-25 00:24:17 +00001359
1360 // C99 6.4.4: Character Constants.
1361 case '\'':
1362 // Notify MIOpt that we read a non-whitespace/non-comment token.
1363 MIOpt.ReadToken();
1364 return LexCharConstant(Result, CurPtr);
1365
1366 // C99 6.4.5: String Literals.
1367 case '"':
1368 // Notify MIOpt that we read a non-whitespace/non-comment token.
1369 MIOpt.ReadToken();
1370 return LexStringLiteral(Result, CurPtr, false);
1371
1372 // C99 6.4.6: Punctuators.
1373 case '?':
Chris Lattner0344cc72008-10-12 04:51:35 +00001374 Kind = tok::question;
Chris Lattner4b009652007-07-25 00:24:17 +00001375 break;
1376 case '[':
Chris Lattner0344cc72008-10-12 04:51:35 +00001377 Kind = tok::l_square;
Chris Lattner4b009652007-07-25 00:24:17 +00001378 break;
1379 case ']':
Chris Lattner0344cc72008-10-12 04:51:35 +00001380 Kind = tok::r_square;
Chris Lattner4b009652007-07-25 00:24:17 +00001381 break;
1382 case '(':
Chris Lattner0344cc72008-10-12 04:51:35 +00001383 Kind = tok::l_paren;
Chris Lattner4b009652007-07-25 00:24:17 +00001384 break;
1385 case ')':
Chris Lattner0344cc72008-10-12 04:51:35 +00001386 Kind = tok::r_paren;
Chris Lattner4b009652007-07-25 00:24:17 +00001387 break;
1388 case '{':
Chris Lattner0344cc72008-10-12 04:51:35 +00001389 Kind = tok::l_brace;
Chris Lattner4b009652007-07-25 00:24:17 +00001390 break;
1391 case '}':
Chris Lattner0344cc72008-10-12 04:51:35 +00001392 Kind = tok::r_brace;
Chris Lattner4b009652007-07-25 00:24:17 +00001393 break;
1394 case '.':
1395 Char = getCharAndSize(CurPtr, SizeTmp);
1396 if (Char >= '0' && Char <= '9') {
1397 // Notify MIOpt that we read a non-whitespace/non-comment token.
1398 MIOpt.ReadToken();
1399
1400 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
1401 } else if (Features.CPlusPlus && Char == '*') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001402 Kind = tok::periodstar;
Chris Lattner4b009652007-07-25 00:24:17 +00001403 CurPtr += SizeTmp;
1404 } else if (Char == '.' &&
1405 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001406 Kind = tok::ellipsis;
Chris Lattner4b009652007-07-25 00:24:17 +00001407 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1408 SizeTmp2, Result);
1409 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001410 Kind = tok::period;
Chris Lattner4b009652007-07-25 00:24:17 +00001411 }
1412 break;
1413 case '&':
1414 Char = getCharAndSize(CurPtr, SizeTmp);
1415 if (Char == '&') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001416 Kind = tok::ampamp;
Chris Lattner4b009652007-07-25 00:24:17 +00001417 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1418 } else if (Char == '=') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001419 Kind = tok::ampequal;
Chris Lattner4b009652007-07-25 00:24:17 +00001420 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1421 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001422 Kind = tok::amp;
Chris Lattner4b009652007-07-25 00:24:17 +00001423 }
1424 break;
1425 case '*':
1426 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001427 Kind = tok::starequal;
Chris Lattner4b009652007-07-25 00:24:17 +00001428 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1429 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001430 Kind = tok::star;
Chris Lattner4b009652007-07-25 00:24:17 +00001431 }
1432 break;
1433 case '+':
1434 Char = getCharAndSize(CurPtr, SizeTmp);
1435 if (Char == '+') {
Chris Lattner4b009652007-07-25 00:24:17 +00001436 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001437 Kind = tok::plusplus;
Chris Lattner4b009652007-07-25 00:24:17 +00001438 } else if (Char == '=') {
Chris Lattner4b009652007-07-25 00:24:17 +00001439 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001440 Kind = tok::plusequal;
Chris Lattner4b009652007-07-25 00:24:17 +00001441 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001442 Kind = tok::plus;
Chris Lattner4b009652007-07-25 00:24:17 +00001443 }
1444 break;
1445 case '-':
1446 Char = getCharAndSize(CurPtr, SizeTmp);
Chris Lattner0344cc72008-10-12 04:51:35 +00001447 if (Char == '-') { // --
Chris Lattner4b009652007-07-25 00:24:17 +00001448 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001449 Kind = tok::minusminus;
Chris Lattner4b009652007-07-25 00:24:17 +00001450 } else if (Char == '>' && Features.CPlusPlus &&
Chris Lattner0344cc72008-10-12 04:51:35 +00001451 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
Chris Lattner4b009652007-07-25 00:24:17 +00001452 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1453 SizeTmp2, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001454 Kind = tok::arrowstar;
1455 } else if (Char == '>') { // ->
Chris Lattner4b009652007-07-25 00:24:17 +00001456 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001457 Kind = tok::arrow;
1458 } else if (Char == '=') { // -=
Chris Lattner4b009652007-07-25 00:24:17 +00001459 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001460 Kind = tok::minusequal;
Chris Lattner4b009652007-07-25 00:24:17 +00001461 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001462 Kind = tok::minus;
Chris Lattner4b009652007-07-25 00:24:17 +00001463 }
1464 break;
1465 case '~':
Chris Lattner0344cc72008-10-12 04:51:35 +00001466 Kind = tok::tilde;
Chris Lattner4b009652007-07-25 00:24:17 +00001467 break;
1468 case '!':
1469 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001470 Kind = tok::exclaimequal;
Chris Lattner4b009652007-07-25 00:24:17 +00001471 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1472 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001473 Kind = tok::exclaim;
Chris Lattner4b009652007-07-25 00:24:17 +00001474 }
1475 break;
1476 case '/':
1477 // 6.4.9: Comments
1478 Char = getCharAndSize(CurPtr, SizeTmp);
1479 if (Char == '/') { // BCPL comment.
Chris Lattner43e455d2009-01-16 22:39:25 +00001480 // Even if BCPL comments are disabled (e.g. in C89 mode), we generally
1481 // want to lex this as a comment. There is one problem with this though,
1482 // that in one particular corner case, this can change the behavior of the
1483 // resultant program. For example, In "foo //**/ bar", C89 would lex
1484 // this as "foo / bar" and langauges with BCPL comments would lex it as
1485 // "foo". Check to see if the character after the second slash is a '*'.
1486 // If so, we will lex that as a "/" instead of the start of a comment.
1487 if (Features.BCPLComment ||
1488 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*') {
1489 if (SkipBCPLComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
1490 return; // KeepCommentMode
Chris Lattnerf03b00c2008-10-12 04:15:42 +00001491
Chris Lattner43e455d2009-01-16 22:39:25 +00001492 // It is common for the tokens immediately after a // comment to be
1493 // whitespace (indentation for the next line). Instead of going through
1494 // the big switch, handle it efficiently now.
1495 goto SkipIgnoredUnits;
1496 }
1497 }
1498
1499 if (Char == '*') { // /**/ comment.
Chris Lattner4b009652007-07-25 00:24:17 +00001500 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattnerf03b00c2008-10-12 04:15:42 +00001501 return; // KeepCommentMode
1502 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattner43e455d2009-01-16 22:39:25 +00001503 }
1504
1505 if (Char == '=') {
Chris Lattner4b009652007-07-25 00:24:17 +00001506 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001507 Kind = tok::slashequal;
Chris Lattner4b009652007-07-25 00:24:17 +00001508 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001509 Kind = tok::slash;
Chris Lattner4b009652007-07-25 00:24:17 +00001510 }
1511 break;
1512 case '%':
1513 Char = getCharAndSize(CurPtr, SizeTmp);
1514 if (Char == '=') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001515 Kind = tok::percentequal;
Chris Lattner4b009652007-07-25 00:24:17 +00001516 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1517 } else if (Features.Digraphs && Char == '>') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001518 Kind = tok::r_brace; // '%>' -> '}'
Chris Lattner4b009652007-07-25 00:24:17 +00001519 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1520 } else if (Features.Digraphs && Char == ':') {
1521 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1522 Char = getCharAndSize(CurPtr, SizeTmp);
1523 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001524 Kind = tok::hashhash; // '%:%:' -> '##'
Chris Lattner4b009652007-07-25 00:24:17 +00001525 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1526 SizeTmp2, Result);
1527 } else if (Char == '@' && Features.Microsoft) { // %:@ -> #@ -> Charize
Chris Lattner4b009652007-07-25 00:24:17 +00001528 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerf9c62772008-11-22 02:02:22 +00001529 if (!isLexingRawMode())
1530 Diag(BufferPtr, diag::charize_microsoft_ext);
Chris Lattner0344cc72008-10-12 04:51:35 +00001531 Kind = tok::hashat;
Chris Lattner4b009652007-07-25 00:24:17 +00001532 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001533 Kind = tok::hash; // '%:' -> '#'
Chris Lattner4b009652007-07-25 00:24:17 +00001534
1535 // We parsed a # character. If this occurs at the start of the line,
1536 // it's actually the start of a preprocessing directive. Callback to
1537 // the preprocessor to handle it.
1538 // FIXME: -fpreprocessed mode??
1539 if (Result.isAtStartOfLine() && !LexingRawMode) {
1540 BufferPtr = CurPtr;
Chris Lattner342dccb2007-10-17 20:41:00 +00001541 PP->HandleDirective(Result);
Chris Lattner4b009652007-07-25 00:24:17 +00001542
1543 // As an optimization, if the preprocessor didn't switch lexers, tail
1544 // recurse.
Chris Lattner342dccb2007-10-17 20:41:00 +00001545 if (PP->isCurrentLexer(this)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001546 // Start a new token. If this is a #include or something, the PP may
1547 // want us starting at the beginning of the line again. If so, set
1548 // the StartOfLine flag.
1549 if (IsAtStartOfLine) {
1550 Result.setFlag(Token::StartOfLine);
1551 IsAtStartOfLine = false;
1552 }
1553 goto LexNextToken; // GCC isn't tail call eliminating.
1554 }
1555
Chris Lattner342dccb2007-10-17 20:41:00 +00001556 return PP->Lex(Result);
Chris Lattner4b009652007-07-25 00:24:17 +00001557 }
1558 }
1559 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001560 Kind = tok::percent;
Chris Lattner4b009652007-07-25 00:24:17 +00001561 }
1562 break;
1563 case '<':
1564 Char = getCharAndSize(CurPtr, SizeTmp);
1565 if (ParsingFilename) {
1566 return LexAngledStringLiteral(Result, CurPtr+SizeTmp);
1567 } else if (Char == '<' &&
1568 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '=') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001569 Kind = tok::lesslessequal;
Chris Lattner4b009652007-07-25 00:24:17 +00001570 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1571 SizeTmp2, Result);
1572 } else if (Char == '<') {
Chris Lattner4b009652007-07-25 00:24:17 +00001573 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001574 Kind = tok::lessless;
Chris Lattner4b009652007-07-25 00:24:17 +00001575 } else if (Char == '=') {
Chris Lattner4b009652007-07-25 00:24:17 +00001576 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001577 Kind = tok::lessequal;
1578 } else if (Features.Digraphs && Char == ':') { // '<:' -> '['
Chris Lattner4b009652007-07-25 00:24:17 +00001579 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001580 Kind = tok::l_square;
1581 } else if (Features.Digraphs && Char == '%') { // '<%' -> '{'
Chris Lattner4b009652007-07-25 00:24:17 +00001582 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001583 Kind = tok::l_brace;
Chris Lattner4b009652007-07-25 00:24:17 +00001584 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001585 Kind = tok::less;
Chris Lattner4b009652007-07-25 00:24:17 +00001586 }
1587 break;
1588 case '>':
1589 Char = getCharAndSize(CurPtr, SizeTmp);
1590 if (Char == '=') {
Chris Lattner4b009652007-07-25 00:24:17 +00001591 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001592 Kind = tok::greaterequal;
Chris Lattner4b009652007-07-25 00:24:17 +00001593 } else if (Char == '>' &&
1594 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '=') {
Chris Lattner4b009652007-07-25 00:24:17 +00001595 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1596 SizeTmp2, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001597 Kind = tok::greatergreaterequal;
Chris Lattner4b009652007-07-25 00:24:17 +00001598 } else if (Char == '>') {
Chris Lattner4b009652007-07-25 00:24:17 +00001599 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001600 Kind = tok::greatergreater;
Chris Lattner4b009652007-07-25 00:24:17 +00001601 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001602 Kind = tok::greater;
Chris Lattner4b009652007-07-25 00:24:17 +00001603 }
1604 break;
1605 case '^':
1606 Char = getCharAndSize(CurPtr, SizeTmp);
1607 if (Char == '=') {
Chris Lattner4b009652007-07-25 00:24:17 +00001608 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001609 Kind = tok::caretequal;
Chris Lattner4b009652007-07-25 00:24:17 +00001610 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001611 Kind = tok::caret;
Chris Lattner4b009652007-07-25 00:24:17 +00001612 }
1613 break;
1614 case '|':
1615 Char = getCharAndSize(CurPtr, SizeTmp);
1616 if (Char == '=') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001617 Kind = tok::pipeequal;
Chris Lattner4b009652007-07-25 00:24:17 +00001618 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1619 } else if (Char == '|') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001620 Kind = tok::pipepipe;
Chris Lattner4b009652007-07-25 00:24:17 +00001621 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1622 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001623 Kind = tok::pipe;
Chris Lattner4b009652007-07-25 00:24:17 +00001624 }
1625 break;
1626 case ':':
1627 Char = getCharAndSize(CurPtr, SizeTmp);
1628 if (Features.Digraphs && Char == '>') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001629 Kind = tok::r_square; // ':>' -> ']'
Chris Lattner4b009652007-07-25 00:24:17 +00001630 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1631 } else if (Features.CPlusPlus && Char == ':') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001632 Kind = tok::coloncolon;
Chris Lattner4b009652007-07-25 00:24:17 +00001633 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1634 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001635 Kind = tok::colon;
Chris Lattner4b009652007-07-25 00:24:17 +00001636 }
1637 break;
1638 case ';':
Chris Lattner0344cc72008-10-12 04:51:35 +00001639 Kind = tok::semi;
Chris Lattner4b009652007-07-25 00:24:17 +00001640 break;
1641 case '=':
1642 Char = getCharAndSize(CurPtr, SizeTmp);
1643 if (Char == '=') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001644 Kind = tok::equalequal;
Chris Lattner4b009652007-07-25 00:24:17 +00001645 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1646 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001647 Kind = tok::equal;
Chris Lattner4b009652007-07-25 00:24:17 +00001648 }
1649 break;
1650 case ',':
Chris Lattner0344cc72008-10-12 04:51:35 +00001651 Kind = tok::comma;
Chris Lattner4b009652007-07-25 00:24:17 +00001652 break;
1653 case '#':
1654 Char = getCharAndSize(CurPtr, SizeTmp);
1655 if (Char == '#') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001656 Kind = tok::hashhash;
Chris Lattner4b009652007-07-25 00:24:17 +00001657 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1658 } else if (Char == '@' && Features.Microsoft) { // #@ -> Charize
Chris Lattner0344cc72008-10-12 04:51:35 +00001659 Kind = tok::hashat;
Chris Lattnerf9c62772008-11-22 02:02:22 +00001660 if (!isLexingRawMode())
1661 Diag(BufferPtr, diag::charize_microsoft_ext);
Chris Lattner4b009652007-07-25 00:24:17 +00001662 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1663 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001664 Kind = tok::hash;
Chris Lattner4b009652007-07-25 00:24:17 +00001665 // We parsed a # character. If this occurs at the start of the line,
1666 // it's actually the start of a preprocessing directive. Callback to
1667 // the preprocessor to handle it.
1668 // FIXME: -fpreprocessed mode??
1669 if (Result.isAtStartOfLine() && !LexingRawMode) {
1670 BufferPtr = CurPtr;
Chris Lattner342dccb2007-10-17 20:41:00 +00001671 PP->HandleDirective(Result);
Chris Lattner4b009652007-07-25 00:24:17 +00001672
1673 // As an optimization, if the preprocessor didn't switch lexers, tail
1674 // recurse.
Chris Lattner342dccb2007-10-17 20:41:00 +00001675 if (PP->isCurrentLexer(this)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001676 // Start a new token. If this is a #include or something, the PP may
1677 // want us starting at the beginning of the line again. If so, set
1678 // the StartOfLine flag.
1679 if (IsAtStartOfLine) {
1680 Result.setFlag(Token::StartOfLine);
1681 IsAtStartOfLine = false;
1682 }
1683 goto LexNextToken; // GCC isn't tail call eliminating.
1684 }
Chris Lattner342dccb2007-10-17 20:41:00 +00001685 return PP->Lex(Result);
Chris Lattner4b009652007-07-25 00:24:17 +00001686 }
1687 }
1688 break;
1689
Chris Lattner0ffadcc2008-01-03 17:58:54 +00001690 case '@':
1691 // Objective C support.
1692 if (CurPtr[-1] == '@' && Features.ObjC1)
Chris Lattner0344cc72008-10-12 04:51:35 +00001693 Kind = tok::at;
Chris Lattner0ffadcc2008-01-03 17:58:54 +00001694 else
Chris Lattner0344cc72008-10-12 04:51:35 +00001695 Kind = tok::unknown;
Chris Lattner0ffadcc2008-01-03 17:58:54 +00001696 break;
1697
Chris Lattner4b009652007-07-25 00:24:17 +00001698 case '\\':
1699 // FIXME: UCN's.
1700 // FALL THROUGH.
1701 default:
Chris Lattner0344cc72008-10-12 04:51:35 +00001702 Kind = tok::unknown;
Chris Lattner4b009652007-07-25 00:24:17 +00001703 break;
1704 }
1705
1706 // Notify MIOpt that we read a non-whitespace/non-comment token.
1707 MIOpt.ReadToken();
1708
1709 // Update the location of token as well as BufferPtr.
Chris Lattner0344cc72008-10-12 04:51:35 +00001710 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner4b009652007-07-25 00:24:17 +00001711}