blob: cef848f073e404d35b2c96cc08ffccb32ab1e293 [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 {
Chris Lattnercb8e41c2007-10-09 18:02:16 +000044 return is(tok::identifier) &&
45 getIdentifierInfo()->getObjCKeywordID() == objcKey;
Chris Lattneraa9bdf12007-10-07 08:47:24 +000046}
47
48/// getObjCKeywordID - Return the ObjC keyword kind.
49tok::ObjCKeywordKind Token::getObjCKeywordID() const {
50 IdentifierInfo *specId = getIdentifierInfo();
51 return specId ? specId->getObjCKeywordID() : tok::objc_not_keyword;
52}
53
Chris Lattner7208a4b2007-12-13 01:59:49 +000054
Chris Lattneraa9bdf12007-10-07 08:47:24 +000055//===----------------------------------------------------------------------===//
56// Lexer Class Implementation
57//===----------------------------------------------------------------------===//
58
59
Chris Lattner342dccb2007-10-17 20:41:00 +000060/// Lexer constructor - Create a new lexer object for the specified buffer
61/// with the specified preprocessor managing the lexing process. This lexer
62/// assumes that the associated file buffer and Preprocessor objects will
63/// outlive it, so it doesn't take ownership of either of them.
Chris Lattner4b009652007-07-25 00:24:17 +000064Lexer::Lexer(SourceLocation fileloc, Preprocessor &pp,
65 const char *BufStart, const char *BufEnd)
Ted Kremenek56758d22008-11-19 21:57:25 +000066 : PreprocessorLexer(&pp, fileloc), FileLoc(fileloc),
67 Features(pp.getLangOptions()) {
Chris Lattner4b009652007-07-25 00:24:17 +000068
Chris Lattner342dccb2007-10-17 20:41:00 +000069 SourceManager &SourceMgr = PP->getSourceManager();
Chris Lattner4b009652007-07-25 00:24:17 +000070 unsigned InputFileID = SourceMgr.getPhysicalLoc(FileLoc).getFileID();
71 const llvm::MemoryBuffer *InputFile = SourceMgr.getBuffer(InputFileID);
72
73 Is_PragmaLexer = false;
Chris Lattner4b009652007-07-25 00:24:17 +000074 InitCharacterInfo();
75
76 // BufferStart must always be InputFile->getBufferStart().
77 BufferStart = InputFile->getBufferStart();
78
79 // BufferPtr and BufferEnd can start out somewhere inside the current buffer.
80 // If unspecified, they starts at the start/end of the buffer.
81 BufferPtr = BufStart ? BufStart : BufferStart;
82 BufferEnd = BufEnd ? BufEnd : InputFile->getBufferEnd();
83
84 assert(BufferEnd[0] == 0 &&
85 "We assume that the input buffer has a null character at the end"
86 " to simplify lexing!");
87
88 // Start of the file is a start of line.
89 IsAtStartOfLine = true;
90
91 // We are not after parsing a #.
92 ParsingPreprocessorDirective = false;
93
94 // We are not after parsing #include.
95 ParsingFilename = false;
96
97 // We are not in raw mode. Raw mode disables diagnostics and interpretation
98 // of tokens (e.g. identifiers, thus disabling macro expansion). It is used
99 // to quickly lex the tokens of the buffer, e.g. when handling a "#if 0" block
100 // or otherwise skipping over tokens.
101 LexingRawMode = false;
102
Chris Lattner867a87b2008-10-12 04:05:48 +0000103 // Default to keeping comments if the preprocessor wants them.
104 ExtendedTokenMode = 0;
Chris Lattner1c1bed12008-10-12 03:27:19 +0000105 SetCommentRetentionState(PP->getCommentRetentionState());
Chris Lattner4b009652007-07-25 00:24:17 +0000106}
107
Chris Lattner342dccb2007-10-17 20:41:00 +0000108/// Lexer constructor - Create a new raw lexer object. This object is only
Chris Lattner0b5892e2008-10-12 01:15:46 +0000109/// suitable for calls to 'LexRawToken'. This lexer assumes that the text
110/// range will outlive it, so it doesn't take ownership of it.
Chris Lattner342dccb2007-10-17 20:41:00 +0000111Lexer::Lexer(SourceLocation fileloc, const LangOptions &features,
Chris Lattner0b5892e2008-10-12 01:15:46 +0000112 const char *BufStart, const char *BufEnd,
113 const llvm::MemoryBuffer *FromFile)
Ted Kremenek56758d22008-11-19 21:57:25 +0000114 : PreprocessorLexer(), FileLoc(fileloc),
115 Features(features) {
116
Chris Lattner342dccb2007-10-17 20:41:00 +0000117 Is_PragmaLexer = false;
118 InitCharacterInfo();
119
Chris Lattner88ad2ac2008-10-12 01:23:27 +0000120 // If a MemoryBuffer was specified, use its start as BufferStart. This affects
121 // the source location objects produced by this lexer.
Chris Lattner0b5892e2008-10-12 01:15:46 +0000122 BufferStart = FromFile ? FromFile->getBufferStart() : BufStart;
Chris Lattner342dccb2007-10-17 20:41:00 +0000123 BufferPtr = BufStart;
124 BufferEnd = BufEnd;
125
126 assert(BufferEnd[0] == 0 &&
127 "We assume that the input buffer has a null character at the end"
128 " to simplify lexing!");
129
130 // Start of the file is a start of line.
131 IsAtStartOfLine = true;
132
133 // We are not after parsing a #.
134 ParsingPreprocessorDirective = false;
135
136 // We are not after parsing #include.
137 ParsingFilename = false;
138
139 // We *are* in raw mode.
140 LexingRawMode = true;
141
Chris Lattnercb8014e2008-10-12 01:34:51 +0000142 // Default to not keeping comments in raw mode.
Chris Lattner867a87b2008-10-12 04:05:48 +0000143 ExtendedTokenMode = 0;
Chris Lattner342dccb2007-10-17 20:41:00 +0000144}
145
146
Chris Lattner4b009652007-07-25 00:24:17 +0000147/// Stringify - Convert the specified string into a C string, with surrounding
148/// ""'s, and with escaped \ and " characters.
149std::string Lexer::Stringify(const std::string &Str, bool Charify) {
150 std::string Result = Str;
151 char Quote = Charify ? '\'' : '"';
152 for (unsigned i = 0, e = Result.size(); i != e; ++i) {
153 if (Result[i] == '\\' || Result[i] == Quote) {
154 Result.insert(Result.begin()+i, '\\');
155 ++i; ++e;
156 }
157 }
158 return Result;
159}
160
161/// Stringify - Convert the specified string into a C string by escaping '\'
162/// and " characters. This does not add surrounding ""'s to the string.
163void Lexer::Stringify(llvm::SmallVectorImpl<char> &Str) {
164 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
165 if (Str[i] == '\\' || Str[i] == '"') {
166 Str.insert(Str.begin()+i, '\\');
167 ++i; ++e;
168 }
169 }
170}
171
172
Chris Lattner761d76b2007-10-17 21:18:47 +0000173/// MeasureTokenLength - Relex the token at the specified location and return
174/// its length in bytes in the input file. If the token needs cleaning (e.g.
175/// includes a trigraph or an escaped newline) then this count includes bytes
176/// that are part of that.
177unsigned Lexer::MeasureTokenLength(SourceLocation Loc,
178 const SourceManager &SM) {
179 // If this comes from a macro expansion, we really do want the macro name, not
180 // the token this macro expanded to.
181 Loc = SM.getLogicalLoc(Loc);
182
183 const char *StrData = SM.getCharacterData(Loc);
184
185 // TODO: this could be special cased for common tokens like identifiers, ')',
186 // etc to make this faster, if it mattered. Just look at StrData[0] to handle
187 // all obviously single-char tokens. This could use
188 // Lexer::isObviouslySimpleCharacter for example to handle identifiers or
189 // something.
190
191
192 const char *BufEnd = SM.getBufferData(Loc.getFileID()).second;
193
194 // Create a langops struct and enable trigraphs. This is sufficient for
195 // measuring tokens.
196 LangOptions LangOpts;
197 LangOpts.Trigraphs = true;
198
199 // Create a lexer starting at the beginning of this token.
200 Lexer TheLexer(Loc, LangOpts, StrData, BufEnd);
201 Token TheTok;
Chris Lattner0b5892e2008-10-12 01:15:46 +0000202 TheLexer.LexFromRawLexer(TheTok);
Chris Lattner761d76b2007-10-17 21:18:47 +0000203 return TheTok.getLength();
204}
205
Chris Lattner4b009652007-07-25 00:24:17 +0000206//===----------------------------------------------------------------------===//
207// Character information.
208//===----------------------------------------------------------------------===//
209
210static unsigned char CharInfo[256];
211
212enum {
213 CHAR_HORZ_WS = 0x01, // ' ', '\t', '\f', '\v'. Note, no '\0'
214 CHAR_VERT_WS = 0x02, // '\r', '\n'
215 CHAR_LETTER = 0x04, // a-z,A-Z
216 CHAR_NUMBER = 0x08, // 0-9
217 CHAR_UNDER = 0x10, // _
218 CHAR_PERIOD = 0x20 // .
219};
220
221static void InitCharacterInfo() {
222 static bool isInited = false;
223 if (isInited) return;
224 isInited = true;
225
226 // Intiialize the CharInfo table.
227 // TODO: statically initialize this.
228 CharInfo[(int)' '] = CharInfo[(int)'\t'] =
229 CharInfo[(int)'\f'] = CharInfo[(int)'\v'] = CHAR_HORZ_WS;
230 CharInfo[(int)'\n'] = CharInfo[(int)'\r'] = CHAR_VERT_WS;
231
232 CharInfo[(int)'_'] = CHAR_UNDER;
233 CharInfo[(int)'.'] = CHAR_PERIOD;
234 for (unsigned i = 'a'; i <= 'z'; ++i)
235 CharInfo[i] = CharInfo[i+'A'-'a'] = CHAR_LETTER;
236 for (unsigned i = '0'; i <= '9'; ++i)
237 CharInfo[i] = CHAR_NUMBER;
238}
239
240/// isIdentifierBody - Return true if this is the body character of an
241/// identifier, which is [a-zA-Z0-9_].
242static inline bool isIdentifierBody(unsigned char c) {
Hartmut Kaiserc62f6b92007-10-18 12:47:01 +0000243 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER)) ? true : false;
Chris Lattner4b009652007-07-25 00:24:17 +0000244}
245
246/// isHorizontalWhitespace - Return true if this character is horizontal
247/// whitespace: ' ', '\t', '\f', '\v'. Note that this returns false for '\0'.
248static inline bool isHorizontalWhitespace(unsigned char c) {
Hartmut Kaiserc62f6b92007-10-18 12:47:01 +0000249 return (CharInfo[c] & CHAR_HORZ_WS) ? true : false;
Chris Lattner4b009652007-07-25 00:24:17 +0000250}
251
252/// isWhitespace - Return true if this character is horizontal or vertical
253/// whitespace: ' ', '\t', '\f', '\v', '\n', '\r'. Note that this returns false
254/// for '\0'.
255static inline bool isWhitespace(unsigned char c) {
Hartmut Kaiserc62f6b92007-10-18 12:47:01 +0000256 return (CharInfo[c] & (CHAR_HORZ_WS|CHAR_VERT_WS)) ? true : false;
Chris Lattner4b009652007-07-25 00:24:17 +0000257}
258
259/// isNumberBody - Return true if this is the body character of an
260/// preprocessing number, which is [a-zA-Z0-9_.].
261static inline bool isNumberBody(unsigned char c) {
Hartmut Kaiserc62f6b92007-10-18 12:47:01 +0000262 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER|CHAR_PERIOD)) ?
263 true : false;
Chris Lattner4b009652007-07-25 00:24:17 +0000264}
265
266
267//===----------------------------------------------------------------------===//
268// Diagnostics forwarding code.
269//===----------------------------------------------------------------------===//
270
271/// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
272/// lexer buffer was all instantiated at a single point, perform the mapping.
273/// This is currently only used for _Pragma implementation, so it is the slow
274/// path of the hot getSourceLocation method. Do not allow it to be inlined.
275static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
276 SourceLocation FileLoc,
277 unsigned CharNo) DISABLE_INLINE;
278static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
279 SourceLocation FileLoc,
280 unsigned CharNo) {
281 // Otherwise, we're lexing "mapped tokens". This is used for things like
282 // _Pragma handling. Combine the instantiation location of FileLoc with the
283 // physical location.
284 SourceManager &SourceMgr = PP.getSourceManager();
285
286 // Create a new SLoc which is expanded from logical(FileLoc) but whose
287 // characters come from phys(FileLoc)+Offset.
288 SourceLocation VirtLoc = SourceMgr.getLogicalLoc(FileLoc);
289 SourceLocation PhysLoc = SourceMgr.getPhysicalLoc(FileLoc);
290 PhysLoc = SourceLocation::getFileLoc(PhysLoc.getFileID(), CharNo);
291 return SourceMgr.getInstantiationLoc(PhysLoc, VirtLoc);
292}
293
294/// getSourceLocation - Return a source location identifier for the specified
295/// offset in the current file.
296SourceLocation Lexer::getSourceLocation(const char *Loc) const {
297 assert(Loc >= BufferStart && Loc <= BufferEnd &&
298 "Location out of range for this buffer!");
299
300 // In the normal case, we're just lexing from a simple file buffer, return
301 // the file id from FileLoc with the offset specified.
302 unsigned CharNo = Loc-BufferStart;
303 if (FileLoc.isFileID())
304 return SourceLocation::getFileLoc(FileLoc.getFileID(), CharNo);
305
Chris Lattner342dccb2007-10-17 20:41:00 +0000306 assert(PP && "This doesn't work on raw lexers");
307 return GetMappedTokenLoc(*PP, FileLoc, CharNo);
Chris Lattner4b009652007-07-25 00:24:17 +0000308}
309
310/// Diag - Forwarding function for diagnostics. This translate a source
311/// position in the current buffer into a SourceLocation object for rendering.
Chris Lattner9943e982008-11-22 00:59:29 +0000312DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
Chris Lattner0370d6b2008-11-18 07:59:24 +0000313 return PP->Diag(getSourceLocation(Loc), DiagID);
Chris Lattner4b009652007-07-25 00:24:17 +0000314}
Chris Lattner4b009652007-07-25 00:24:17 +0000315
Chris Lattner82b474f2008-11-22 06:20:42 +0000316DiagnosticBuilder Lexer::Diag(SourceLocation Loc, unsigned DiagID) const {
317 return PP->Diag(Loc, DiagID);
318}
319
320
Chris Lattner4b009652007-07-25 00:24:17 +0000321//===----------------------------------------------------------------------===//
322// Trigraph and Escaped Newline Handling Code.
323//===----------------------------------------------------------------------===//
324
325/// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
326/// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
327static char GetTrigraphCharForLetter(char Letter) {
328 switch (Letter) {
329 default: return 0;
330 case '=': return '#';
331 case ')': return ']';
332 case '(': return '[';
333 case '!': return '|';
334 case '\'': return '^';
335 case '>': return '}';
336 case '/': return '\\';
337 case '<': return '{';
338 case '-': return '~';
339 }
340}
341
342/// DecodeTrigraphChar - If the specified character is a legal trigraph when
343/// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
344/// return the result character. Finally, emit a warning about trigraph use
345/// whether trigraphs are enabled or not.
346static char DecodeTrigraphChar(const char *CP, Lexer *L) {
347 char Res = GetTrigraphCharForLetter(*CP);
Chris Lattner0370d6b2008-11-18 07:59:24 +0000348 if (!Res || !L) return Res;
349
350 if (!L->getFeatures().Trigraphs) {
Chris Lattnerf9c62772008-11-22 02:02:22 +0000351 if (!L->isLexingRawMode())
352 L->Diag(CP-2, diag::trigraph_ignored);
Chris Lattner0370d6b2008-11-18 07:59:24 +0000353 return 0;
Chris Lattner4b009652007-07-25 00:24:17 +0000354 }
Chris Lattner0370d6b2008-11-18 07:59:24 +0000355
Chris Lattnerf9c62772008-11-22 02:02:22 +0000356 if (!L->isLexingRawMode())
357 L->Diag(CP-2, diag::trigraph_converted) << std::string()+Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000358 return Res;
359}
360
361/// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
362/// get its size, and return it. This is tricky in several cases:
363/// 1. If currently at the start of a trigraph, we warn about the trigraph,
364/// then either return the trigraph (skipping 3 chars) or the '?',
365/// depending on whether trigraphs are enabled or not.
366/// 2. If this is an escaped newline (potentially with whitespace between
367/// the backslash and newline), implicitly skip the newline and return
368/// the char after it.
369/// 3. If this is a UCN, return it. FIXME: C++ UCN's?
370///
371/// This handles the slow/uncommon case of the getCharAndSize method. Here we
372/// know that we can accumulate into Size, and that we have already incremented
373/// Ptr by Size bytes.
374///
375/// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
376/// be updated to match.
377///
378char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
379 Token *Tok) {
380 // If we have a slash, look for an escaped newline.
381 if (Ptr[0] == '\\') {
382 ++Size;
383 ++Ptr;
384Slash:
385 // Common case, backslash-char where the char is not whitespace.
386 if (!isWhitespace(Ptr[0])) return '\\';
387
388 // See if we have optional whitespace characters followed by a newline.
389 {
390 unsigned SizeTmp = 0;
391 do {
392 ++SizeTmp;
393 if (Ptr[SizeTmp-1] == '\n' || Ptr[SizeTmp-1] == '\r') {
394 // Remember that this token needs to be cleaned.
395 if (Tok) Tok->setFlag(Token::NeedsCleaning);
396
397 // Warn if there was whitespace between the backslash and newline.
Chris Lattnerf9c62772008-11-22 02:02:22 +0000398 if (SizeTmp != 1 && Tok && !isLexingRawMode())
Chris Lattner4b009652007-07-25 00:24:17 +0000399 Diag(Ptr, diag::backslash_newline_space);
400
401 // If this is a \r\n or \n\r, skip the newlines.
402 if ((Ptr[SizeTmp] == '\r' || Ptr[SizeTmp] == '\n') &&
403 Ptr[SizeTmp-1] != Ptr[SizeTmp])
404 ++SizeTmp;
405
406 // Found backslash<whitespace><newline>. Parse the char after it.
407 Size += SizeTmp;
408 Ptr += SizeTmp;
409 // Use slow version to accumulate a correct size field.
410 return getCharAndSizeSlow(Ptr, Size, Tok);
411 }
412 } while (isWhitespace(Ptr[SizeTmp]));
413 }
414
415 // Otherwise, this is not an escaped newline, just return the slash.
416 return '\\';
417 }
418
419 // If this is a trigraph, process it.
420 if (Ptr[0] == '?' && Ptr[1] == '?') {
421 // If this is actually a legal trigraph (not something like "??x"), emit
422 // a trigraph warning. If so, and if trigraphs are enabled, return it.
423 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : 0)) {
424 // Remember that this token needs to be cleaned.
425 if (Tok) Tok->setFlag(Token::NeedsCleaning);
426
427 Ptr += 3;
428 Size += 3;
429 if (C == '\\') goto Slash;
430 return C;
431 }
432 }
433
434 // If this is neither, return a single character.
435 ++Size;
436 return *Ptr;
437}
438
439
440/// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
441/// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
442/// and that we have already incremented Ptr by Size bytes.
443///
444/// NOTE: When this method is updated, getCharAndSizeSlow (above) should
445/// be updated to match.
446char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
447 const LangOptions &Features) {
448 // If we have a slash, look for an escaped newline.
449 if (Ptr[0] == '\\') {
450 ++Size;
451 ++Ptr;
452Slash:
453 // Common case, backslash-char where the char is not whitespace.
454 if (!isWhitespace(Ptr[0])) return '\\';
455
456 // See if we have optional whitespace characters followed by a newline.
457 {
458 unsigned SizeTmp = 0;
459 do {
460 ++SizeTmp;
461 if (Ptr[SizeTmp-1] == '\n' || Ptr[SizeTmp-1] == '\r') {
462
463 // If this is a \r\n or \n\r, skip the newlines.
464 if ((Ptr[SizeTmp] == '\r' || Ptr[SizeTmp] == '\n') &&
465 Ptr[SizeTmp-1] != Ptr[SizeTmp])
466 ++SizeTmp;
467
468 // Found backslash<whitespace><newline>. Parse the char after it.
469 Size += SizeTmp;
470 Ptr += SizeTmp;
471
472 // Use slow version to accumulate a correct size field.
473 return getCharAndSizeSlowNoWarn(Ptr, Size, Features);
474 }
475 } while (isWhitespace(Ptr[SizeTmp]));
476 }
477
478 // Otherwise, this is not an escaped newline, just return the slash.
479 return '\\';
480 }
481
482 // If this is a trigraph, process it.
483 if (Features.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
484 // If this is actually a legal trigraph (not something like "??x"), return
485 // it.
486 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
487 Ptr += 3;
488 Size += 3;
489 if (C == '\\') goto Slash;
490 return C;
491 }
492 }
493
494 // If this is neither, return a single character.
495 ++Size;
496 return *Ptr;
497}
498
499//===----------------------------------------------------------------------===//
500// Helper methods for lexing.
501//===----------------------------------------------------------------------===//
502
503void Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
504 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
505 unsigned Size;
506 unsigned char C = *CurPtr++;
507 while (isIdentifierBody(C)) {
508 C = *CurPtr++;
509 }
510 --CurPtr; // Back up over the skipped character.
511
512 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
513 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
514 // FIXME: UCNs.
515 if (C != '\\' && C != '?' && (C != '$' || !Features.DollarIdents)) {
516FinishIdentifier:
517 const char *IdStart = BufferPtr;
Chris Lattner0344cc72008-10-12 04:51:35 +0000518 FormTokenWithChars(Result, CurPtr, tok::identifier);
Chris Lattner4b009652007-07-25 00:24:17 +0000519
520 // If we are in raw mode, return this identifier raw. There is no need to
521 // look up identifier information or attempt to macro expand it.
522 if (LexingRawMode) return;
523
524 // Fill in Result.IdentifierInfo, looking up the identifier in the
525 // identifier table.
Chris Lattner342dccb2007-10-17 20:41:00 +0000526 PP->LookUpIdentifierInfo(Result, IdStart);
Chris Lattner4b009652007-07-25 00:24:17 +0000527
528 // Finally, now that we know we have an identifier, pass this off to the
529 // preprocessor, which may macro expand it or something.
Chris Lattner342dccb2007-10-17 20:41:00 +0000530 return PP->HandleIdentifier(Result);
Chris Lattner4b009652007-07-25 00:24:17 +0000531 }
532
533 // Otherwise, $,\,? in identifier found. Enter slower path.
534
535 C = getCharAndSize(CurPtr, Size);
536 while (1) {
537 if (C == '$') {
538 // If we hit a $ and they are not supported in identifiers, we are done.
539 if (!Features.DollarIdents) goto FinishIdentifier;
540
541 // Otherwise, emit a diagnostic and continue.
Chris Lattnerf9c62772008-11-22 02:02:22 +0000542 if (!isLexingRawMode())
543 Diag(CurPtr, diag::ext_dollar_in_identifier);
Chris Lattner4b009652007-07-25 00:24:17 +0000544 CurPtr = ConsumeChar(CurPtr, Size, Result);
545 C = getCharAndSize(CurPtr, Size);
546 continue;
547 } else if (!isIdentifierBody(C)) { // FIXME: UCNs.
548 // Found end of identifier.
549 goto FinishIdentifier;
550 }
551
552 // Otherwise, this character is good, consume it.
553 CurPtr = ConsumeChar(CurPtr, Size, Result);
554
555 C = getCharAndSize(CurPtr, Size);
556 while (isIdentifierBody(C)) { // FIXME: UCNs.
557 CurPtr = ConsumeChar(CurPtr, Size, Result);
558 C = getCharAndSize(CurPtr, Size);
559 }
560 }
561}
562
563
Nate Begeman937cac72008-04-14 02:26:39 +0000564/// LexNumericConstant - Lex the remainder of a integer or floating point
Chris Lattner4b009652007-07-25 00:24:17 +0000565/// constant. From[-1] is the first character lexed. Return the end of the
566/// constant.
567void Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
568 unsigned Size;
569 char C = getCharAndSize(CurPtr, Size);
570 char PrevCh = 0;
571 while (isNumberBody(C)) { // FIXME: UCNs?
572 CurPtr = ConsumeChar(CurPtr, Size, Result);
573 PrevCh = C;
574 C = getCharAndSize(CurPtr, Size);
575 }
576
577 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
578 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e'))
579 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
580
581 // If we have a hex FP constant, continue.
582 if (Features.HexFloats &&
583 (C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p'))
584 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
585
Chris Lattner4b009652007-07-25 00:24:17 +0000586 // Update the location of token as well as BufferPtr.
Chris Lattner0344cc72008-10-12 04:51:35 +0000587 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
Chris Lattner4b009652007-07-25 00:24:17 +0000588}
589
590/// LexStringLiteral - Lex the remainder of a string literal, after having lexed
591/// either " or L".
Chris Lattner867a87b2008-10-12 04:05:48 +0000592void Lexer::LexStringLiteral(Token &Result, const char *CurPtr, bool Wide) {
Chris Lattner4b009652007-07-25 00:24:17 +0000593 const char *NulCharacter = 0; // Does this string contain the \0 character?
594
595 char C = getAndAdvanceChar(CurPtr, Result);
596 while (C != '"') {
597 // Skip escaped characters.
598 if (C == '\\') {
599 // Skip the escaped character.
600 C = getAndAdvanceChar(CurPtr, Result);
601 } else if (C == '\n' || C == '\r' || // Newline.
602 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Chris Lattnerf9c62772008-11-22 02:02:22 +0000603 if (!isLexingRawMode())
604 Diag(BufferPtr, diag::err_unterminated_string);
Chris Lattner0344cc72008-10-12 04:51:35 +0000605 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Chris Lattner4b009652007-07-25 00:24:17 +0000606 return;
607 } else if (C == 0) {
608 NulCharacter = CurPtr-1;
609 }
610 C = getAndAdvanceChar(CurPtr, Result);
611 }
612
613 // If a nul character existed in the string, warn about it.
Chris Lattnerf9c62772008-11-22 02:02:22 +0000614 if (NulCharacter && !isLexingRawMode())
615 Diag(NulCharacter, diag::null_in_string);
Chris Lattner4b009652007-07-25 00:24:17 +0000616
Chris Lattner4b009652007-07-25 00:24:17 +0000617 // Update the location of the token as well as the BufferPtr instance var.
Chris Lattner0344cc72008-10-12 04:51:35 +0000618 FormTokenWithChars(Result, CurPtr,
619 Wide ? tok::wide_string_literal : tok::string_literal);
Chris Lattner4b009652007-07-25 00:24:17 +0000620}
621
622/// LexAngledStringLiteral - Lex the remainder of an angled string literal,
623/// after having lexed the '<' character. This is used for #include filenames.
624void Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
625 const char *NulCharacter = 0; // Does this string contain the \0 character?
626
627 char C = getAndAdvanceChar(CurPtr, Result);
628 while (C != '>') {
629 // Skip escaped characters.
630 if (C == '\\') {
631 // Skip the escaped character.
632 C = getAndAdvanceChar(CurPtr, Result);
633 } else if (C == '\n' || C == '\r' || // Newline.
634 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Chris Lattnerf9c62772008-11-22 02:02:22 +0000635 if (!isLexingRawMode())
636 Diag(BufferPtr, diag::err_unterminated_string);
Chris Lattner0344cc72008-10-12 04:51:35 +0000637 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Chris Lattner4b009652007-07-25 00:24:17 +0000638 return;
639 } else if (C == 0) {
640 NulCharacter = CurPtr-1;
641 }
642 C = getAndAdvanceChar(CurPtr, Result);
643 }
644
645 // If a nul character existed in the string, warn about it.
Chris Lattnerf9c62772008-11-22 02:02:22 +0000646 if (NulCharacter && !isLexingRawMode())
647 Diag(NulCharacter, diag::null_in_string);
Chris Lattner4b009652007-07-25 00:24:17 +0000648
Chris Lattner4b009652007-07-25 00:24:17 +0000649 // Update the location of token as well as BufferPtr.
Chris Lattner0344cc72008-10-12 04:51:35 +0000650 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
Chris Lattner4b009652007-07-25 00:24:17 +0000651}
652
653
654/// LexCharConstant - Lex the remainder of a character constant, after having
655/// lexed either ' or L'.
656void Lexer::LexCharConstant(Token &Result, const char *CurPtr) {
657 const char *NulCharacter = 0; // Does this character contain the \0 character?
658
659 // Handle the common case of 'x' and '\y' efficiently.
660 char C = getAndAdvanceChar(CurPtr, Result);
661 if (C == '\'') {
Chris Lattnerf9c62772008-11-22 02:02:22 +0000662 if (!isLexingRawMode())
663 Diag(BufferPtr, diag::err_empty_character);
Chris Lattner0344cc72008-10-12 04:51:35 +0000664 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner4b009652007-07-25 00:24:17 +0000665 return;
666 } else if (C == '\\') {
667 // Skip the escaped character.
668 // FIXME: UCN's.
669 C = getAndAdvanceChar(CurPtr, Result);
670 }
671
672 if (C && C != '\n' && C != '\r' && CurPtr[0] == '\'') {
673 ++CurPtr;
674 } else {
675 // Fall back on generic code for embedded nulls, newlines, wide chars.
676 do {
677 // Skip escaped characters.
678 if (C == '\\') {
679 // Skip the escaped character.
680 C = getAndAdvanceChar(CurPtr, Result);
681 } else if (C == '\n' || C == '\r' || // Newline.
682 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Chris Lattnerf9c62772008-11-22 02:02:22 +0000683 if (!isLexingRawMode())
684 Diag(BufferPtr, diag::err_unterminated_char);
Chris Lattner0344cc72008-10-12 04:51:35 +0000685 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Chris Lattner4b009652007-07-25 00:24:17 +0000686 return;
687 } else if (C == 0) {
688 NulCharacter = CurPtr-1;
689 }
690 C = getAndAdvanceChar(CurPtr, Result);
691 } while (C != '\'');
692 }
693
Chris Lattnerf9c62772008-11-22 02:02:22 +0000694 if (NulCharacter && !isLexingRawMode())
695 Diag(NulCharacter, diag::null_in_char);
Chris Lattner4b009652007-07-25 00:24:17 +0000696
Chris Lattner4b009652007-07-25 00:24:17 +0000697 // Update the location of token as well as BufferPtr.
Chris Lattner0344cc72008-10-12 04:51:35 +0000698 FormTokenWithChars(Result, CurPtr, tok::char_constant);
Chris Lattner4b009652007-07-25 00:24:17 +0000699}
700
701/// SkipWhitespace - Efficiently skip over a series of whitespace characters.
702/// Update BufferPtr to point to the next non-whitespace character and return.
Chris Lattner867a87b2008-10-12 04:05:48 +0000703///
704/// This method forms a token and returns true if KeepWhitespaceMode is enabled.
705///
706bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr) {
Chris Lattner4b009652007-07-25 00:24:17 +0000707 // Whitespace - Skip it, then return the token after the whitespace.
708 unsigned char Char = *CurPtr; // Skip consequtive spaces efficiently.
709 while (1) {
710 // Skip horizontal whitespace very aggressively.
711 while (isHorizontalWhitespace(Char))
712 Char = *++CurPtr;
713
714 // Otherwise if we something other than whitespace, we're done.
715 if (Char != '\n' && Char != '\r')
716 break;
717
718 if (ParsingPreprocessorDirective) {
719 // End of preprocessor directive line, let LexTokenInternal handle this.
720 BufferPtr = CurPtr;
Chris Lattner867a87b2008-10-12 04:05:48 +0000721 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000722 }
723
724 // ok, but handle newline.
725 // The returned token is at the start of the line.
726 Result.setFlag(Token::StartOfLine);
727 // No leading whitespace seen so far.
728 Result.clearFlag(Token::LeadingSpace);
729 Char = *++CurPtr;
730 }
731
732 // If this isn't immediately after a newline, there is leading space.
733 char PrevChar = CurPtr[-1];
734 if (PrevChar != '\n' && PrevChar != '\r')
735 Result.setFlag(Token::LeadingSpace);
736
Chris Lattner867a87b2008-10-12 04:05:48 +0000737 // If the client wants us to return whitespace, return it now.
738 if (isKeepWhitespaceMode()) {
Chris Lattner0344cc72008-10-12 04:51:35 +0000739 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner867a87b2008-10-12 04:05:48 +0000740 return true;
741 }
742
Chris Lattner4b009652007-07-25 00:24:17 +0000743 BufferPtr = CurPtr;
Chris Lattner867a87b2008-10-12 04:05:48 +0000744 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000745}
746
747// SkipBCPLComment - We have just read the // characters from input. Skip until
748// we find the newline character thats terminate the comment. Then update
Chris Lattnerf03b00c2008-10-12 04:15:42 +0000749/// BufferPtr and return. If we're in KeepCommentMode, this will form the token
750/// and return true.
Chris Lattner4b009652007-07-25 00:24:17 +0000751bool Lexer::SkipBCPLComment(Token &Result, const char *CurPtr) {
752 // If BCPL comments aren't explicitly enabled for this language, emit an
753 // extension warning.
Chris Lattnerf9c62772008-11-22 02:02:22 +0000754 if (!Features.BCPLComment && !isLexingRawMode()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000755 Diag(BufferPtr, diag::ext_bcpl_comment);
756
757 // Mark them enabled so we only emit one warning for this translation
758 // unit.
759 Features.BCPLComment = true;
760 }
761
762 // Scan over the body of the comment. The common case, when scanning, is that
763 // the comment contains normal ascii characters with nothing interesting in
764 // them. As such, optimize for this case with the inner loop.
765 char C;
766 do {
767 C = *CurPtr;
768 // FIXME: Speedup BCPL comment lexing. Just scan for a \n or \r character.
769 // If we find a \n character, scan backwards, checking to see if it's an
770 // escaped newline, like we do for block comments.
771
772 // Skip over characters in the fast loop.
773 while (C != 0 && // Potentially EOF.
774 C != '\\' && // Potentially escaped newline.
775 C != '?' && // Potentially trigraph.
776 C != '\n' && C != '\r') // Newline or DOS-style newline.
777 C = *++CurPtr;
778
779 // If this is a newline, we're done.
780 if (C == '\n' || C == '\r')
781 break; // Found the newline? Break out!
782
783 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
784 // properly decode the character.
785 const char *OldPtr = CurPtr;
786 C = getAndAdvanceChar(CurPtr, Result);
787
788 // If we read multiple characters, and one of those characters was a \r or
789 // \n, then we had an escaped newline within the comment. Emit diagnostic
790 // unless the next line is also a // comment.
791 if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') {
792 for (; OldPtr != CurPtr; ++OldPtr)
793 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
794 // Okay, we found a // comment that ends in a newline, if the next
795 // line is also a // comment, but has spaces, don't emit a diagnostic.
796 if (isspace(C)) {
797 const char *ForwardPtr = CurPtr;
798 while (isspace(*ForwardPtr)) // Skip whitespace.
799 ++ForwardPtr;
800 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
801 break;
802 }
803
Chris Lattnerf9c62772008-11-22 02:02:22 +0000804 if (!isLexingRawMode())
805 Diag(OldPtr-1, diag::ext_multi_line_bcpl_comment);
Chris Lattner4b009652007-07-25 00:24:17 +0000806 break;
807 }
808 }
809
810 if (CurPtr == BufferEnd+1) { --CurPtr; break; }
811 } while (C != '\n' && C != '\r');
812
813 // Found but did not consume the newline.
814
815 // If we are returning comments as tokens, return this comment as a token.
Chris Lattner170adb12008-10-12 03:22:02 +0000816 if (inKeepCommentMode())
Chris Lattner4b009652007-07-25 00:24:17 +0000817 return SaveBCPLComment(Result, CurPtr);
818
819 // If we are inside a preprocessor directive and we see the end of line,
820 // return immediately, so that the lexer can return this as an EOM token.
821 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
822 BufferPtr = CurPtr;
Chris Lattnerf03b00c2008-10-12 04:15:42 +0000823 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000824 }
825
826 // Otherwise, eat the \n character. We don't care if this is a \n\r or
Chris Lattner43d38202008-10-12 00:23:07 +0000827 // \r\n sequence. This is an efficiency hack (because we know the \n can't
Chris Lattner867a87b2008-10-12 04:05:48 +0000828 // contribute to another token), it isn't needed for correctness. Note that
829 // this is ok even in KeepWhitespaceMode, because we would have returned the
830 /// comment above in that mode.
Chris Lattner4b009652007-07-25 00:24:17 +0000831 ++CurPtr;
832
833 // The next returned token is at the start of the line.
834 Result.setFlag(Token::StartOfLine);
835 // No leading whitespace seen so far.
836 Result.clearFlag(Token::LeadingSpace);
837 BufferPtr = CurPtr;
Chris Lattnerf03b00c2008-10-12 04:15:42 +0000838 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000839}
840
841/// SaveBCPLComment - If in save-comment mode, package up this BCPL comment in
842/// an appropriate way and return it.
843bool Lexer::SaveBCPLComment(Token &Result, const char *CurPtr) {
Chris Lattner0344cc72008-10-12 04:51:35 +0000844 // If we're not in a preprocessor directive, just return the // comment
845 // directly.
846 FormTokenWithChars(Result, CurPtr, tok::comment);
Chris Lattner4b009652007-07-25 00:24:17 +0000847
Chris Lattner0344cc72008-10-12 04:51:35 +0000848 if (!ParsingPreprocessorDirective)
849 return true;
850
851 // If this BCPL-style comment is in a macro definition, transmogrify it into
852 // a C-style block comment.
853 std::string Spelling = PP->getSpelling(Result);
854 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not bcpl comment?");
855 Spelling[1] = '*'; // Change prefix to "/*".
856 Spelling += "*/"; // add suffix.
857
858 Result.setKind(tok::comment);
859 Result.setLocation(PP->CreateString(&Spelling[0], Spelling.size(),
860 Result.getLocation()));
861 Result.setLength(Spelling.size());
Chris Lattnerf03b00c2008-10-12 04:15:42 +0000862 return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000863}
864
865/// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
866/// character (either \n or \r) is part of an escaped newline sequence. Issue a
867/// diagnostic if so. We know that the is inside of a block comment.
868static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
869 Lexer *L) {
870 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
871
872 // Back up off the newline.
873 --CurPtr;
874
875 // If this is a two-character newline sequence, skip the other character.
876 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
877 // \n\n or \r\r -> not escaped newline.
878 if (CurPtr[0] == CurPtr[1])
879 return false;
880 // \n\r or \r\n -> skip the newline.
881 --CurPtr;
882 }
883
884 // If we have horizontal whitespace, skip over it. We allow whitespace
885 // between the slash and newline.
886 bool HasSpace = false;
887 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
888 --CurPtr;
889 HasSpace = true;
890 }
891
892 // If we have a slash, we know this is an escaped newline.
893 if (*CurPtr == '\\') {
894 if (CurPtr[-1] != '*') return false;
895 } else {
896 // It isn't a slash, is it the ?? / trigraph?
897 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
898 CurPtr[-3] != '*')
899 return false;
900
901 // This is the trigraph ending the comment. Emit a stern warning!
902 CurPtr -= 2;
903
904 // If no trigraphs are enabled, warn that we ignored this trigraph and
905 // ignore this * character.
906 if (!L->getFeatures().Trigraphs) {
Chris Lattnerf9c62772008-11-22 02:02:22 +0000907 if (!L->isLexingRawMode())
908 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
Chris Lattner4b009652007-07-25 00:24:17 +0000909 return false;
910 }
Chris Lattnerf9c62772008-11-22 02:02:22 +0000911 if (!L->isLexingRawMode())
912 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
Chris Lattner4b009652007-07-25 00:24:17 +0000913 }
914
915 // Warn about having an escaped newline between the */ characters.
Chris Lattnerf9c62772008-11-22 02:02:22 +0000916 if (!L->isLexingRawMode())
917 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
Chris Lattner4b009652007-07-25 00:24:17 +0000918
919 // If there was space between the backslash and newline, warn about it.
Chris Lattnerf9c62772008-11-22 02:02:22 +0000920 if (HasSpace && !L->isLexingRawMode())
921 L->Diag(CurPtr, diag::backslash_newline_space);
Chris Lattner4b009652007-07-25 00:24:17 +0000922
923 return true;
924}
925
926#ifdef __SSE2__
927#include <emmintrin.h>
928#elif __ALTIVEC__
929#include <altivec.h>
930#undef bool
931#endif
932
933/// SkipBlockComment - We have just read the /* characters from input. Read
934/// until we find the */ characters that terminate the comment. Note that we
935/// don't bother decoding trigraphs or escaped newlines in block comments,
936/// because they cannot cause the comment to end. The only thing that can
937/// happen is the comment could end with an escaped newline between the */ end
938/// of comment.
Chris Lattnerf03b00c2008-10-12 04:15:42 +0000939///
940/// If KeepCommentMode is enabled, this forms a token from the comment and
941/// returns true.
Chris Lattner4b009652007-07-25 00:24:17 +0000942bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr) {
943 // Scan one character past where we should, looking for a '/' character. Once
944 // we find it, check to see if it was preceeded by a *. This common
945 // optimization helps people who like to put a lot of * characters in their
946 // comments.
947
948 // The first character we get with newlines and trigraphs skipped to handle
949 // the degenerate /*/ case below correctly if the * has an escaped newline
950 // after it.
951 unsigned CharSize;
952 unsigned char C = getCharAndSize(CurPtr, CharSize);
953 CurPtr += CharSize;
954 if (C == 0 && CurPtr == BufferEnd+1) {
Chris Lattnerf9c62772008-11-22 02:02:22 +0000955 if (!isLexingRawMode())
Chris Lattnere5eca952008-10-12 01:31:51 +0000956 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattnerd66f4542008-10-12 04:19:49 +0000957 --CurPtr;
958
959 // KeepWhitespaceMode should return this broken comment as a token. Since
960 // it isn't a well formed comment, just return it as an 'unknown' token.
961 if (isKeepWhitespaceMode()) {
Chris Lattner0344cc72008-10-12 04:51:35 +0000962 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd66f4542008-10-12 04:19:49 +0000963 return true;
964 }
965
966 BufferPtr = CurPtr;
Chris Lattnerf03b00c2008-10-12 04:15:42 +0000967 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000968 }
969
970 // Check to see if the first character after the '/*' is another /. If so,
971 // then this slash does not end the block comment, it is part of it.
972 if (C == '/')
973 C = *CurPtr++;
974
975 while (1) {
976 // Skip over all non-interesting characters until we find end of buffer or a
977 // (probably ending) '/' character.
978 if (CurPtr + 24 < BufferEnd) {
979 // While not aligned to a 16-byte boundary.
980 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
981 C = *CurPtr++;
982
983 if (C == '/') goto FoundSlash;
984
985#ifdef __SSE2__
986 __m128i Slashes = _mm_set_epi8('/', '/', '/', '/', '/', '/', '/', '/',
987 '/', '/', '/', '/', '/', '/', '/', '/');
988 while (CurPtr+16 <= BufferEnd &&
989 _mm_movemask_epi8(_mm_cmpeq_epi8(*(__m128i*)CurPtr, Slashes)) == 0)
990 CurPtr += 16;
991#elif __ALTIVEC__
992 __vector unsigned char Slashes = {
993 '/', '/', '/', '/', '/', '/', '/', '/',
994 '/', '/', '/', '/', '/', '/', '/', '/'
995 };
996 while (CurPtr+16 <= BufferEnd &&
997 !vec_any_eq(*(vector unsigned char*)CurPtr, Slashes))
998 CurPtr += 16;
999#else
1000 // Scan for '/' quickly. Many block comments are very large.
1001 while (CurPtr[0] != '/' &&
1002 CurPtr[1] != '/' &&
1003 CurPtr[2] != '/' &&
1004 CurPtr[3] != '/' &&
1005 CurPtr+4 < BufferEnd) {
1006 CurPtr += 4;
1007 }
1008#endif
1009
1010 // It has to be one of the bytes scanned, increment to it and read one.
1011 C = *CurPtr++;
1012 }
1013
1014 // Loop to scan the remainder.
1015 while (C != '/' && C != '\0')
1016 C = *CurPtr++;
1017
1018 FoundSlash:
1019 if (C == '/') {
1020 if (CurPtr[-2] == '*') // We found the final */. We're done!
1021 break;
1022
1023 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
1024 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
1025 // We found the final */, though it had an escaped newline between the
1026 // * and /. We're done!
1027 break;
1028 }
1029 }
1030 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
1031 // If this is a /* inside of the comment, emit a warning. Don't do this
1032 // if this is a /*/, which will end the comment. This misses cases with
1033 // embedded escaped newlines, but oh well.
Chris Lattnerf9c62772008-11-22 02:02:22 +00001034 if (!isLexingRawMode())
1035 Diag(CurPtr-1, diag::warn_nested_block_comment);
Chris Lattner4b009652007-07-25 00:24:17 +00001036 }
1037 } else if (C == 0 && CurPtr == BufferEnd+1) {
Chris Lattnerf9c62772008-11-22 02:02:22 +00001038 if (!isLexingRawMode())
1039 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner4b009652007-07-25 00:24:17 +00001040 // Note: the user probably forgot a */. We could continue immediately
1041 // after the /*, but this would involve lexing a lot of what really is the
1042 // comment, which surely would confuse the parser.
Chris Lattnerd66f4542008-10-12 04:19:49 +00001043 --CurPtr;
1044
1045 // KeepWhitespaceMode should return this broken comment as a token. Since
1046 // it isn't a well formed comment, just return it as an 'unknown' token.
1047 if (isKeepWhitespaceMode()) {
Chris Lattner0344cc72008-10-12 04:51:35 +00001048 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd66f4542008-10-12 04:19:49 +00001049 return true;
1050 }
1051
1052 BufferPtr = CurPtr;
Chris Lattnerf03b00c2008-10-12 04:15:42 +00001053 return false;
Chris Lattner4b009652007-07-25 00:24:17 +00001054 }
1055 C = *CurPtr++;
1056 }
1057
1058 // If we are returning comments as tokens, return this comment as a token.
Chris Lattner170adb12008-10-12 03:22:02 +00001059 if (inKeepCommentMode()) {
Chris Lattner0344cc72008-10-12 04:51:35 +00001060 FormTokenWithChars(Result, CurPtr, tok::comment);
Chris Lattnerf03b00c2008-10-12 04:15:42 +00001061 return true;
Chris Lattner4b009652007-07-25 00:24:17 +00001062 }
1063
1064 // It is common for the tokens immediately after a /**/ comment to be
1065 // whitespace. Instead of going through the big switch, handle it
Chris Lattner867a87b2008-10-12 04:05:48 +00001066 // efficiently now. This is safe even in KeepWhitespaceMode because we would
1067 // have already returned above with the comment as a token.
Chris Lattner4b009652007-07-25 00:24:17 +00001068 if (isHorizontalWhitespace(*CurPtr)) {
1069 Result.setFlag(Token::LeadingSpace);
1070 SkipWhitespace(Result, CurPtr+1);
Chris Lattnerf03b00c2008-10-12 04:15:42 +00001071 return false;
Chris Lattner4b009652007-07-25 00:24:17 +00001072 }
1073
1074 // Otherwise, just return so that the next character will be lexed as a token.
1075 BufferPtr = CurPtr;
1076 Result.setFlag(Token::LeadingSpace);
Chris Lattnerf03b00c2008-10-12 04:15:42 +00001077 return false;
Chris Lattner4b009652007-07-25 00:24:17 +00001078}
1079
1080//===----------------------------------------------------------------------===//
1081// Primary Lexing Entry Points
1082//===----------------------------------------------------------------------===//
1083
Chris Lattner4b009652007-07-25 00:24:17 +00001084/// ReadToEndOfLine - Read the rest of the current preprocessor line as an
1085/// uninterpreted string. This switches the lexer out of directive mode.
1086std::string Lexer::ReadToEndOfLine() {
1087 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
1088 "Must be in a preprocessing directive!");
1089 std::string Result;
1090 Token Tmp;
1091
1092 // CurPtr - Cache BufferPtr in an automatic variable.
1093 const char *CurPtr = BufferPtr;
1094 while (1) {
1095 char Char = getAndAdvanceChar(CurPtr, Tmp);
1096 switch (Char) {
1097 default:
1098 Result += Char;
1099 break;
1100 case 0: // Null.
1101 // Found end of file?
1102 if (CurPtr-1 != BufferEnd) {
1103 // Nope, normal character, continue.
1104 Result += Char;
1105 break;
1106 }
1107 // FALL THROUGH.
1108 case '\r':
1109 case '\n':
1110 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
1111 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
1112 BufferPtr = CurPtr-1;
1113
1114 // Next, lex the character, which should handle the EOM transition.
1115 Lex(Tmp);
Chris Lattnercb8e41c2007-10-09 18:02:16 +00001116 assert(Tmp.is(tok::eom) && "Unexpected token!");
Chris Lattner4b009652007-07-25 00:24:17 +00001117
1118 // Finally, we're done, return the string we found.
1119 return Result;
1120 }
1121 }
1122}
1123
1124/// LexEndOfFile - CurPtr points to the end of this file. Handle this
1125/// condition, reporting diagnostics and handling other edge cases as required.
1126/// This returns true if Result contains a token, false if PP.Lex should be
1127/// called again.
1128bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
1129 // If we hit the end of the file while parsing a preprocessor directive,
1130 // end the preprocessor directive first. The next token returned will
1131 // then be the end of file.
1132 if (ParsingPreprocessorDirective) {
1133 // Done parsing the "line".
1134 ParsingPreprocessorDirective = false;
Chris Lattner4b009652007-07-25 00:24:17 +00001135 // Update the location of token as well as BufferPtr.
Chris Lattner0344cc72008-10-12 04:51:35 +00001136 FormTokenWithChars(Result, CurPtr, tok::eom);
Chris Lattner4b009652007-07-25 00:24:17 +00001137
1138 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattner1c1bed12008-10-12 03:27:19 +00001139 SetCommentRetentionState(PP->getCommentRetentionState());
Chris Lattner4b009652007-07-25 00:24:17 +00001140 return true; // Have a token.
1141 }
1142
1143 // If we are in raw mode, return this event as an EOF token. Let the caller
1144 // that put us in raw mode handle the event.
Chris Lattnerf9c62772008-11-22 02:02:22 +00001145 if (isLexingRawMode()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001146 Result.startToken();
1147 BufferPtr = BufferEnd;
Chris Lattner0344cc72008-10-12 04:51:35 +00001148 FormTokenWithChars(Result, BufferEnd, tok::eof);
Chris Lattner4b009652007-07-25 00:24:17 +00001149 return true;
1150 }
1151
1152 // Otherwise, issue diagnostics for unterminated #if and missing newline.
1153
1154 // If we are in a #if directive, emit an error.
1155 while (!ConditionalStack.empty()) {
Chris Lattner82b474f2008-11-22 06:20:42 +00001156 Diag(ConditionalStack.back().IfLoc, diag::err_pp_unterminated_conditional);
Chris Lattner4b009652007-07-25 00:24:17 +00001157 ConditionalStack.pop_back();
1158 }
1159
Chris Lattner5c337fa2008-04-12 05:54:25 +00001160 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
1161 // a pedwarn.
1162 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r'))
Chris Lattner4b009652007-07-25 00:24:17 +00001163 Diag(BufferEnd, diag::ext_no_newline_eof);
1164
1165 BufferPtr = CurPtr;
1166
1167 // Finally, let the preprocessor handle this.
Chris Lattner342dccb2007-10-17 20:41:00 +00001168 return PP->HandleEndOfFile(Result);
Chris Lattner4b009652007-07-25 00:24:17 +00001169}
1170
1171/// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
1172/// the specified lexer will return a tok::l_paren token, 0 if it is something
1173/// else and 2 if there are no more tokens in the buffer controlled by the
1174/// lexer.
1175unsigned Lexer::isNextPPTokenLParen() {
1176 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
1177
1178 // Switch to 'skipping' mode. This will ensure that we can lex a token
1179 // without emitting diagnostics, disables macro expansion, and will cause EOF
1180 // to return an EOF token instead of popping the include stack.
1181 LexingRawMode = true;
1182
1183 // Save state that can be changed while lexing so that we can restore it.
1184 const char *TmpBufferPtr = BufferPtr;
1185
1186 Token Tok;
1187 Tok.startToken();
1188 LexTokenInternal(Tok);
1189
1190 // Restore state that may have changed.
1191 BufferPtr = TmpBufferPtr;
1192
1193 // Restore the lexer back to non-skipping mode.
1194 LexingRawMode = false;
1195
Chris Lattnercb8e41c2007-10-09 18:02:16 +00001196 if (Tok.is(tok::eof))
Chris Lattner4b009652007-07-25 00:24:17 +00001197 return 2;
Chris Lattnercb8e41c2007-10-09 18:02:16 +00001198 return Tok.is(tok::l_paren);
Chris Lattner4b009652007-07-25 00:24:17 +00001199}
1200
1201
1202/// LexTokenInternal - This implements a simple C family lexer. It is an
1203/// extremely performance critical piece of code. This assumes that the buffer
1204/// has a null character at the end of the file. Return true if an error
1205/// occurred and compilation should terminate, false if normal. This returns a
1206/// preprocessing token, not a normal token, as such, it is an internal
1207/// interface. It assumes that the Flags of result have been cleared before
1208/// calling this.
1209void Lexer::LexTokenInternal(Token &Result) {
1210LexNextToken:
1211 // New token, can't need cleaning yet.
1212 Result.clearFlag(Token::NeedsCleaning);
1213 Result.setIdentifierInfo(0);
1214
1215 // CurPtr - Cache BufferPtr in an automatic variable.
1216 const char *CurPtr = BufferPtr;
1217
1218 // Small amounts of horizontal whitespace is very common between tokens.
1219 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
1220 ++CurPtr;
1221 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
1222 ++CurPtr;
Chris Lattner867a87b2008-10-12 04:05:48 +00001223
1224 // If we are keeping whitespace and other tokens, just return what we just
1225 // skipped. The next lexer invocation will return the token after the
1226 // whitespace.
1227 if (isKeepWhitespaceMode()) {
Chris Lattner0344cc72008-10-12 04:51:35 +00001228 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner867a87b2008-10-12 04:05:48 +00001229 return;
1230 }
1231
Chris Lattner4b009652007-07-25 00:24:17 +00001232 BufferPtr = CurPtr;
1233 Result.setFlag(Token::LeadingSpace);
1234 }
1235
1236 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
1237
1238 // Read a character, advancing over it.
1239 char Char = getAndAdvanceChar(CurPtr, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001240 tok::TokenKind Kind;
1241
Chris Lattner4b009652007-07-25 00:24:17 +00001242 switch (Char) {
1243 case 0: // Null.
1244 // Found end of file?
1245 if (CurPtr-1 == BufferEnd) {
1246 // Read the PP instance variable into an automatic variable, because
1247 // LexEndOfFile will often delete 'this'.
Chris Lattner342dccb2007-10-17 20:41:00 +00001248 Preprocessor *PPCache = PP;
Chris Lattner4b009652007-07-25 00:24:17 +00001249 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
1250 return; // Got a token to return.
Chris Lattner342dccb2007-10-17 20:41:00 +00001251 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
1252 return PPCache->Lex(Result);
Chris Lattner4b009652007-07-25 00:24:17 +00001253 }
1254
Chris Lattnerf9c62772008-11-22 02:02:22 +00001255 if (!isLexingRawMode())
1256 Diag(CurPtr-1, diag::null_in_file);
Chris Lattner4b009652007-07-25 00:24:17 +00001257 Result.setFlag(Token::LeadingSpace);
Chris Lattner867a87b2008-10-12 04:05:48 +00001258 if (SkipWhitespace(Result, CurPtr))
1259 return; // KeepWhitespaceMode
1260
Chris Lattner4b009652007-07-25 00:24:17 +00001261 goto LexNextToken; // GCC isn't tail call eliminating.
1262 case '\n':
1263 case '\r':
1264 // If we are inside a preprocessor directive and we see the end of line,
1265 // we know we are done with the directive, so return an EOM token.
1266 if (ParsingPreprocessorDirective) {
1267 // Done parsing the "line".
1268 ParsingPreprocessorDirective = false;
1269
1270 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattner1c1bed12008-10-12 03:27:19 +00001271 SetCommentRetentionState(PP->getCommentRetentionState());
Chris Lattner4b009652007-07-25 00:24:17 +00001272
1273 // Since we consumed a newline, we are back at the start of a line.
1274 IsAtStartOfLine = true;
1275
Chris Lattner0344cc72008-10-12 04:51:35 +00001276 Kind = tok::eom;
Chris Lattner4b009652007-07-25 00:24:17 +00001277 break;
1278 }
1279 // The returned token is at the start of the line.
1280 Result.setFlag(Token::StartOfLine);
1281 // No leading whitespace seen so far.
1282 Result.clearFlag(Token::LeadingSpace);
Chris Lattner867a87b2008-10-12 04:05:48 +00001283
1284 if (SkipWhitespace(Result, CurPtr))
1285 return; // KeepWhitespaceMode
Chris Lattner4b009652007-07-25 00:24:17 +00001286 goto LexNextToken; // GCC isn't tail call eliminating.
1287 case ' ':
1288 case '\t':
1289 case '\f':
1290 case '\v':
1291 SkipHorizontalWhitespace:
1292 Result.setFlag(Token::LeadingSpace);
Chris Lattner867a87b2008-10-12 04:05:48 +00001293 if (SkipWhitespace(Result, CurPtr))
1294 return; // KeepWhitespaceMode
Chris Lattner4b009652007-07-25 00:24:17 +00001295
1296 SkipIgnoredUnits:
1297 CurPtr = BufferPtr;
1298
1299 // If the next token is obviously a // or /* */ comment, skip it efficiently
1300 // too (without going through the big switch stmt).
Chris Lattner170adb12008-10-12 03:22:02 +00001301 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001302 SkipBCPLComment(Result, CurPtr+2);
1303 goto SkipIgnoredUnits;
Chris Lattner170adb12008-10-12 03:22:02 +00001304 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001305 SkipBlockComment(Result, CurPtr+2);
1306 goto SkipIgnoredUnits;
1307 } else if (isHorizontalWhitespace(*CurPtr)) {
1308 goto SkipHorizontalWhitespace;
1309 }
1310 goto LexNextToken; // GCC isn't tail call eliminating.
1311
Chris Lattner0ffadcc2008-01-03 17:58:54 +00001312 // C99 6.4.4.1: Integer Constants.
1313 // C99 6.4.4.2: Floating Constants.
1314 case '0': case '1': case '2': case '3': case '4':
1315 case '5': case '6': case '7': case '8': case '9':
1316 // Notify MIOpt that we read a non-whitespace/non-comment token.
1317 MIOpt.ReadToken();
1318 return LexNumericConstant(Result, CurPtr);
1319
1320 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
Chris Lattner4b009652007-07-25 00:24:17 +00001321 // Notify MIOpt that we read a non-whitespace/non-comment token.
1322 MIOpt.ReadToken();
1323 Char = getCharAndSize(CurPtr, SizeTmp);
1324
1325 // Wide string literal.
1326 if (Char == '"')
1327 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
1328 true);
1329
1330 // Wide character constant.
1331 if (Char == '\'')
1332 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
1333 // FALL THROUGH, treating L like the start of an identifier.
1334
1335 // C99 6.4.2: Identifiers.
1336 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
1337 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
1338 case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U':
1339 case 'V': case 'W': case 'X': case 'Y': case 'Z':
1340 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
1341 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
1342 case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u':
1343 case 'v': case 'w': case 'x': case 'y': case 'z':
1344 case '_':
1345 // Notify MIOpt that we read a non-whitespace/non-comment token.
1346 MIOpt.ReadToken();
1347 return LexIdentifier(Result, CurPtr);
Chris Lattner0ffadcc2008-01-03 17:58:54 +00001348
1349 case '$': // $ in identifiers.
1350 if (Features.DollarIdents) {
Chris Lattnerf9c62772008-11-22 02:02:22 +00001351 if (!isLexingRawMode())
1352 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
Chris Lattner0ffadcc2008-01-03 17:58:54 +00001353 // Notify MIOpt that we read a non-whitespace/non-comment token.
1354 MIOpt.ReadToken();
1355 return LexIdentifier(Result, CurPtr);
1356 }
Chris Lattner4b009652007-07-25 00:24:17 +00001357
Chris Lattner0344cc72008-10-12 04:51:35 +00001358 Kind = tok::unknown;
Chris Lattner0ffadcc2008-01-03 17:58:54 +00001359 break;
Chris Lattner4b009652007-07-25 00:24:17 +00001360
1361 // C99 6.4.4: Character Constants.
1362 case '\'':
1363 // Notify MIOpt that we read a non-whitespace/non-comment token.
1364 MIOpt.ReadToken();
1365 return LexCharConstant(Result, CurPtr);
1366
1367 // C99 6.4.5: String Literals.
1368 case '"':
1369 // Notify MIOpt that we read a non-whitespace/non-comment token.
1370 MIOpt.ReadToken();
1371 return LexStringLiteral(Result, CurPtr, false);
1372
1373 // C99 6.4.6: Punctuators.
1374 case '?':
Chris Lattner0344cc72008-10-12 04:51:35 +00001375 Kind = tok::question;
Chris Lattner4b009652007-07-25 00:24:17 +00001376 break;
1377 case '[':
Chris Lattner0344cc72008-10-12 04:51:35 +00001378 Kind = tok::l_square;
Chris Lattner4b009652007-07-25 00:24:17 +00001379 break;
1380 case ']':
Chris Lattner0344cc72008-10-12 04:51:35 +00001381 Kind = tok::r_square;
Chris Lattner4b009652007-07-25 00:24:17 +00001382 break;
1383 case '(':
Chris Lattner0344cc72008-10-12 04:51:35 +00001384 Kind = tok::l_paren;
Chris Lattner4b009652007-07-25 00:24:17 +00001385 break;
1386 case ')':
Chris Lattner0344cc72008-10-12 04:51:35 +00001387 Kind = tok::r_paren;
Chris Lattner4b009652007-07-25 00:24:17 +00001388 break;
1389 case '{':
Chris Lattner0344cc72008-10-12 04:51:35 +00001390 Kind = tok::l_brace;
Chris Lattner4b009652007-07-25 00:24:17 +00001391 break;
1392 case '}':
Chris Lattner0344cc72008-10-12 04:51:35 +00001393 Kind = tok::r_brace;
Chris Lattner4b009652007-07-25 00:24:17 +00001394 break;
1395 case '.':
1396 Char = getCharAndSize(CurPtr, SizeTmp);
1397 if (Char >= '0' && Char <= '9') {
1398 // Notify MIOpt that we read a non-whitespace/non-comment token.
1399 MIOpt.ReadToken();
1400
1401 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
1402 } else if (Features.CPlusPlus && Char == '*') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001403 Kind = tok::periodstar;
Chris Lattner4b009652007-07-25 00:24:17 +00001404 CurPtr += SizeTmp;
1405 } else if (Char == '.' &&
1406 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001407 Kind = tok::ellipsis;
Chris Lattner4b009652007-07-25 00:24:17 +00001408 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1409 SizeTmp2, Result);
1410 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001411 Kind = tok::period;
Chris Lattner4b009652007-07-25 00:24:17 +00001412 }
1413 break;
1414 case '&':
1415 Char = getCharAndSize(CurPtr, SizeTmp);
1416 if (Char == '&') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001417 Kind = tok::ampamp;
Chris Lattner4b009652007-07-25 00:24:17 +00001418 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1419 } else if (Char == '=') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001420 Kind = tok::ampequal;
Chris Lattner4b009652007-07-25 00:24:17 +00001421 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1422 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001423 Kind = tok::amp;
Chris Lattner4b009652007-07-25 00:24:17 +00001424 }
1425 break;
1426 case '*':
1427 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001428 Kind = tok::starequal;
Chris Lattner4b009652007-07-25 00:24:17 +00001429 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1430 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001431 Kind = tok::star;
Chris Lattner4b009652007-07-25 00:24:17 +00001432 }
1433 break;
1434 case '+':
1435 Char = getCharAndSize(CurPtr, SizeTmp);
1436 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::plusplus;
Chris Lattner4b009652007-07-25 00:24:17 +00001439 } else if (Char == '=') {
Chris Lattner4b009652007-07-25 00:24:17 +00001440 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001441 Kind = tok::plusequal;
Chris Lattner4b009652007-07-25 00:24:17 +00001442 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001443 Kind = tok::plus;
Chris Lattner4b009652007-07-25 00:24:17 +00001444 }
1445 break;
1446 case '-':
1447 Char = getCharAndSize(CurPtr, SizeTmp);
Chris Lattner0344cc72008-10-12 04:51:35 +00001448 if (Char == '-') { // --
Chris Lattner4b009652007-07-25 00:24:17 +00001449 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001450 Kind = tok::minusminus;
Chris Lattner4b009652007-07-25 00:24:17 +00001451 } else if (Char == '>' && Features.CPlusPlus &&
Chris Lattner0344cc72008-10-12 04:51:35 +00001452 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
Chris Lattner4b009652007-07-25 00:24:17 +00001453 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1454 SizeTmp2, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001455 Kind = tok::arrowstar;
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::arrow;
1459 } else if (Char == '=') { // -=
Chris Lattner4b009652007-07-25 00:24:17 +00001460 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001461 Kind = tok::minusequal;
Chris Lattner4b009652007-07-25 00:24:17 +00001462 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001463 Kind = tok::minus;
Chris Lattner4b009652007-07-25 00:24:17 +00001464 }
1465 break;
1466 case '~':
Chris Lattner0344cc72008-10-12 04:51:35 +00001467 Kind = tok::tilde;
Chris Lattner4b009652007-07-25 00:24:17 +00001468 break;
1469 case '!':
1470 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001471 Kind = tok::exclaimequal;
Chris Lattner4b009652007-07-25 00:24:17 +00001472 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1473 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001474 Kind = tok::exclaim;
Chris Lattner4b009652007-07-25 00:24:17 +00001475 }
1476 break;
1477 case '/':
1478 // 6.4.9: Comments
1479 Char = getCharAndSize(CurPtr, SizeTmp);
1480 if (Char == '/') { // BCPL comment.
Chris Lattnerf03b00c2008-10-12 04:15:42 +00001481 if (SkipBCPLComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
1482 return; // KeepCommentMode
1483
1484 // It is common for the tokens immediately after a // comment to be
1485 // whitespace (indentation for the next line). Instead of going through
1486 // the big switch, handle it efficiently now.
1487 goto SkipIgnoredUnits;
Chris Lattner4b009652007-07-25 00:24:17 +00001488 } else if (Char == '*') { // /**/ comment.
1489 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattnerf03b00c2008-10-12 04:15:42 +00001490 return; // KeepCommentMode
1491 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattner4b009652007-07-25 00:24:17 +00001492 } else if (Char == '=') {
Chris Lattner4b009652007-07-25 00:24:17 +00001493 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001494 Kind = tok::slashequal;
Chris Lattner4b009652007-07-25 00:24:17 +00001495 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001496 Kind = tok::slash;
Chris Lattner4b009652007-07-25 00:24:17 +00001497 }
1498 break;
1499 case '%':
1500 Char = getCharAndSize(CurPtr, SizeTmp);
1501 if (Char == '=') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001502 Kind = tok::percentequal;
Chris Lattner4b009652007-07-25 00:24:17 +00001503 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1504 } else if (Features.Digraphs && Char == '>') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001505 Kind = tok::r_brace; // '%>' -> '}'
Chris Lattner4b009652007-07-25 00:24:17 +00001506 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1507 } else if (Features.Digraphs && Char == ':') {
1508 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1509 Char = getCharAndSize(CurPtr, SizeTmp);
1510 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001511 Kind = tok::hashhash; // '%:%:' -> '##'
Chris Lattner4b009652007-07-25 00:24:17 +00001512 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1513 SizeTmp2, Result);
1514 } else if (Char == '@' && Features.Microsoft) { // %:@ -> #@ -> Charize
Chris Lattner4b009652007-07-25 00:24:17 +00001515 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerf9c62772008-11-22 02:02:22 +00001516 if (!isLexingRawMode())
1517 Diag(BufferPtr, diag::charize_microsoft_ext);
Chris Lattner0344cc72008-10-12 04:51:35 +00001518 Kind = tok::hashat;
Chris Lattner4b009652007-07-25 00:24:17 +00001519 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001520 Kind = tok::hash; // '%:' -> '#'
Chris Lattner4b009652007-07-25 00:24:17 +00001521
1522 // We parsed a # character. If this occurs at the start of the line,
1523 // it's actually the start of a preprocessing directive. Callback to
1524 // the preprocessor to handle it.
1525 // FIXME: -fpreprocessed mode??
1526 if (Result.isAtStartOfLine() && !LexingRawMode) {
1527 BufferPtr = CurPtr;
Chris Lattner342dccb2007-10-17 20:41:00 +00001528 PP->HandleDirective(Result);
Chris Lattner4b009652007-07-25 00:24:17 +00001529
1530 // As an optimization, if the preprocessor didn't switch lexers, tail
1531 // recurse.
Chris Lattner342dccb2007-10-17 20:41:00 +00001532 if (PP->isCurrentLexer(this)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001533 // Start a new token. If this is a #include or something, the PP may
1534 // want us starting at the beginning of the line again. If so, set
1535 // the StartOfLine flag.
1536 if (IsAtStartOfLine) {
1537 Result.setFlag(Token::StartOfLine);
1538 IsAtStartOfLine = false;
1539 }
1540 goto LexNextToken; // GCC isn't tail call eliminating.
1541 }
1542
Chris Lattner342dccb2007-10-17 20:41:00 +00001543 return PP->Lex(Result);
Chris Lattner4b009652007-07-25 00:24:17 +00001544 }
1545 }
1546 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001547 Kind = tok::percent;
Chris Lattner4b009652007-07-25 00:24:17 +00001548 }
1549 break;
1550 case '<':
1551 Char = getCharAndSize(CurPtr, SizeTmp);
1552 if (ParsingFilename) {
1553 return LexAngledStringLiteral(Result, CurPtr+SizeTmp);
1554 } else if (Char == '<' &&
1555 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '=') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001556 Kind = tok::lesslessequal;
Chris Lattner4b009652007-07-25 00:24:17 +00001557 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1558 SizeTmp2, Result);
1559 } 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::lessless;
Chris Lattner4b009652007-07-25 00:24:17 +00001562 } else if (Char == '=') {
Chris Lattner4b009652007-07-25 00:24:17 +00001563 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001564 Kind = tok::lessequal;
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_square;
1568 } else if (Features.Digraphs && Char == '%') { // '<%' -> '{'
Chris Lattner4b009652007-07-25 00:24:17 +00001569 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001570 Kind = tok::l_brace;
Chris Lattner4b009652007-07-25 00:24:17 +00001571 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001572 Kind = tok::less;
Chris Lattner4b009652007-07-25 00:24:17 +00001573 }
1574 break;
1575 case '>':
1576 Char = getCharAndSize(CurPtr, SizeTmp);
1577 if (Char == '=') {
Chris Lattner4b009652007-07-25 00:24:17 +00001578 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001579 Kind = tok::greaterequal;
Chris Lattner4b009652007-07-25 00:24:17 +00001580 } else if (Char == '>' &&
1581 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '=') {
Chris Lattner4b009652007-07-25 00:24:17 +00001582 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1583 SizeTmp2, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001584 Kind = tok::greatergreaterequal;
Chris Lattner4b009652007-07-25 00:24:17 +00001585 } else if (Char == '>') {
Chris Lattner4b009652007-07-25 00:24:17 +00001586 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001587 Kind = tok::greatergreater;
Chris Lattner4b009652007-07-25 00:24:17 +00001588 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001589 Kind = tok::greater;
Chris Lattner4b009652007-07-25 00:24:17 +00001590 }
1591 break;
1592 case '^':
1593 Char = getCharAndSize(CurPtr, SizeTmp);
1594 if (Char == '=') {
Chris Lattner4b009652007-07-25 00:24:17 +00001595 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001596 Kind = tok::caretequal;
Chris Lattner4b009652007-07-25 00:24:17 +00001597 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001598 Kind = tok::caret;
Chris Lattner4b009652007-07-25 00:24:17 +00001599 }
1600 break;
1601 case '|':
1602 Char = getCharAndSize(CurPtr, SizeTmp);
1603 if (Char == '=') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001604 Kind = tok::pipeequal;
Chris Lattner4b009652007-07-25 00:24:17 +00001605 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1606 } else if (Char == '|') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001607 Kind = tok::pipepipe;
Chris Lattner4b009652007-07-25 00:24:17 +00001608 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1609 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001610 Kind = tok::pipe;
Chris Lattner4b009652007-07-25 00:24:17 +00001611 }
1612 break;
1613 case ':':
1614 Char = getCharAndSize(CurPtr, SizeTmp);
1615 if (Features.Digraphs && Char == '>') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001616 Kind = tok::r_square; // ':>' -> ']'
Chris Lattner4b009652007-07-25 00:24:17 +00001617 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1618 } else if (Features.CPlusPlus && Char == ':') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001619 Kind = tok::coloncolon;
Chris Lattner4b009652007-07-25 00:24:17 +00001620 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1621 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001622 Kind = tok::colon;
Chris Lattner4b009652007-07-25 00:24:17 +00001623 }
1624 break;
1625 case ';':
Chris Lattner0344cc72008-10-12 04:51:35 +00001626 Kind = tok::semi;
Chris Lattner4b009652007-07-25 00:24:17 +00001627 break;
1628 case '=':
1629 Char = getCharAndSize(CurPtr, SizeTmp);
1630 if (Char == '=') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001631 Kind = tok::equalequal;
Chris Lattner4b009652007-07-25 00:24:17 +00001632 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1633 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001634 Kind = tok::equal;
Chris Lattner4b009652007-07-25 00:24:17 +00001635 }
1636 break;
1637 case ',':
Chris Lattner0344cc72008-10-12 04:51:35 +00001638 Kind = tok::comma;
Chris Lattner4b009652007-07-25 00:24:17 +00001639 break;
1640 case '#':
1641 Char = getCharAndSize(CurPtr, SizeTmp);
1642 if (Char == '#') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001643 Kind = tok::hashhash;
Chris Lattner4b009652007-07-25 00:24:17 +00001644 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1645 } else if (Char == '@' && Features.Microsoft) { // #@ -> Charize
Chris Lattner0344cc72008-10-12 04:51:35 +00001646 Kind = tok::hashat;
Chris Lattnerf9c62772008-11-22 02:02:22 +00001647 if (!isLexingRawMode())
1648 Diag(BufferPtr, diag::charize_microsoft_ext);
Chris Lattner4b009652007-07-25 00:24:17 +00001649 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1650 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001651 Kind = tok::hash;
Chris Lattner4b009652007-07-25 00:24:17 +00001652 // We parsed a # character. If this occurs at the start of the line,
1653 // it's actually the start of a preprocessing directive. Callback to
1654 // the preprocessor to handle it.
1655 // FIXME: -fpreprocessed mode??
1656 if (Result.isAtStartOfLine() && !LexingRawMode) {
1657 BufferPtr = CurPtr;
Chris Lattner342dccb2007-10-17 20:41:00 +00001658 PP->HandleDirective(Result);
Chris Lattner4b009652007-07-25 00:24:17 +00001659
1660 // As an optimization, if the preprocessor didn't switch lexers, tail
1661 // recurse.
Chris Lattner342dccb2007-10-17 20:41:00 +00001662 if (PP->isCurrentLexer(this)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001663 // Start a new token. If this is a #include or something, the PP may
1664 // want us starting at the beginning of the line again. If so, set
1665 // the StartOfLine flag.
1666 if (IsAtStartOfLine) {
1667 Result.setFlag(Token::StartOfLine);
1668 IsAtStartOfLine = false;
1669 }
1670 goto LexNextToken; // GCC isn't tail call eliminating.
1671 }
Chris Lattner342dccb2007-10-17 20:41:00 +00001672 return PP->Lex(Result);
Chris Lattner4b009652007-07-25 00:24:17 +00001673 }
1674 }
1675 break;
1676
Chris Lattner0ffadcc2008-01-03 17:58:54 +00001677 case '@':
1678 // Objective C support.
1679 if (CurPtr[-1] == '@' && Features.ObjC1)
Chris Lattner0344cc72008-10-12 04:51:35 +00001680 Kind = tok::at;
Chris Lattner0ffadcc2008-01-03 17:58:54 +00001681 else
Chris Lattner0344cc72008-10-12 04:51:35 +00001682 Kind = tok::unknown;
Chris Lattner0ffadcc2008-01-03 17:58:54 +00001683 break;
1684
Chris Lattner4b009652007-07-25 00:24:17 +00001685 case '\\':
1686 // FIXME: UCN's.
1687 // FALL THROUGH.
1688 default:
Chris Lattner0344cc72008-10-12 04:51:35 +00001689 Kind = tok::unknown;
Chris Lattner4b009652007-07-25 00:24:17 +00001690 break;
1691 }
1692
1693 // Notify MIOpt that we read a non-whitespace/non-comment token.
1694 MIOpt.ReadToken();
1695
1696 // Update the location of token as well as BufferPtr.
Chris Lattner0344cc72008-10-12 04:51:35 +00001697 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner4b009652007-07-25 00:24:17 +00001698}