blob: f85cfd9f0f076adc466c2ff5d16aacef74330e39 [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
60
Chris Lattner342dccb2007-10-17 20:41:00 +000061/// Lexer constructor - Create a new lexer object for the specified buffer
62/// with the specified preprocessor managing the lexing process. This lexer
63/// assumes that the associated file buffer and Preprocessor objects will
64/// outlive it, so it doesn't take ownership of either of them.
Chris Lattner4b009652007-07-25 00:24:17 +000065Lexer::Lexer(SourceLocation fileloc, Preprocessor &pp,
66 const char *BufStart, const char *BufEnd)
Ted Kremenek56758d22008-11-19 21:57:25 +000067 : PreprocessorLexer(&pp, fileloc), FileLoc(fileloc),
68 Features(pp.getLangOptions()) {
Chris Lattner4b009652007-07-25 00:24:17 +000069
Chris Lattner342dccb2007-10-17 20:41:00 +000070 SourceManager &SourceMgr = PP->getSourceManager();
Chris Lattner4b009652007-07-25 00:24:17 +000071 unsigned InputFileID = SourceMgr.getPhysicalLoc(FileLoc).getFileID();
72 const llvm::MemoryBuffer *InputFile = SourceMgr.getBuffer(InputFileID);
73
74 Is_PragmaLexer = false;
Chris Lattner4b009652007-07-25 00:24:17 +000075 InitCharacterInfo();
76
77 // BufferStart must always be InputFile->getBufferStart().
78 BufferStart = InputFile->getBufferStart();
79
80 // BufferPtr and BufferEnd can start out somewhere inside the current buffer.
81 // If unspecified, they starts at the start/end of the buffer.
82 BufferPtr = BufStart ? BufStart : BufferStart;
83 BufferEnd = BufEnd ? BufEnd : InputFile->getBufferEnd();
84
85 assert(BufferEnd[0] == 0 &&
86 "We assume that the input buffer has a null character at the end"
87 " to simplify lexing!");
88
89 // Start of the file is a start of line.
90 IsAtStartOfLine = true;
91
92 // We are not after parsing a #.
93 ParsingPreprocessorDirective = false;
94
95 // We are not after parsing #include.
96 ParsingFilename = false;
97
98 // We are not in raw mode. Raw mode disables diagnostics and interpretation
99 // of tokens (e.g. identifiers, thus disabling macro expansion). It is used
100 // to quickly lex the tokens of the buffer, e.g. when handling a "#if 0" block
101 // or otherwise skipping over tokens.
102 LexingRawMode = false;
103
Chris Lattner867a87b2008-10-12 04:05:48 +0000104 // Default to keeping comments if the preprocessor wants them.
105 ExtendedTokenMode = 0;
Chris Lattner1c1bed12008-10-12 03:27:19 +0000106 SetCommentRetentionState(PP->getCommentRetentionState());
Chris Lattner4b009652007-07-25 00:24:17 +0000107}
108
Chris Lattner342dccb2007-10-17 20:41:00 +0000109/// Lexer constructor - Create a new raw lexer object. This object is only
Chris Lattner0b5892e2008-10-12 01:15:46 +0000110/// suitable for calls to 'LexRawToken'. This lexer assumes that the text
111/// range will outlive it, so it doesn't take ownership of it.
Chris Lattner342dccb2007-10-17 20:41:00 +0000112Lexer::Lexer(SourceLocation fileloc, const LangOptions &features,
Chris Lattner0b5892e2008-10-12 01:15:46 +0000113 const char *BufStart, const char *BufEnd,
114 const llvm::MemoryBuffer *FromFile)
Ted Kremenek56758d22008-11-19 21:57:25 +0000115 : PreprocessorLexer(), FileLoc(fileloc),
116 Features(features) {
117
Chris Lattner342dccb2007-10-17 20:41:00 +0000118 Is_PragmaLexer = false;
119 InitCharacterInfo();
120
Chris Lattner88ad2ac2008-10-12 01:23:27 +0000121 // If a MemoryBuffer was specified, use its start as BufferStart. This affects
122 // the source location objects produced by this lexer.
Chris Lattner0b5892e2008-10-12 01:15:46 +0000123 BufferStart = FromFile ? FromFile->getBufferStart() : BufStart;
Chris Lattner342dccb2007-10-17 20:41:00 +0000124 BufferPtr = BufStart;
125 BufferEnd = BufEnd;
126
127 assert(BufferEnd[0] == 0 &&
128 "We assume that the input buffer has a null character at the end"
129 " to simplify lexing!");
130
131 // Start of the file is a start of line.
132 IsAtStartOfLine = true;
133
134 // We are not after parsing a #.
135 ParsingPreprocessorDirective = false;
136
137 // We are not after parsing #include.
138 ParsingFilename = false;
139
140 // We *are* in raw mode.
141 LexingRawMode = true;
142
Chris Lattnercb8014e2008-10-12 01:34:51 +0000143 // Default to not keeping comments in raw mode.
Chris Lattner867a87b2008-10-12 04:05:48 +0000144 ExtendedTokenMode = 0;
Chris Lattner342dccb2007-10-17 20:41:00 +0000145}
146
147
Chris Lattner4b009652007-07-25 00:24:17 +0000148/// Stringify - Convert the specified string into a C string, with surrounding
149/// ""'s, and with escaped \ and " characters.
150std::string Lexer::Stringify(const std::string &Str, bool Charify) {
151 std::string Result = Str;
152 char Quote = Charify ? '\'' : '"';
153 for (unsigned i = 0, e = Result.size(); i != e; ++i) {
154 if (Result[i] == '\\' || Result[i] == Quote) {
155 Result.insert(Result.begin()+i, '\\');
156 ++i; ++e;
157 }
158 }
159 return Result;
160}
161
162/// Stringify - Convert the specified string into a C string by escaping '\'
163/// and " characters. This does not add surrounding ""'s to the string.
164void Lexer::Stringify(llvm::SmallVectorImpl<char> &Str) {
165 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
166 if (Str[i] == '\\' || Str[i] == '"') {
167 Str.insert(Str.begin()+i, '\\');
168 ++i; ++e;
169 }
170 }
171}
172
173
Chris Lattner761d76b2007-10-17 21:18:47 +0000174/// MeasureTokenLength - Relex the token at the specified location and return
175/// its length in bytes in the input file. If the token needs cleaning (e.g.
176/// includes a trigraph or an escaped newline) then this count includes bytes
177/// that are part of that.
178unsigned Lexer::MeasureTokenLength(SourceLocation Loc,
179 const SourceManager &SM) {
180 // If this comes from a macro expansion, we really do want the macro name, not
181 // the token this macro expanded to.
182 Loc = SM.getLogicalLoc(Loc);
183
184 const char *StrData = SM.getCharacterData(Loc);
185
186 // TODO: this could be special cased for common tokens like identifiers, ')',
187 // etc to make this faster, if it mattered. Just look at StrData[0] to handle
188 // all obviously single-char tokens. This could use
189 // Lexer::isObviouslySimpleCharacter for example to handle identifiers or
190 // something.
191
192
193 const char *BufEnd = SM.getBufferData(Loc.getFileID()).second;
194
195 // Create a langops struct and enable trigraphs. This is sufficient for
196 // measuring tokens.
197 LangOptions LangOpts;
198 LangOpts.Trigraphs = true;
199
200 // Create a lexer starting at the beginning of this token.
201 Lexer TheLexer(Loc, LangOpts, StrData, BufEnd);
202 Token TheTok;
Chris Lattner0b5892e2008-10-12 01:15:46 +0000203 TheLexer.LexFromRawLexer(TheTok);
Chris Lattner761d76b2007-10-17 21:18:47 +0000204 return TheTok.getLength();
205}
206
Chris Lattner4b009652007-07-25 00:24:17 +0000207//===----------------------------------------------------------------------===//
208// Character information.
209//===----------------------------------------------------------------------===//
210
211static unsigned char CharInfo[256];
212
213enum {
214 CHAR_HORZ_WS = 0x01, // ' ', '\t', '\f', '\v'. Note, no '\0'
215 CHAR_VERT_WS = 0x02, // '\r', '\n'
216 CHAR_LETTER = 0x04, // a-z,A-Z
217 CHAR_NUMBER = 0x08, // 0-9
218 CHAR_UNDER = 0x10, // _
219 CHAR_PERIOD = 0x20 // .
220};
221
222static void InitCharacterInfo() {
223 static bool isInited = false;
224 if (isInited) return;
225 isInited = true;
226
227 // Intiialize the CharInfo table.
228 // TODO: statically initialize this.
229 CharInfo[(int)' '] = CharInfo[(int)'\t'] =
230 CharInfo[(int)'\f'] = CharInfo[(int)'\v'] = CHAR_HORZ_WS;
231 CharInfo[(int)'\n'] = CharInfo[(int)'\r'] = CHAR_VERT_WS;
232
233 CharInfo[(int)'_'] = CHAR_UNDER;
234 CharInfo[(int)'.'] = CHAR_PERIOD;
235 for (unsigned i = 'a'; i <= 'z'; ++i)
236 CharInfo[i] = CharInfo[i+'A'-'a'] = CHAR_LETTER;
237 for (unsigned i = '0'; i <= '9'; ++i)
238 CharInfo[i] = CHAR_NUMBER;
239}
240
241/// isIdentifierBody - Return true if this is the body character of an
242/// identifier, which is [a-zA-Z0-9_].
243static inline bool isIdentifierBody(unsigned char c) {
Hartmut Kaiserc62f6b92007-10-18 12:47:01 +0000244 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER)) ? true : false;
Chris Lattner4b009652007-07-25 00:24:17 +0000245}
246
247/// isHorizontalWhitespace - Return true if this character is horizontal
248/// whitespace: ' ', '\t', '\f', '\v'. Note that this returns false for '\0'.
249static inline bool isHorizontalWhitespace(unsigned char c) {
Hartmut Kaiserc62f6b92007-10-18 12:47:01 +0000250 return (CharInfo[c] & CHAR_HORZ_WS) ? true : false;
Chris Lattner4b009652007-07-25 00:24:17 +0000251}
252
253/// isWhitespace - Return true if this character is horizontal or vertical
254/// whitespace: ' ', '\t', '\f', '\v', '\n', '\r'. Note that this returns false
255/// for '\0'.
256static inline bool isWhitespace(unsigned char c) {
Hartmut Kaiserc62f6b92007-10-18 12:47:01 +0000257 return (CharInfo[c] & (CHAR_HORZ_WS|CHAR_VERT_WS)) ? true : false;
Chris Lattner4b009652007-07-25 00:24:17 +0000258}
259
260/// isNumberBody - Return true if this is the body character of an
261/// preprocessing number, which is [a-zA-Z0-9_.].
262static inline bool isNumberBody(unsigned char c) {
Hartmut Kaiserc62f6b92007-10-18 12:47:01 +0000263 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER|CHAR_PERIOD)) ?
264 true : false;
Chris Lattner4b009652007-07-25 00:24:17 +0000265}
266
267
268//===----------------------------------------------------------------------===//
269// Diagnostics forwarding code.
270//===----------------------------------------------------------------------===//
271
272/// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
273/// lexer buffer was all instantiated at a single point, perform the mapping.
274/// This is currently only used for _Pragma implementation, so it is the slow
275/// path of the hot getSourceLocation method. Do not allow it to be inlined.
276static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
277 SourceLocation FileLoc,
278 unsigned CharNo) DISABLE_INLINE;
279static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
280 SourceLocation FileLoc,
281 unsigned CharNo) {
282 // Otherwise, we're lexing "mapped tokens". This is used for things like
283 // _Pragma handling. Combine the instantiation location of FileLoc with the
284 // physical location.
285 SourceManager &SourceMgr = PP.getSourceManager();
286
287 // Create a new SLoc which is expanded from logical(FileLoc) but whose
288 // characters come from phys(FileLoc)+Offset.
289 SourceLocation VirtLoc = SourceMgr.getLogicalLoc(FileLoc);
290 SourceLocation PhysLoc = SourceMgr.getPhysicalLoc(FileLoc);
291 PhysLoc = SourceLocation::getFileLoc(PhysLoc.getFileID(), CharNo);
292 return SourceMgr.getInstantiationLoc(PhysLoc, VirtLoc);
293}
294
295/// getSourceLocation - Return a source location identifier for the specified
296/// offset in the current file.
297SourceLocation Lexer::getSourceLocation(const char *Loc) const {
298 assert(Loc >= BufferStart && Loc <= BufferEnd &&
299 "Location out of range for this buffer!");
300
301 // In the normal case, we're just lexing from a simple file buffer, return
302 // the file id from FileLoc with the offset specified.
303 unsigned CharNo = Loc-BufferStart;
304 if (FileLoc.isFileID())
305 return SourceLocation::getFileLoc(FileLoc.getFileID(), CharNo);
306
Chris Lattner342dccb2007-10-17 20:41:00 +0000307 assert(PP && "This doesn't work on raw lexers");
308 return GetMappedTokenLoc(*PP, FileLoc, CharNo);
Chris Lattner4b009652007-07-25 00:24:17 +0000309}
310
311/// Diag - Forwarding function for diagnostics. This translate a source
312/// position in the current buffer into a SourceLocation object for rendering.
Chris Lattner9943e982008-11-22 00:59:29 +0000313DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
Chris Lattner0370d6b2008-11-18 07:59:24 +0000314 return PP->Diag(getSourceLocation(Loc), DiagID);
Chris Lattner4b009652007-07-25 00:24:17 +0000315}
Chris Lattner4b009652007-07-25 00:24:17 +0000316
317//===----------------------------------------------------------------------===//
318// Trigraph and Escaped Newline Handling Code.
319//===----------------------------------------------------------------------===//
320
321/// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
322/// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
323static char GetTrigraphCharForLetter(char Letter) {
324 switch (Letter) {
325 default: return 0;
326 case '=': return '#';
327 case ')': return ']';
328 case '(': return '[';
329 case '!': return '|';
330 case '\'': return '^';
331 case '>': return '}';
332 case '/': return '\\';
333 case '<': return '{';
334 case '-': return '~';
335 }
336}
337
338/// DecodeTrigraphChar - If the specified character is a legal trigraph when
339/// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
340/// return the result character. Finally, emit a warning about trigraph use
341/// whether trigraphs are enabled or not.
342static char DecodeTrigraphChar(const char *CP, Lexer *L) {
343 char Res = GetTrigraphCharForLetter(*CP);
Chris Lattner0370d6b2008-11-18 07:59:24 +0000344 if (!Res || !L) return Res;
345
346 if (!L->getFeatures().Trigraphs) {
Chris Lattnerf9c62772008-11-22 02:02:22 +0000347 if (!L->isLexingRawMode())
348 L->Diag(CP-2, diag::trigraph_ignored);
Chris Lattner0370d6b2008-11-18 07:59:24 +0000349 return 0;
Chris Lattner4b009652007-07-25 00:24:17 +0000350 }
Chris Lattner0370d6b2008-11-18 07:59:24 +0000351
Chris Lattnerf9c62772008-11-22 02:02:22 +0000352 if (!L->isLexingRawMode())
353 L->Diag(CP-2, diag::trigraph_converted) << std::string()+Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000354 return Res;
355}
356
357/// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
358/// get its size, and return it. This is tricky in several cases:
359/// 1. If currently at the start of a trigraph, we warn about the trigraph,
360/// then either return the trigraph (skipping 3 chars) or the '?',
361/// depending on whether trigraphs are enabled or not.
362/// 2. If this is an escaped newline (potentially with whitespace between
363/// the backslash and newline), implicitly skip the newline and return
364/// the char after it.
365/// 3. If this is a UCN, return it. FIXME: C++ UCN's?
366///
367/// This handles the slow/uncommon case of the getCharAndSize method. Here we
368/// know that we can accumulate into Size, and that we have already incremented
369/// Ptr by Size bytes.
370///
371/// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
372/// be updated to match.
373///
374char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
375 Token *Tok) {
376 // If we have a slash, look for an escaped newline.
377 if (Ptr[0] == '\\') {
378 ++Size;
379 ++Ptr;
380Slash:
381 // Common case, backslash-char where the char is not whitespace.
382 if (!isWhitespace(Ptr[0])) return '\\';
383
384 // See if we have optional whitespace characters followed by a newline.
385 {
386 unsigned SizeTmp = 0;
387 do {
388 ++SizeTmp;
389 if (Ptr[SizeTmp-1] == '\n' || Ptr[SizeTmp-1] == '\r') {
390 // Remember that this token needs to be cleaned.
391 if (Tok) Tok->setFlag(Token::NeedsCleaning);
392
393 // Warn if there was whitespace between the backslash and newline.
Chris Lattnerf9c62772008-11-22 02:02:22 +0000394 if (SizeTmp != 1 && Tok && !isLexingRawMode())
Chris Lattner4b009652007-07-25 00:24:17 +0000395 Diag(Ptr, diag::backslash_newline_space);
396
397 // If this is a \r\n or \n\r, skip the newlines.
398 if ((Ptr[SizeTmp] == '\r' || Ptr[SizeTmp] == '\n') &&
399 Ptr[SizeTmp-1] != Ptr[SizeTmp])
400 ++SizeTmp;
401
402 // Found backslash<whitespace><newline>. Parse the char after it.
403 Size += SizeTmp;
404 Ptr += SizeTmp;
405 // Use slow version to accumulate a correct size field.
406 return getCharAndSizeSlow(Ptr, Size, Tok);
407 }
408 } while (isWhitespace(Ptr[SizeTmp]));
409 }
410
411 // Otherwise, this is not an escaped newline, just return the slash.
412 return '\\';
413 }
414
415 // If this is a trigraph, process it.
416 if (Ptr[0] == '?' && Ptr[1] == '?') {
417 // If this is actually a legal trigraph (not something like "??x"), emit
418 // a trigraph warning. If so, and if trigraphs are enabled, return it.
419 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : 0)) {
420 // Remember that this token needs to be cleaned.
421 if (Tok) Tok->setFlag(Token::NeedsCleaning);
422
423 Ptr += 3;
424 Size += 3;
425 if (C == '\\') goto Slash;
426 return C;
427 }
428 }
429
430 // If this is neither, return a single character.
431 ++Size;
432 return *Ptr;
433}
434
435
436/// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
437/// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
438/// and that we have already incremented Ptr by Size bytes.
439///
440/// NOTE: When this method is updated, getCharAndSizeSlow (above) should
441/// be updated to match.
442char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
443 const LangOptions &Features) {
444 // If we have a slash, look for an escaped newline.
445 if (Ptr[0] == '\\') {
446 ++Size;
447 ++Ptr;
448Slash:
449 // Common case, backslash-char where the char is not whitespace.
450 if (!isWhitespace(Ptr[0])) return '\\';
451
452 // See if we have optional whitespace characters followed by a newline.
453 {
454 unsigned SizeTmp = 0;
455 do {
456 ++SizeTmp;
457 if (Ptr[SizeTmp-1] == '\n' || Ptr[SizeTmp-1] == '\r') {
458
459 // If this is a \r\n or \n\r, skip the newlines.
460 if ((Ptr[SizeTmp] == '\r' || Ptr[SizeTmp] == '\n') &&
461 Ptr[SizeTmp-1] != Ptr[SizeTmp])
462 ++SizeTmp;
463
464 // Found backslash<whitespace><newline>. Parse the char after it.
465 Size += SizeTmp;
466 Ptr += SizeTmp;
467
468 // Use slow version to accumulate a correct size field.
469 return getCharAndSizeSlowNoWarn(Ptr, Size, Features);
470 }
471 } while (isWhitespace(Ptr[SizeTmp]));
472 }
473
474 // Otherwise, this is not an escaped newline, just return the slash.
475 return '\\';
476 }
477
478 // If this is a trigraph, process it.
479 if (Features.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
480 // If this is actually a legal trigraph (not something like "??x"), return
481 // it.
482 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
483 Ptr += 3;
484 Size += 3;
485 if (C == '\\') goto Slash;
486 return C;
487 }
488 }
489
490 // If this is neither, return a single character.
491 ++Size;
492 return *Ptr;
493}
494
495//===----------------------------------------------------------------------===//
496// Helper methods for lexing.
497//===----------------------------------------------------------------------===//
498
499void Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
500 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
501 unsigned Size;
502 unsigned char C = *CurPtr++;
503 while (isIdentifierBody(C)) {
504 C = *CurPtr++;
505 }
506 --CurPtr; // Back up over the skipped character.
507
508 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
509 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
510 // FIXME: UCNs.
511 if (C != '\\' && C != '?' && (C != '$' || !Features.DollarIdents)) {
512FinishIdentifier:
513 const char *IdStart = BufferPtr;
Chris Lattner0344cc72008-10-12 04:51:35 +0000514 FormTokenWithChars(Result, CurPtr, tok::identifier);
Chris Lattner4b009652007-07-25 00:24:17 +0000515
516 // If we are in raw mode, return this identifier raw. There is no need to
517 // look up identifier information or attempt to macro expand it.
518 if (LexingRawMode) return;
519
520 // Fill in Result.IdentifierInfo, looking up the identifier in the
521 // identifier table.
Chris Lattner342dccb2007-10-17 20:41:00 +0000522 PP->LookUpIdentifierInfo(Result, IdStart);
Chris Lattner4b009652007-07-25 00:24:17 +0000523
524 // Finally, now that we know we have an identifier, pass this off to the
525 // preprocessor, which may macro expand it or something.
Chris Lattner342dccb2007-10-17 20:41:00 +0000526 return PP->HandleIdentifier(Result);
Chris Lattner4b009652007-07-25 00:24:17 +0000527 }
528
529 // Otherwise, $,\,? in identifier found. Enter slower path.
530
531 C = getCharAndSize(CurPtr, Size);
532 while (1) {
533 if (C == '$') {
534 // If we hit a $ and they are not supported in identifiers, we are done.
535 if (!Features.DollarIdents) goto FinishIdentifier;
536
537 // Otherwise, emit a diagnostic and continue.
Chris Lattnerf9c62772008-11-22 02:02:22 +0000538 if (!isLexingRawMode())
539 Diag(CurPtr, diag::ext_dollar_in_identifier);
Chris Lattner4b009652007-07-25 00:24:17 +0000540 CurPtr = ConsumeChar(CurPtr, Size, Result);
541 C = getCharAndSize(CurPtr, Size);
542 continue;
543 } else if (!isIdentifierBody(C)) { // FIXME: UCNs.
544 // Found end of identifier.
545 goto FinishIdentifier;
546 }
547
548 // Otherwise, this character is good, consume it.
549 CurPtr = ConsumeChar(CurPtr, Size, Result);
550
551 C = getCharAndSize(CurPtr, Size);
552 while (isIdentifierBody(C)) { // FIXME: UCNs.
553 CurPtr = ConsumeChar(CurPtr, Size, Result);
554 C = getCharAndSize(CurPtr, Size);
555 }
556 }
557}
558
559
Nate Begeman937cac72008-04-14 02:26:39 +0000560/// LexNumericConstant - Lex the remainder of a integer or floating point
Chris Lattner4b009652007-07-25 00:24:17 +0000561/// constant. From[-1] is the first character lexed. Return the end of the
562/// constant.
563void Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
564 unsigned Size;
565 char C = getCharAndSize(CurPtr, Size);
566 char PrevCh = 0;
567 while (isNumberBody(C)) { // FIXME: UCNs?
568 CurPtr = ConsumeChar(CurPtr, Size, Result);
569 PrevCh = C;
570 C = getCharAndSize(CurPtr, Size);
571 }
572
573 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
574 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e'))
575 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
576
577 // If we have a hex FP constant, continue.
Chris Lattner9ba63822008-11-22 07:39:03 +0000578 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p') &&
579 (Features.HexFloats || !Features.NoExtensions))
Chris Lattner4b009652007-07-25 00:24:17 +0000580 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
581
Chris Lattner4b009652007-07-25 00:24:17 +0000582 // Update the location of token as well as BufferPtr.
Chris Lattner0344cc72008-10-12 04:51:35 +0000583 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
Chris Lattner4b009652007-07-25 00:24:17 +0000584}
585
586/// LexStringLiteral - Lex the remainder of a string literal, after having lexed
587/// either " or L".
Chris Lattner867a87b2008-10-12 04:05:48 +0000588void Lexer::LexStringLiteral(Token &Result, const char *CurPtr, bool Wide) {
Chris Lattner4b009652007-07-25 00:24:17 +0000589 const char *NulCharacter = 0; // Does this string contain the \0 character?
590
591 char C = getAndAdvanceChar(CurPtr, Result);
592 while (C != '"') {
593 // Skip escaped characters.
594 if (C == '\\') {
595 // Skip the escaped character.
596 C = getAndAdvanceChar(CurPtr, Result);
597 } else if (C == '\n' || C == '\r' || // Newline.
598 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Chris Lattnerf9c62772008-11-22 02:02:22 +0000599 if (!isLexingRawMode())
600 Diag(BufferPtr, diag::err_unterminated_string);
Chris Lattner0344cc72008-10-12 04:51:35 +0000601 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Chris Lattner4b009652007-07-25 00:24:17 +0000602 return;
603 } else if (C == 0) {
604 NulCharacter = CurPtr-1;
605 }
606 C = getAndAdvanceChar(CurPtr, Result);
607 }
608
609 // If a nul character existed in the string, warn about it.
Chris Lattnerf9c62772008-11-22 02:02:22 +0000610 if (NulCharacter && !isLexingRawMode())
611 Diag(NulCharacter, diag::null_in_string);
Chris Lattner4b009652007-07-25 00:24:17 +0000612
Chris Lattner4b009652007-07-25 00:24:17 +0000613 // Update the location of the token as well as the BufferPtr instance var.
Chris Lattner0344cc72008-10-12 04:51:35 +0000614 FormTokenWithChars(Result, CurPtr,
615 Wide ? tok::wide_string_literal : tok::string_literal);
Chris Lattner4b009652007-07-25 00:24:17 +0000616}
617
618/// LexAngledStringLiteral - Lex the remainder of an angled string literal,
619/// after having lexed the '<' character. This is used for #include filenames.
620void Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
621 const char *NulCharacter = 0; // Does this string contain the \0 character?
622
623 char C = getAndAdvanceChar(CurPtr, Result);
624 while (C != '>') {
625 // Skip escaped characters.
626 if (C == '\\') {
627 // Skip the escaped character.
628 C = getAndAdvanceChar(CurPtr, Result);
629 } else if (C == '\n' || C == '\r' || // Newline.
630 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Chris Lattnerf9c62772008-11-22 02:02:22 +0000631 if (!isLexingRawMode())
632 Diag(BufferPtr, diag::err_unterminated_string);
Chris Lattner0344cc72008-10-12 04:51:35 +0000633 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Chris Lattner4b009652007-07-25 00:24:17 +0000634 return;
635 } else if (C == 0) {
636 NulCharacter = CurPtr-1;
637 }
638 C = getAndAdvanceChar(CurPtr, Result);
639 }
640
641 // If a nul character existed in the string, warn about it.
Chris Lattnerf9c62772008-11-22 02:02:22 +0000642 if (NulCharacter && !isLexingRawMode())
643 Diag(NulCharacter, diag::null_in_string);
Chris Lattner4b009652007-07-25 00:24:17 +0000644
Chris Lattner4b009652007-07-25 00:24:17 +0000645 // Update the location of token as well as BufferPtr.
Chris Lattner0344cc72008-10-12 04:51:35 +0000646 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
Chris Lattner4b009652007-07-25 00:24:17 +0000647}
648
649
650/// LexCharConstant - Lex the remainder of a character constant, after having
651/// lexed either ' or L'.
652void Lexer::LexCharConstant(Token &Result, const char *CurPtr) {
653 const char *NulCharacter = 0; // Does this character contain the \0 character?
654
655 // Handle the common case of 'x' and '\y' efficiently.
656 char C = getAndAdvanceChar(CurPtr, Result);
657 if (C == '\'') {
Chris Lattnerf9c62772008-11-22 02:02:22 +0000658 if (!isLexingRawMode())
659 Diag(BufferPtr, diag::err_empty_character);
Chris Lattner0344cc72008-10-12 04:51:35 +0000660 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner4b009652007-07-25 00:24:17 +0000661 return;
662 } else if (C == '\\') {
663 // Skip the escaped character.
664 // FIXME: UCN's.
665 C = getAndAdvanceChar(CurPtr, Result);
666 }
667
668 if (C && C != '\n' && C != '\r' && CurPtr[0] == '\'') {
669 ++CurPtr;
670 } else {
671 // Fall back on generic code for embedded nulls, newlines, wide chars.
672 do {
673 // Skip escaped characters.
674 if (C == '\\') {
675 // Skip the escaped character.
676 C = getAndAdvanceChar(CurPtr, Result);
677 } else if (C == '\n' || C == '\r' || // Newline.
678 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Chris Lattnerf9c62772008-11-22 02:02:22 +0000679 if (!isLexingRawMode())
680 Diag(BufferPtr, diag::err_unterminated_char);
Chris Lattner0344cc72008-10-12 04:51:35 +0000681 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Chris Lattner4b009652007-07-25 00:24:17 +0000682 return;
683 } else if (C == 0) {
684 NulCharacter = CurPtr-1;
685 }
686 C = getAndAdvanceChar(CurPtr, Result);
687 } while (C != '\'');
688 }
689
Chris Lattnerf9c62772008-11-22 02:02:22 +0000690 if (NulCharacter && !isLexingRawMode())
691 Diag(NulCharacter, diag::null_in_char);
Chris Lattner4b009652007-07-25 00:24:17 +0000692
Chris Lattner4b009652007-07-25 00:24:17 +0000693 // Update the location of token as well as BufferPtr.
Chris Lattner0344cc72008-10-12 04:51:35 +0000694 FormTokenWithChars(Result, CurPtr, tok::char_constant);
Chris Lattner4b009652007-07-25 00:24:17 +0000695}
696
697/// SkipWhitespace - Efficiently skip over a series of whitespace characters.
698/// Update BufferPtr to point to the next non-whitespace character and return.
Chris Lattner867a87b2008-10-12 04:05:48 +0000699///
700/// This method forms a token and returns true if KeepWhitespaceMode is enabled.
701///
702bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr) {
Chris Lattner4b009652007-07-25 00:24:17 +0000703 // Whitespace - Skip it, then return the token after the whitespace.
704 unsigned char Char = *CurPtr; // Skip consequtive spaces efficiently.
705 while (1) {
706 // Skip horizontal whitespace very aggressively.
707 while (isHorizontalWhitespace(Char))
708 Char = *++CurPtr;
709
Daniel Dunbara2208392008-11-25 00:20:22 +0000710 // Otherwise if we have something other than whitespace, we're done.
Chris Lattner4b009652007-07-25 00:24:17 +0000711 if (Char != '\n' && Char != '\r')
712 break;
713
714 if (ParsingPreprocessorDirective) {
715 // End of preprocessor directive line, let LexTokenInternal handle this.
716 BufferPtr = CurPtr;
Chris Lattner867a87b2008-10-12 04:05:48 +0000717 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000718 }
719
720 // ok, but handle newline.
721 // The returned token is at the start of the line.
722 Result.setFlag(Token::StartOfLine);
723 // No leading whitespace seen so far.
724 Result.clearFlag(Token::LeadingSpace);
725 Char = *++CurPtr;
726 }
727
728 // If this isn't immediately after a newline, there is leading space.
729 char PrevChar = CurPtr[-1];
730 if (PrevChar != '\n' && PrevChar != '\r')
731 Result.setFlag(Token::LeadingSpace);
732
Chris Lattner867a87b2008-10-12 04:05:48 +0000733 // If the client wants us to return whitespace, return it now.
734 if (isKeepWhitespaceMode()) {
Chris Lattner0344cc72008-10-12 04:51:35 +0000735 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner867a87b2008-10-12 04:05:48 +0000736 return true;
737 }
738
Chris Lattner4b009652007-07-25 00:24:17 +0000739 BufferPtr = CurPtr;
Chris Lattner867a87b2008-10-12 04:05:48 +0000740 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000741}
742
743// SkipBCPLComment - We have just read the // characters from input. Skip until
744// we find the newline character thats terminate the comment. Then update
Chris Lattnerf03b00c2008-10-12 04:15:42 +0000745/// BufferPtr and return. If we're in KeepCommentMode, this will form the token
746/// and return true.
Chris Lattner4b009652007-07-25 00:24:17 +0000747bool Lexer::SkipBCPLComment(Token &Result, const char *CurPtr) {
748 // If BCPL comments aren't explicitly enabled for this language, emit an
749 // extension warning.
Chris Lattnerf9c62772008-11-22 02:02:22 +0000750 if (!Features.BCPLComment && !isLexingRawMode()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000751 Diag(BufferPtr, diag::ext_bcpl_comment);
752
753 // Mark them enabled so we only emit one warning for this translation
754 // unit.
755 Features.BCPLComment = true;
756 }
757
758 // Scan over the body of the comment. The common case, when scanning, is that
759 // the comment contains normal ascii characters with nothing interesting in
760 // them. As such, optimize for this case with the inner loop.
761 char C;
762 do {
763 C = *CurPtr;
764 // FIXME: Speedup BCPL comment lexing. Just scan for a \n or \r character.
765 // If we find a \n character, scan backwards, checking to see if it's an
766 // escaped newline, like we do for block comments.
767
768 // Skip over characters in the fast loop.
769 while (C != 0 && // Potentially EOF.
770 C != '\\' && // Potentially escaped newline.
771 C != '?' && // Potentially trigraph.
772 C != '\n' && C != '\r') // Newline or DOS-style newline.
773 C = *++CurPtr;
774
775 // If this is a newline, we're done.
776 if (C == '\n' || C == '\r')
777 break; // Found the newline? Break out!
778
779 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
780 // properly decode the character.
781 const char *OldPtr = CurPtr;
782 C = getAndAdvanceChar(CurPtr, Result);
783
784 // If we read multiple characters, and one of those characters was a \r or
785 // \n, then we had an escaped newline within the comment. Emit diagnostic
786 // unless the next line is also a // comment.
787 if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') {
788 for (; OldPtr != CurPtr; ++OldPtr)
789 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
790 // Okay, we found a // comment that ends in a newline, if the next
791 // line is also a // comment, but has spaces, don't emit a diagnostic.
792 if (isspace(C)) {
793 const char *ForwardPtr = CurPtr;
794 while (isspace(*ForwardPtr)) // Skip whitespace.
795 ++ForwardPtr;
796 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
797 break;
798 }
799
Chris Lattnerf9c62772008-11-22 02:02:22 +0000800 if (!isLexingRawMode())
801 Diag(OldPtr-1, diag::ext_multi_line_bcpl_comment);
Chris Lattner4b009652007-07-25 00:24:17 +0000802 break;
803 }
804 }
805
806 if (CurPtr == BufferEnd+1) { --CurPtr; break; }
807 } while (C != '\n' && C != '\r');
808
809 // Found but did not consume the newline.
810
811 // If we are returning comments as tokens, return this comment as a token.
Chris Lattner170adb12008-10-12 03:22:02 +0000812 if (inKeepCommentMode())
Chris Lattner4b009652007-07-25 00:24:17 +0000813 return SaveBCPLComment(Result, CurPtr);
814
815 // If we are inside a preprocessor directive and we see the end of line,
816 // return immediately, so that the lexer can return this as an EOM token.
817 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
818 BufferPtr = CurPtr;
Chris Lattnerf03b00c2008-10-12 04:15:42 +0000819 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000820 }
821
822 // Otherwise, eat the \n character. We don't care if this is a \n\r or
Chris Lattner43d38202008-10-12 00:23:07 +0000823 // \r\n sequence. This is an efficiency hack (because we know the \n can't
Chris Lattner867a87b2008-10-12 04:05:48 +0000824 // contribute to another token), it isn't needed for correctness. Note that
825 // this is ok even in KeepWhitespaceMode, because we would have returned the
826 /// comment above in that mode.
Chris Lattner4b009652007-07-25 00:24:17 +0000827 ++CurPtr;
828
829 // The next returned token is at the start of the line.
830 Result.setFlag(Token::StartOfLine);
831 // No leading whitespace seen so far.
832 Result.clearFlag(Token::LeadingSpace);
833 BufferPtr = CurPtr;
Chris Lattnerf03b00c2008-10-12 04:15:42 +0000834 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000835}
836
837/// SaveBCPLComment - If in save-comment mode, package up this BCPL comment in
838/// an appropriate way and return it.
839bool Lexer::SaveBCPLComment(Token &Result, const char *CurPtr) {
Chris Lattner0344cc72008-10-12 04:51:35 +0000840 // If we're not in a preprocessor directive, just return the // comment
841 // directly.
842 FormTokenWithChars(Result, CurPtr, tok::comment);
Chris Lattner4b009652007-07-25 00:24:17 +0000843
Chris Lattner0344cc72008-10-12 04:51:35 +0000844 if (!ParsingPreprocessorDirective)
845 return true;
846
847 // If this BCPL-style comment is in a macro definition, transmogrify it into
848 // a C-style block comment.
849 std::string Spelling = PP->getSpelling(Result);
850 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not bcpl comment?");
851 Spelling[1] = '*'; // Change prefix to "/*".
852 Spelling += "*/"; // add suffix.
853
854 Result.setKind(tok::comment);
855 Result.setLocation(PP->CreateString(&Spelling[0], Spelling.size(),
856 Result.getLocation()));
857 Result.setLength(Spelling.size());
Chris Lattnerf03b00c2008-10-12 04:15:42 +0000858 return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000859}
860
861/// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
862/// character (either \n or \r) is part of an escaped newline sequence. Issue a
863/// diagnostic if so. We know that the is inside of a block comment.
864static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
865 Lexer *L) {
866 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
867
868 // Back up off the newline.
869 --CurPtr;
870
871 // If this is a two-character newline sequence, skip the other character.
872 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
873 // \n\n or \r\r -> not escaped newline.
874 if (CurPtr[0] == CurPtr[1])
875 return false;
876 // \n\r or \r\n -> skip the newline.
877 --CurPtr;
878 }
879
880 // If we have horizontal whitespace, skip over it. We allow whitespace
881 // between the slash and newline.
882 bool HasSpace = false;
883 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
884 --CurPtr;
885 HasSpace = true;
886 }
887
888 // If we have a slash, we know this is an escaped newline.
889 if (*CurPtr == '\\') {
890 if (CurPtr[-1] != '*') return false;
891 } else {
892 // It isn't a slash, is it the ?? / trigraph?
893 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
894 CurPtr[-3] != '*')
895 return false;
896
897 // This is the trigraph ending the comment. Emit a stern warning!
898 CurPtr -= 2;
899
900 // If no trigraphs are enabled, warn that we ignored this trigraph and
901 // ignore this * character.
902 if (!L->getFeatures().Trigraphs) {
Chris Lattnerf9c62772008-11-22 02:02:22 +0000903 if (!L->isLexingRawMode())
904 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
Chris Lattner4b009652007-07-25 00:24:17 +0000905 return false;
906 }
Chris Lattnerf9c62772008-11-22 02:02:22 +0000907 if (!L->isLexingRawMode())
908 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
Chris Lattner4b009652007-07-25 00:24:17 +0000909 }
910
911 // Warn about having an escaped newline between the */ characters.
Chris Lattnerf9c62772008-11-22 02:02:22 +0000912 if (!L->isLexingRawMode())
913 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
Chris Lattner4b009652007-07-25 00:24:17 +0000914
915 // If there was space between the backslash and newline, warn about it.
Chris Lattnerf9c62772008-11-22 02:02:22 +0000916 if (HasSpace && !L->isLexingRawMode())
917 L->Diag(CurPtr, diag::backslash_newline_space);
Chris Lattner4b009652007-07-25 00:24:17 +0000918
919 return true;
920}
921
922#ifdef __SSE2__
923#include <emmintrin.h>
924#elif __ALTIVEC__
925#include <altivec.h>
926#undef bool
927#endif
928
929/// SkipBlockComment - We have just read the /* characters from input. Read
930/// until we find the */ characters that terminate the comment. Note that we
931/// don't bother decoding trigraphs or escaped newlines in block comments,
932/// because they cannot cause the comment to end. The only thing that can
933/// happen is the comment could end with an escaped newline between the */ end
934/// of comment.
Chris Lattnerf03b00c2008-10-12 04:15:42 +0000935///
936/// If KeepCommentMode is enabled, this forms a token from the comment and
937/// returns true.
Chris Lattner4b009652007-07-25 00:24:17 +0000938bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr) {
939 // Scan one character past where we should, looking for a '/' character. Once
940 // we find it, check to see if it was preceeded by a *. This common
941 // optimization helps people who like to put a lot of * characters in their
942 // comments.
943
944 // The first character we get with newlines and trigraphs skipped to handle
945 // the degenerate /*/ case below correctly if the * has an escaped newline
946 // after it.
947 unsigned CharSize;
948 unsigned char C = getCharAndSize(CurPtr, CharSize);
949 CurPtr += CharSize;
950 if (C == 0 && CurPtr == BufferEnd+1) {
Chris Lattnerf9c62772008-11-22 02:02:22 +0000951 if (!isLexingRawMode())
Chris Lattnere5eca952008-10-12 01:31:51 +0000952 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattnerd66f4542008-10-12 04:19:49 +0000953 --CurPtr;
954
955 // KeepWhitespaceMode should return this broken comment as a token. Since
956 // it isn't a well formed comment, just return it as an 'unknown' token.
957 if (isKeepWhitespaceMode()) {
Chris Lattner0344cc72008-10-12 04:51:35 +0000958 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd66f4542008-10-12 04:19:49 +0000959 return true;
960 }
961
962 BufferPtr = CurPtr;
Chris Lattnerf03b00c2008-10-12 04:15:42 +0000963 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000964 }
965
966 // Check to see if the first character after the '/*' is another /. If so,
967 // then this slash does not end the block comment, it is part of it.
968 if (C == '/')
969 C = *CurPtr++;
970
971 while (1) {
972 // Skip over all non-interesting characters until we find end of buffer or a
973 // (probably ending) '/' character.
974 if (CurPtr + 24 < BufferEnd) {
975 // While not aligned to a 16-byte boundary.
976 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
977 C = *CurPtr++;
978
979 if (C == '/') goto FoundSlash;
980
981#ifdef __SSE2__
982 __m128i Slashes = _mm_set_epi8('/', '/', '/', '/', '/', '/', '/', '/',
983 '/', '/', '/', '/', '/', '/', '/', '/');
984 while (CurPtr+16 <= BufferEnd &&
985 _mm_movemask_epi8(_mm_cmpeq_epi8(*(__m128i*)CurPtr, Slashes)) == 0)
986 CurPtr += 16;
987#elif __ALTIVEC__
988 __vector unsigned char Slashes = {
989 '/', '/', '/', '/', '/', '/', '/', '/',
990 '/', '/', '/', '/', '/', '/', '/', '/'
991 };
992 while (CurPtr+16 <= BufferEnd &&
993 !vec_any_eq(*(vector unsigned char*)CurPtr, Slashes))
994 CurPtr += 16;
995#else
996 // Scan for '/' quickly. Many block comments are very large.
997 while (CurPtr[0] != '/' &&
998 CurPtr[1] != '/' &&
999 CurPtr[2] != '/' &&
1000 CurPtr[3] != '/' &&
1001 CurPtr+4 < BufferEnd) {
1002 CurPtr += 4;
1003 }
1004#endif
1005
1006 // It has to be one of the bytes scanned, increment to it and read one.
1007 C = *CurPtr++;
1008 }
1009
1010 // Loop to scan the remainder.
1011 while (C != '/' && C != '\0')
1012 C = *CurPtr++;
1013
1014 FoundSlash:
1015 if (C == '/') {
1016 if (CurPtr[-2] == '*') // We found the final */. We're done!
1017 break;
1018
1019 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
1020 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
1021 // We found the final */, though it had an escaped newline between the
1022 // * and /. We're done!
1023 break;
1024 }
1025 }
1026 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
1027 // If this is a /* inside of the comment, emit a warning. Don't do this
1028 // if this is a /*/, which will end the comment. This misses cases with
1029 // embedded escaped newlines, but oh well.
Chris Lattnerf9c62772008-11-22 02:02:22 +00001030 if (!isLexingRawMode())
1031 Diag(CurPtr-1, diag::warn_nested_block_comment);
Chris Lattner4b009652007-07-25 00:24:17 +00001032 }
1033 } else if (C == 0 && CurPtr == BufferEnd+1) {
Chris Lattnerf9c62772008-11-22 02:02:22 +00001034 if (!isLexingRawMode())
1035 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner4b009652007-07-25 00:24:17 +00001036 // Note: the user probably forgot a */. We could continue immediately
1037 // after the /*, but this would involve lexing a lot of what really is the
1038 // comment, which surely would confuse the parser.
Chris Lattnerd66f4542008-10-12 04:19:49 +00001039 --CurPtr;
1040
1041 // KeepWhitespaceMode should return this broken comment as a token. Since
1042 // it isn't a well formed comment, just return it as an 'unknown' token.
1043 if (isKeepWhitespaceMode()) {
Chris Lattner0344cc72008-10-12 04:51:35 +00001044 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd66f4542008-10-12 04:19:49 +00001045 return true;
1046 }
1047
1048 BufferPtr = CurPtr;
Chris Lattnerf03b00c2008-10-12 04:15:42 +00001049 return false;
Chris Lattner4b009652007-07-25 00:24:17 +00001050 }
1051 C = *CurPtr++;
1052 }
1053
1054 // If we are returning comments as tokens, return this comment as a token.
Chris Lattner170adb12008-10-12 03:22:02 +00001055 if (inKeepCommentMode()) {
Chris Lattner0344cc72008-10-12 04:51:35 +00001056 FormTokenWithChars(Result, CurPtr, tok::comment);
Chris Lattnerf03b00c2008-10-12 04:15:42 +00001057 return true;
Chris Lattner4b009652007-07-25 00:24:17 +00001058 }
1059
1060 // It is common for the tokens immediately after a /**/ comment to be
1061 // whitespace. Instead of going through the big switch, handle it
Chris Lattner867a87b2008-10-12 04:05:48 +00001062 // efficiently now. This is safe even in KeepWhitespaceMode because we would
1063 // have already returned above with the comment as a token.
Chris Lattner4b009652007-07-25 00:24:17 +00001064 if (isHorizontalWhitespace(*CurPtr)) {
1065 Result.setFlag(Token::LeadingSpace);
1066 SkipWhitespace(Result, CurPtr+1);
Chris Lattnerf03b00c2008-10-12 04:15:42 +00001067 return false;
Chris Lattner4b009652007-07-25 00:24:17 +00001068 }
1069
1070 // Otherwise, just return so that the next character will be lexed as a token.
1071 BufferPtr = CurPtr;
1072 Result.setFlag(Token::LeadingSpace);
Chris Lattnerf03b00c2008-10-12 04:15:42 +00001073 return false;
Chris Lattner4b009652007-07-25 00:24:17 +00001074}
1075
1076//===----------------------------------------------------------------------===//
1077// Primary Lexing Entry Points
1078//===----------------------------------------------------------------------===//
1079
Chris Lattner4b009652007-07-25 00:24:17 +00001080/// ReadToEndOfLine - Read the rest of the current preprocessor line as an
1081/// uninterpreted string. This switches the lexer out of directive mode.
1082std::string Lexer::ReadToEndOfLine() {
1083 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
1084 "Must be in a preprocessing directive!");
1085 std::string Result;
1086 Token Tmp;
1087
1088 // CurPtr - Cache BufferPtr in an automatic variable.
1089 const char *CurPtr = BufferPtr;
1090 while (1) {
1091 char Char = getAndAdvanceChar(CurPtr, Tmp);
1092 switch (Char) {
1093 default:
1094 Result += Char;
1095 break;
1096 case 0: // Null.
1097 // Found end of file?
1098 if (CurPtr-1 != BufferEnd) {
1099 // Nope, normal character, continue.
1100 Result += Char;
1101 break;
1102 }
1103 // FALL THROUGH.
1104 case '\r':
1105 case '\n':
1106 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
1107 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
1108 BufferPtr = CurPtr-1;
1109
1110 // Next, lex the character, which should handle the EOM transition.
1111 Lex(Tmp);
Chris Lattnercb8e41c2007-10-09 18:02:16 +00001112 assert(Tmp.is(tok::eom) && "Unexpected token!");
Chris Lattner4b009652007-07-25 00:24:17 +00001113
1114 // Finally, we're done, return the string we found.
1115 return Result;
1116 }
1117 }
1118}
1119
1120/// LexEndOfFile - CurPtr points to the end of this file. Handle this
1121/// condition, reporting diagnostics and handling other edge cases as required.
1122/// This returns true if Result contains a token, false if PP.Lex should be
1123/// called again.
1124bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
1125 // If we hit the end of the file while parsing a preprocessor directive,
1126 // end the preprocessor directive first. The next token returned will
1127 // then be the end of file.
1128 if (ParsingPreprocessorDirective) {
1129 // Done parsing the "line".
1130 ParsingPreprocessorDirective = false;
Chris Lattner4b009652007-07-25 00:24:17 +00001131 // Update the location of token as well as BufferPtr.
Chris Lattner0344cc72008-10-12 04:51:35 +00001132 FormTokenWithChars(Result, CurPtr, tok::eom);
Chris Lattner4b009652007-07-25 00:24:17 +00001133
1134 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattner1c1bed12008-10-12 03:27:19 +00001135 SetCommentRetentionState(PP->getCommentRetentionState());
Chris Lattner4b009652007-07-25 00:24:17 +00001136 return true; // Have a token.
1137 }
1138
1139 // If we are in raw mode, return this event as an EOF token. Let the caller
1140 // that put us in raw mode handle the event.
Chris Lattnerf9c62772008-11-22 02:02:22 +00001141 if (isLexingRawMode()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001142 Result.startToken();
1143 BufferPtr = BufferEnd;
Chris Lattner0344cc72008-10-12 04:51:35 +00001144 FormTokenWithChars(Result, BufferEnd, tok::eof);
Chris Lattner4b009652007-07-25 00:24:17 +00001145 return true;
1146 }
1147
1148 // Otherwise, issue diagnostics for unterminated #if and missing newline.
1149
1150 // If we are in a #if directive, emit an error.
1151 while (!ConditionalStack.empty()) {
Chris Lattner8ef6cdc2008-11-22 06:22:39 +00001152 PP->Diag(ConditionalStack.back().IfLoc,
1153 diag::err_pp_unterminated_conditional);
Chris Lattner4b009652007-07-25 00:24:17 +00001154 ConditionalStack.pop_back();
1155 }
1156
Chris Lattner5c337fa2008-04-12 05:54:25 +00001157 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
1158 // a pedwarn.
1159 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r'))
Chris Lattner4b009652007-07-25 00:24:17 +00001160 Diag(BufferEnd, diag::ext_no_newline_eof);
1161
1162 BufferPtr = CurPtr;
1163
1164 // Finally, let the preprocessor handle this.
Chris Lattner342dccb2007-10-17 20:41:00 +00001165 return PP->HandleEndOfFile(Result);
Chris Lattner4b009652007-07-25 00:24:17 +00001166}
1167
1168/// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
1169/// the specified lexer will return a tok::l_paren token, 0 if it is something
1170/// else and 2 if there are no more tokens in the buffer controlled by the
1171/// lexer.
1172unsigned Lexer::isNextPPTokenLParen() {
1173 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
1174
1175 // Switch to 'skipping' mode. This will ensure that we can lex a token
1176 // without emitting diagnostics, disables macro expansion, and will cause EOF
1177 // to return an EOF token instead of popping the include stack.
1178 LexingRawMode = true;
1179
1180 // Save state that can be changed while lexing so that we can restore it.
1181 const char *TmpBufferPtr = BufferPtr;
1182
1183 Token Tok;
1184 Tok.startToken();
1185 LexTokenInternal(Tok);
1186
1187 // Restore state that may have changed.
1188 BufferPtr = TmpBufferPtr;
1189
1190 // Restore the lexer back to non-skipping mode.
1191 LexingRawMode = false;
1192
Chris Lattnercb8e41c2007-10-09 18:02:16 +00001193 if (Tok.is(tok::eof))
Chris Lattner4b009652007-07-25 00:24:17 +00001194 return 2;
Chris Lattnercb8e41c2007-10-09 18:02:16 +00001195 return Tok.is(tok::l_paren);
Chris Lattner4b009652007-07-25 00:24:17 +00001196}
1197
1198
1199/// LexTokenInternal - This implements a simple C family lexer. It is an
1200/// extremely performance critical piece of code. This assumes that the buffer
1201/// has a null character at the end of the file. Return true if an error
1202/// occurred and compilation should terminate, false if normal. This returns a
1203/// preprocessing token, not a normal token, as such, it is an internal
1204/// interface. It assumes that the Flags of result have been cleared before
1205/// calling this.
1206void Lexer::LexTokenInternal(Token &Result) {
1207LexNextToken:
1208 // New token, can't need cleaning yet.
1209 Result.clearFlag(Token::NeedsCleaning);
1210 Result.setIdentifierInfo(0);
1211
1212 // CurPtr - Cache BufferPtr in an automatic variable.
1213 const char *CurPtr = BufferPtr;
1214
1215 // Small amounts of horizontal whitespace is very common between tokens.
1216 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
1217 ++CurPtr;
1218 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
1219 ++CurPtr;
Chris Lattner867a87b2008-10-12 04:05:48 +00001220
1221 // If we are keeping whitespace and other tokens, just return what we just
1222 // skipped. The next lexer invocation will return the token after the
1223 // whitespace.
1224 if (isKeepWhitespaceMode()) {
Chris Lattner0344cc72008-10-12 04:51:35 +00001225 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner867a87b2008-10-12 04:05:48 +00001226 return;
1227 }
1228
Chris Lattner4b009652007-07-25 00:24:17 +00001229 BufferPtr = CurPtr;
1230 Result.setFlag(Token::LeadingSpace);
1231 }
1232
1233 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
1234
1235 // Read a character, advancing over it.
1236 char Char = getAndAdvanceChar(CurPtr, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001237 tok::TokenKind Kind;
1238
Chris Lattner4b009652007-07-25 00:24:17 +00001239 switch (Char) {
1240 case 0: // Null.
1241 // Found end of file?
1242 if (CurPtr-1 == BufferEnd) {
1243 // Read the PP instance variable into an automatic variable, because
1244 // LexEndOfFile will often delete 'this'.
Chris Lattner342dccb2007-10-17 20:41:00 +00001245 Preprocessor *PPCache = PP;
Chris Lattner4b009652007-07-25 00:24:17 +00001246 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
1247 return; // Got a token to return.
Chris Lattner342dccb2007-10-17 20:41:00 +00001248 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
1249 return PPCache->Lex(Result);
Chris Lattner4b009652007-07-25 00:24:17 +00001250 }
1251
Chris Lattnerf9c62772008-11-22 02:02:22 +00001252 if (!isLexingRawMode())
1253 Diag(CurPtr-1, diag::null_in_file);
Chris Lattner4b009652007-07-25 00:24:17 +00001254 Result.setFlag(Token::LeadingSpace);
Chris Lattner867a87b2008-10-12 04:05:48 +00001255 if (SkipWhitespace(Result, CurPtr))
1256 return; // KeepWhitespaceMode
1257
Chris Lattner4b009652007-07-25 00:24:17 +00001258 goto LexNextToken; // GCC isn't tail call eliminating.
1259 case '\n':
1260 case '\r':
1261 // If we are inside a preprocessor directive and we see the end of line,
1262 // we know we are done with the directive, so return an EOM token.
1263 if (ParsingPreprocessorDirective) {
1264 // Done parsing the "line".
1265 ParsingPreprocessorDirective = false;
1266
1267 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattner1c1bed12008-10-12 03:27:19 +00001268 SetCommentRetentionState(PP->getCommentRetentionState());
Chris Lattner4b009652007-07-25 00:24:17 +00001269
1270 // Since we consumed a newline, we are back at the start of a line.
1271 IsAtStartOfLine = true;
1272
Chris Lattner0344cc72008-10-12 04:51:35 +00001273 Kind = tok::eom;
Chris Lattner4b009652007-07-25 00:24:17 +00001274 break;
1275 }
1276 // The returned token is at the start of the line.
1277 Result.setFlag(Token::StartOfLine);
1278 // No leading whitespace seen so far.
1279 Result.clearFlag(Token::LeadingSpace);
Chris Lattner867a87b2008-10-12 04:05:48 +00001280
1281 if (SkipWhitespace(Result, CurPtr))
1282 return; // KeepWhitespaceMode
Chris Lattner4b009652007-07-25 00:24:17 +00001283 goto LexNextToken; // GCC isn't tail call eliminating.
1284 case ' ':
1285 case '\t':
1286 case '\f':
1287 case '\v':
1288 SkipHorizontalWhitespace:
1289 Result.setFlag(Token::LeadingSpace);
Chris Lattner867a87b2008-10-12 04:05:48 +00001290 if (SkipWhitespace(Result, CurPtr))
1291 return; // KeepWhitespaceMode
Chris Lattner4b009652007-07-25 00:24:17 +00001292
1293 SkipIgnoredUnits:
1294 CurPtr = BufferPtr;
1295
1296 // If the next token is obviously a // or /* */ comment, skip it efficiently
1297 // too (without going through the big switch stmt).
Chris Lattner170adb12008-10-12 03:22:02 +00001298 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001299 SkipBCPLComment(Result, CurPtr+2);
1300 goto SkipIgnoredUnits;
Chris Lattner170adb12008-10-12 03:22:02 +00001301 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001302 SkipBlockComment(Result, CurPtr+2);
1303 goto SkipIgnoredUnits;
1304 } else if (isHorizontalWhitespace(*CurPtr)) {
1305 goto SkipHorizontalWhitespace;
1306 }
1307 goto LexNextToken; // GCC isn't tail call eliminating.
1308
Chris Lattner0ffadcc2008-01-03 17:58:54 +00001309 // C99 6.4.4.1: Integer Constants.
1310 // C99 6.4.4.2: Floating Constants.
1311 case '0': case '1': case '2': case '3': case '4':
1312 case '5': case '6': case '7': case '8': case '9':
1313 // Notify MIOpt that we read a non-whitespace/non-comment token.
1314 MIOpt.ReadToken();
1315 return LexNumericConstant(Result, CurPtr);
1316
1317 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
Chris Lattner4b009652007-07-25 00:24:17 +00001318 // Notify MIOpt that we read a non-whitespace/non-comment token.
1319 MIOpt.ReadToken();
1320 Char = getCharAndSize(CurPtr, SizeTmp);
1321
1322 // Wide string literal.
1323 if (Char == '"')
1324 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
1325 true);
1326
1327 // Wide character constant.
1328 if (Char == '\'')
1329 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
1330 // FALL THROUGH, treating L like the start of an identifier.
1331
1332 // C99 6.4.2: Identifiers.
1333 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
1334 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
1335 case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U':
1336 case 'V': case 'W': case 'X': case 'Y': case 'Z':
1337 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
1338 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
1339 case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u':
1340 case 'v': case 'w': case 'x': case 'y': case 'z':
1341 case '_':
1342 // Notify MIOpt that we read a non-whitespace/non-comment token.
1343 MIOpt.ReadToken();
1344 return LexIdentifier(Result, CurPtr);
Chris Lattner0ffadcc2008-01-03 17:58:54 +00001345
1346 case '$': // $ in identifiers.
1347 if (Features.DollarIdents) {
Chris Lattnerf9c62772008-11-22 02:02:22 +00001348 if (!isLexingRawMode())
1349 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
Chris Lattner0ffadcc2008-01-03 17:58:54 +00001350 // Notify MIOpt that we read a non-whitespace/non-comment token.
1351 MIOpt.ReadToken();
1352 return LexIdentifier(Result, CurPtr);
1353 }
Chris Lattner4b009652007-07-25 00:24:17 +00001354
Chris Lattner0344cc72008-10-12 04:51:35 +00001355 Kind = tok::unknown;
Chris Lattner0ffadcc2008-01-03 17:58:54 +00001356 break;
Chris Lattner4b009652007-07-25 00:24:17 +00001357
1358 // C99 6.4.4: Character Constants.
1359 case '\'':
1360 // Notify MIOpt that we read a non-whitespace/non-comment token.
1361 MIOpt.ReadToken();
1362 return LexCharConstant(Result, CurPtr);
1363
1364 // C99 6.4.5: String Literals.
1365 case '"':
1366 // Notify MIOpt that we read a non-whitespace/non-comment token.
1367 MIOpt.ReadToken();
1368 return LexStringLiteral(Result, CurPtr, false);
1369
1370 // C99 6.4.6: Punctuators.
1371 case '?':
Chris Lattner0344cc72008-10-12 04:51:35 +00001372 Kind = tok::question;
Chris Lattner4b009652007-07-25 00:24:17 +00001373 break;
1374 case '[':
Chris Lattner0344cc72008-10-12 04:51:35 +00001375 Kind = tok::l_square;
Chris Lattner4b009652007-07-25 00:24:17 +00001376 break;
1377 case ']':
Chris Lattner0344cc72008-10-12 04:51:35 +00001378 Kind = tok::r_square;
Chris Lattner4b009652007-07-25 00:24:17 +00001379 break;
1380 case '(':
Chris Lattner0344cc72008-10-12 04:51:35 +00001381 Kind = tok::l_paren;
Chris Lattner4b009652007-07-25 00:24:17 +00001382 break;
1383 case ')':
Chris Lattner0344cc72008-10-12 04:51:35 +00001384 Kind = tok::r_paren;
Chris Lattner4b009652007-07-25 00:24:17 +00001385 break;
1386 case '{':
Chris Lattner0344cc72008-10-12 04:51:35 +00001387 Kind = tok::l_brace;
Chris Lattner4b009652007-07-25 00:24:17 +00001388 break;
1389 case '}':
Chris Lattner0344cc72008-10-12 04:51:35 +00001390 Kind = tok::r_brace;
Chris Lattner4b009652007-07-25 00:24:17 +00001391 break;
1392 case '.':
1393 Char = getCharAndSize(CurPtr, SizeTmp);
1394 if (Char >= '0' && Char <= '9') {
1395 // Notify MIOpt that we read a non-whitespace/non-comment token.
1396 MIOpt.ReadToken();
1397
1398 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
1399 } else if (Features.CPlusPlus && Char == '*') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001400 Kind = tok::periodstar;
Chris Lattner4b009652007-07-25 00:24:17 +00001401 CurPtr += SizeTmp;
1402 } else if (Char == '.' &&
1403 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001404 Kind = tok::ellipsis;
Chris Lattner4b009652007-07-25 00:24:17 +00001405 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1406 SizeTmp2, Result);
1407 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001408 Kind = tok::period;
Chris Lattner4b009652007-07-25 00:24:17 +00001409 }
1410 break;
1411 case '&':
1412 Char = getCharAndSize(CurPtr, SizeTmp);
1413 if (Char == '&') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001414 Kind = tok::ampamp;
Chris Lattner4b009652007-07-25 00:24:17 +00001415 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1416 } else if (Char == '=') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001417 Kind = tok::ampequal;
Chris Lattner4b009652007-07-25 00:24:17 +00001418 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1419 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001420 Kind = tok::amp;
Chris Lattner4b009652007-07-25 00:24:17 +00001421 }
1422 break;
1423 case '*':
1424 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001425 Kind = tok::starequal;
Chris Lattner4b009652007-07-25 00:24:17 +00001426 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1427 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001428 Kind = tok::star;
Chris Lattner4b009652007-07-25 00:24:17 +00001429 }
1430 break;
1431 case '+':
1432 Char = getCharAndSize(CurPtr, SizeTmp);
1433 if (Char == '+') {
Chris Lattner4b009652007-07-25 00:24:17 +00001434 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001435 Kind = tok::plusplus;
Chris Lattner4b009652007-07-25 00:24:17 +00001436 } else if (Char == '=') {
Chris Lattner4b009652007-07-25 00:24:17 +00001437 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001438 Kind = tok::plusequal;
Chris Lattner4b009652007-07-25 00:24:17 +00001439 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001440 Kind = tok::plus;
Chris Lattner4b009652007-07-25 00:24:17 +00001441 }
1442 break;
1443 case '-':
1444 Char = getCharAndSize(CurPtr, SizeTmp);
Chris Lattner0344cc72008-10-12 04:51:35 +00001445 if (Char == '-') { // --
Chris Lattner4b009652007-07-25 00:24:17 +00001446 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001447 Kind = tok::minusminus;
Chris Lattner4b009652007-07-25 00:24:17 +00001448 } else if (Char == '>' && Features.CPlusPlus &&
Chris Lattner0344cc72008-10-12 04:51:35 +00001449 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
Chris Lattner4b009652007-07-25 00:24:17 +00001450 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1451 SizeTmp2, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001452 Kind = tok::arrowstar;
1453 } else if (Char == '>') { // ->
Chris Lattner4b009652007-07-25 00:24:17 +00001454 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001455 Kind = tok::arrow;
1456 } else if (Char == '=') { // -=
Chris Lattner4b009652007-07-25 00:24:17 +00001457 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001458 Kind = tok::minusequal;
Chris Lattner4b009652007-07-25 00:24:17 +00001459 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001460 Kind = tok::minus;
Chris Lattner4b009652007-07-25 00:24:17 +00001461 }
1462 break;
1463 case '~':
Chris Lattner0344cc72008-10-12 04:51:35 +00001464 Kind = tok::tilde;
Chris Lattner4b009652007-07-25 00:24:17 +00001465 break;
1466 case '!':
1467 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001468 Kind = tok::exclaimequal;
Chris Lattner4b009652007-07-25 00:24:17 +00001469 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1470 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001471 Kind = tok::exclaim;
Chris Lattner4b009652007-07-25 00:24:17 +00001472 }
1473 break;
1474 case '/':
1475 // 6.4.9: Comments
1476 Char = getCharAndSize(CurPtr, SizeTmp);
1477 if (Char == '/') { // BCPL comment.
Chris Lattnerf03b00c2008-10-12 04:15:42 +00001478 if (SkipBCPLComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
1479 return; // KeepCommentMode
1480
1481 // It is common for the tokens immediately after a // comment to be
1482 // whitespace (indentation for the next line). Instead of going through
1483 // the big switch, handle it efficiently now.
1484 goto SkipIgnoredUnits;
Chris Lattner4b009652007-07-25 00:24:17 +00001485 } else if (Char == '*') { // /**/ comment.
1486 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattnerf03b00c2008-10-12 04:15:42 +00001487 return; // KeepCommentMode
1488 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattner4b009652007-07-25 00:24:17 +00001489 } else if (Char == '=') {
Chris Lattner4b009652007-07-25 00:24:17 +00001490 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001491 Kind = tok::slashequal;
Chris Lattner4b009652007-07-25 00:24:17 +00001492 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001493 Kind = tok::slash;
Chris Lattner4b009652007-07-25 00:24:17 +00001494 }
1495 break;
1496 case '%':
1497 Char = getCharAndSize(CurPtr, SizeTmp);
1498 if (Char == '=') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001499 Kind = tok::percentequal;
Chris Lattner4b009652007-07-25 00:24:17 +00001500 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1501 } else if (Features.Digraphs && Char == '>') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001502 Kind = tok::r_brace; // '%>' -> '}'
Chris Lattner4b009652007-07-25 00:24:17 +00001503 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1504 } else if (Features.Digraphs && Char == ':') {
1505 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1506 Char = getCharAndSize(CurPtr, SizeTmp);
1507 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001508 Kind = tok::hashhash; // '%:%:' -> '##'
Chris Lattner4b009652007-07-25 00:24:17 +00001509 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1510 SizeTmp2, Result);
1511 } else if (Char == '@' && Features.Microsoft) { // %:@ -> #@ -> Charize
Chris Lattner4b009652007-07-25 00:24:17 +00001512 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerf9c62772008-11-22 02:02:22 +00001513 if (!isLexingRawMode())
1514 Diag(BufferPtr, diag::charize_microsoft_ext);
Chris Lattner0344cc72008-10-12 04:51:35 +00001515 Kind = tok::hashat;
Chris Lattner4b009652007-07-25 00:24:17 +00001516 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001517 Kind = tok::hash; // '%:' -> '#'
Chris Lattner4b009652007-07-25 00:24:17 +00001518
1519 // We parsed a # character. If this occurs at the start of the line,
1520 // it's actually the start of a preprocessing directive. Callback to
1521 // the preprocessor to handle it.
1522 // FIXME: -fpreprocessed mode??
1523 if (Result.isAtStartOfLine() && !LexingRawMode) {
1524 BufferPtr = CurPtr;
Chris Lattner342dccb2007-10-17 20:41:00 +00001525 PP->HandleDirective(Result);
Chris Lattner4b009652007-07-25 00:24:17 +00001526
1527 // As an optimization, if the preprocessor didn't switch lexers, tail
1528 // recurse.
Chris Lattner342dccb2007-10-17 20:41:00 +00001529 if (PP->isCurrentLexer(this)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001530 // Start a new token. If this is a #include or something, the PP may
1531 // want us starting at the beginning of the line again. If so, set
1532 // the StartOfLine flag.
1533 if (IsAtStartOfLine) {
1534 Result.setFlag(Token::StartOfLine);
1535 IsAtStartOfLine = false;
1536 }
1537 goto LexNextToken; // GCC isn't tail call eliminating.
1538 }
1539
Chris Lattner342dccb2007-10-17 20:41:00 +00001540 return PP->Lex(Result);
Chris Lattner4b009652007-07-25 00:24:17 +00001541 }
1542 }
1543 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001544 Kind = tok::percent;
Chris Lattner4b009652007-07-25 00:24:17 +00001545 }
1546 break;
1547 case '<':
1548 Char = getCharAndSize(CurPtr, SizeTmp);
1549 if (ParsingFilename) {
1550 return LexAngledStringLiteral(Result, CurPtr+SizeTmp);
1551 } else if (Char == '<' &&
1552 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '=') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001553 Kind = tok::lesslessequal;
Chris Lattner4b009652007-07-25 00:24:17 +00001554 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1555 SizeTmp2, Result);
1556 } else if (Char == '<') {
Chris Lattner4b009652007-07-25 00:24:17 +00001557 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001558 Kind = tok::lessless;
Chris Lattner4b009652007-07-25 00:24:17 +00001559 } else if (Char == '=') {
Chris Lattner4b009652007-07-25 00:24:17 +00001560 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001561 Kind = tok::lessequal;
1562 } else if (Features.Digraphs && Char == ':') { // '<:' -> '['
Chris Lattner4b009652007-07-25 00:24:17 +00001563 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001564 Kind = tok::l_square;
1565 } else if (Features.Digraphs && Char == '%') { // '<%' -> '{'
Chris Lattner4b009652007-07-25 00:24:17 +00001566 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001567 Kind = tok::l_brace;
Chris Lattner4b009652007-07-25 00:24:17 +00001568 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001569 Kind = tok::less;
Chris Lattner4b009652007-07-25 00:24:17 +00001570 }
1571 break;
1572 case '>':
1573 Char = getCharAndSize(CurPtr, SizeTmp);
1574 if (Char == '=') {
Chris Lattner4b009652007-07-25 00:24:17 +00001575 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001576 Kind = tok::greaterequal;
Chris Lattner4b009652007-07-25 00:24:17 +00001577 } else if (Char == '>' &&
1578 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '=') {
Chris Lattner4b009652007-07-25 00:24:17 +00001579 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1580 SizeTmp2, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001581 Kind = tok::greatergreaterequal;
Chris Lattner4b009652007-07-25 00:24:17 +00001582 } else if (Char == '>') {
Chris Lattner4b009652007-07-25 00:24:17 +00001583 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001584 Kind = tok::greatergreater;
Chris Lattner4b009652007-07-25 00:24:17 +00001585 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001586 Kind = tok::greater;
Chris Lattner4b009652007-07-25 00:24:17 +00001587 }
1588 break;
1589 case '^':
1590 Char = getCharAndSize(CurPtr, SizeTmp);
1591 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::caretequal;
Chris Lattner4b009652007-07-25 00:24:17 +00001594 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001595 Kind = tok::caret;
Chris Lattner4b009652007-07-25 00:24:17 +00001596 }
1597 break;
1598 case '|':
1599 Char = getCharAndSize(CurPtr, SizeTmp);
1600 if (Char == '=') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001601 Kind = tok::pipeequal;
Chris Lattner4b009652007-07-25 00:24:17 +00001602 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1603 } else if (Char == '|') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001604 Kind = tok::pipepipe;
Chris Lattner4b009652007-07-25 00:24:17 +00001605 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1606 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001607 Kind = tok::pipe;
Chris Lattner4b009652007-07-25 00:24:17 +00001608 }
1609 break;
1610 case ':':
1611 Char = getCharAndSize(CurPtr, SizeTmp);
1612 if (Features.Digraphs && Char == '>') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001613 Kind = tok::r_square; // ':>' -> ']'
Chris Lattner4b009652007-07-25 00:24:17 +00001614 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1615 } else if (Features.CPlusPlus && Char == ':') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001616 Kind = tok::coloncolon;
Chris Lattner4b009652007-07-25 00:24:17 +00001617 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1618 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001619 Kind = tok::colon;
Chris Lattner4b009652007-07-25 00:24:17 +00001620 }
1621 break;
1622 case ';':
Chris Lattner0344cc72008-10-12 04:51:35 +00001623 Kind = tok::semi;
Chris Lattner4b009652007-07-25 00:24:17 +00001624 break;
1625 case '=':
1626 Char = getCharAndSize(CurPtr, SizeTmp);
1627 if (Char == '=') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001628 Kind = tok::equalequal;
Chris Lattner4b009652007-07-25 00:24:17 +00001629 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1630 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001631 Kind = tok::equal;
Chris Lattner4b009652007-07-25 00:24:17 +00001632 }
1633 break;
1634 case ',':
Chris Lattner0344cc72008-10-12 04:51:35 +00001635 Kind = tok::comma;
Chris Lattner4b009652007-07-25 00:24:17 +00001636 break;
1637 case '#':
1638 Char = getCharAndSize(CurPtr, SizeTmp);
1639 if (Char == '#') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001640 Kind = tok::hashhash;
Chris Lattner4b009652007-07-25 00:24:17 +00001641 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1642 } else if (Char == '@' && Features.Microsoft) { // #@ -> Charize
Chris Lattner0344cc72008-10-12 04:51:35 +00001643 Kind = tok::hashat;
Chris Lattnerf9c62772008-11-22 02:02:22 +00001644 if (!isLexingRawMode())
1645 Diag(BufferPtr, diag::charize_microsoft_ext);
Chris Lattner4b009652007-07-25 00:24:17 +00001646 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1647 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001648 Kind = tok::hash;
Chris Lattner4b009652007-07-25 00:24:17 +00001649 // We parsed a # character. If this occurs at the start of the line,
1650 // it's actually the start of a preprocessing directive. Callback to
1651 // the preprocessor to handle it.
1652 // FIXME: -fpreprocessed mode??
1653 if (Result.isAtStartOfLine() && !LexingRawMode) {
1654 BufferPtr = CurPtr;
Chris Lattner342dccb2007-10-17 20:41:00 +00001655 PP->HandleDirective(Result);
Chris Lattner4b009652007-07-25 00:24:17 +00001656
1657 // As an optimization, if the preprocessor didn't switch lexers, tail
1658 // recurse.
Chris Lattner342dccb2007-10-17 20:41:00 +00001659 if (PP->isCurrentLexer(this)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001660 // Start a new token. If this is a #include or something, the PP may
1661 // want us starting at the beginning of the line again. If so, set
1662 // the StartOfLine flag.
1663 if (IsAtStartOfLine) {
1664 Result.setFlag(Token::StartOfLine);
1665 IsAtStartOfLine = false;
1666 }
1667 goto LexNextToken; // GCC isn't tail call eliminating.
1668 }
Chris Lattner342dccb2007-10-17 20:41:00 +00001669 return PP->Lex(Result);
Chris Lattner4b009652007-07-25 00:24:17 +00001670 }
1671 }
1672 break;
1673
Chris Lattner0ffadcc2008-01-03 17:58:54 +00001674 case '@':
1675 // Objective C support.
1676 if (CurPtr[-1] == '@' && Features.ObjC1)
Chris Lattner0344cc72008-10-12 04:51:35 +00001677 Kind = tok::at;
Chris Lattner0ffadcc2008-01-03 17:58:54 +00001678 else
Chris Lattner0344cc72008-10-12 04:51:35 +00001679 Kind = tok::unknown;
Chris Lattner0ffadcc2008-01-03 17:58:54 +00001680 break;
1681
Chris Lattner4b009652007-07-25 00:24:17 +00001682 case '\\':
1683 // FIXME: UCN's.
1684 // FALL THROUGH.
1685 default:
Chris Lattner0344cc72008-10-12 04:51:35 +00001686 Kind = tok::unknown;
Chris Lattner4b009652007-07-25 00:24:17 +00001687 break;
1688 }
1689
1690 // Notify MIOpt that we read a non-whitespace/non-comment token.
1691 MIOpt.ReadToken();
1692
1693 // Update the location of token as well as BufferPtr.
Chris Lattner0344cc72008-10-12 04:51:35 +00001694 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner4b009652007-07-25 00:24:17 +00001695}