blob: 65956cb8b7efc94e2773691d90da7d13d5225d51 [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)
Chris Lattner342dccb2007-10-17 20:41:00 +000066 : FileLoc(fileloc), PP(&pp), Features(pp.getLangOptions()) {
Chris Lattner4b009652007-07-25 00:24:17 +000067
Chris Lattner342dccb2007-10-17 20:41:00 +000068 SourceManager &SourceMgr = PP->getSourceManager();
Chris Lattner4b009652007-07-25 00:24:17 +000069 unsigned InputFileID = SourceMgr.getPhysicalLoc(FileLoc).getFileID();
70 const llvm::MemoryBuffer *InputFile = SourceMgr.getBuffer(InputFileID);
71
72 Is_PragmaLexer = false;
Chris Lattner4b009652007-07-25 00:24:17 +000073 InitCharacterInfo();
74
75 // BufferStart must always be InputFile->getBufferStart().
76 BufferStart = InputFile->getBufferStart();
77
78 // BufferPtr and BufferEnd can start out somewhere inside the current buffer.
79 // If unspecified, they starts at the start/end of the buffer.
80 BufferPtr = BufStart ? BufStart : BufferStart;
81 BufferEnd = BufEnd ? BufEnd : InputFile->getBufferEnd();
82
83 assert(BufferEnd[0] == 0 &&
84 "We assume that the input buffer has a null character at the end"
85 " to simplify lexing!");
86
87 // Start of the file is a start of line.
88 IsAtStartOfLine = true;
89
90 // We are not after parsing a #.
91 ParsingPreprocessorDirective = false;
92
93 // We are not after parsing #include.
94 ParsingFilename = false;
95
96 // We are not in raw mode. Raw mode disables diagnostics and interpretation
97 // of tokens (e.g. identifiers, thus disabling macro expansion). It is used
98 // to quickly lex the tokens of the buffer, e.g. when handling a "#if 0" block
99 // or otherwise skipping over tokens.
100 LexingRawMode = false;
101
Chris Lattner867a87b2008-10-12 04:05:48 +0000102 // Default to keeping comments if the preprocessor wants them.
103 ExtendedTokenMode = 0;
Chris Lattner1c1bed12008-10-12 03:27:19 +0000104 SetCommentRetentionState(PP->getCommentRetentionState());
Chris Lattner4b009652007-07-25 00:24:17 +0000105}
106
Chris Lattner342dccb2007-10-17 20:41:00 +0000107/// Lexer constructor - Create a new raw lexer object. This object is only
Chris Lattner0b5892e2008-10-12 01:15:46 +0000108/// suitable for calls to 'LexRawToken'. This lexer assumes that the text
109/// range will outlive it, so it doesn't take ownership of it.
Chris Lattner342dccb2007-10-17 20:41:00 +0000110Lexer::Lexer(SourceLocation fileloc, const LangOptions &features,
Chris Lattner0b5892e2008-10-12 01:15:46 +0000111 const char *BufStart, const char *BufEnd,
112 const llvm::MemoryBuffer *FromFile)
Chris Lattner342dccb2007-10-17 20:41:00 +0000113 : FileLoc(fileloc), PP(0), Features(features) {
114 Is_PragmaLexer = false;
115 InitCharacterInfo();
116
Chris Lattner88ad2ac2008-10-12 01:23:27 +0000117 // If a MemoryBuffer was specified, use its start as BufferStart. This affects
118 // the source location objects produced by this lexer.
Chris Lattner0b5892e2008-10-12 01:15:46 +0000119 BufferStart = FromFile ? FromFile->getBufferStart() : BufStart;
Chris Lattner342dccb2007-10-17 20:41:00 +0000120 BufferPtr = BufStart;
121 BufferEnd = BufEnd;
122
123 assert(BufferEnd[0] == 0 &&
124 "We assume that the input buffer has a null character at the end"
125 " to simplify lexing!");
126
127 // Start of the file is a start of line.
128 IsAtStartOfLine = true;
129
130 // We are not after parsing a #.
131 ParsingPreprocessorDirective = false;
132
133 // We are not after parsing #include.
134 ParsingFilename = false;
135
136 // We *are* in raw mode.
137 LexingRawMode = true;
138
Chris Lattnercb8014e2008-10-12 01:34:51 +0000139 // Default to not keeping comments in raw mode.
Chris Lattner867a87b2008-10-12 04:05:48 +0000140 ExtendedTokenMode = 0;
Chris Lattner342dccb2007-10-17 20:41:00 +0000141}
142
143
Chris Lattner4b009652007-07-25 00:24:17 +0000144/// Stringify - Convert the specified string into a C string, with surrounding
145/// ""'s, and with escaped \ and " characters.
146std::string Lexer::Stringify(const std::string &Str, bool Charify) {
147 std::string Result = Str;
148 char Quote = Charify ? '\'' : '"';
149 for (unsigned i = 0, e = Result.size(); i != e; ++i) {
150 if (Result[i] == '\\' || Result[i] == Quote) {
151 Result.insert(Result.begin()+i, '\\');
152 ++i; ++e;
153 }
154 }
155 return Result;
156}
157
158/// Stringify - Convert the specified string into a C string by escaping '\'
159/// and " characters. This does not add surrounding ""'s to the string.
160void Lexer::Stringify(llvm::SmallVectorImpl<char> &Str) {
161 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
162 if (Str[i] == '\\' || Str[i] == '"') {
163 Str.insert(Str.begin()+i, '\\');
164 ++i; ++e;
165 }
166 }
167}
168
169
Chris Lattner761d76b2007-10-17 21:18:47 +0000170/// MeasureTokenLength - Relex the token at the specified location and return
171/// its length in bytes in the input file. If the token needs cleaning (e.g.
172/// includes a trigraph or an escaped newline) then this count includes bytes
173/// that are part of that.
174unsigned Lexer::MeasureTokenLength(SourceLocation Loc,
175 const SourceManager &SM) {
176 // If this comes from a macro expansion, we really do want the macro name, not
177 // the token this macro expanded to.
178 Loc = SM.getLogicalLoc(Loc);
179
180 const char *StrData = SM.getCharacterData(Loc);
181
182 // TODO: this could be special cased for common tokens like identifiers, ')',
183 // etc to make this faster, if it mattered. Just look at StrData[0] to handle
184 // all obviously single-char tokens. This could use
185 // Lexer::isObviouslySimpleCharacter for example to handle identifiers or
186 // something.
187
188
189 const char *BufEnd = SM.getBufferData(Loc.getFileID()).second;
190
191 // Create a langops struct and enable trigraphs. This is sufficient for
192 // measuring tokens.
193 LangOptions LangOpts;
194 LangOpts.Trigraphs = true;
195
196 // Create a lexer starting at the beginning of this token.
197 Lexer TheLexer(Loc, LangOpts, StrData, BufEnd);
198 Token TheTok;
Chris Lattner0b5892e2008-10-12 01:15:46 +0000199 TheLexer.LexFromRawLexer(TheTok);
Chris Lattner761d76b2007-10-17 21:18:47 +0000200 return TheTok.getLength();
201}
202
Chris Lattner4b009652007-07-25 00:24:17 +0000203//===----------------------------------------------------------------------===//
204// Character information.
205//===----------------------------------------------------------------------===//
206
207static unsigned char CharInfo[256];
208
209enum {
210 CHAR_HORZ_WS = 0x01, // ' ', '\t', '\f', '\v'. Note, no '\0'
211 CHAR_VERT_WS = 0x02, // '\r', '\n'
212 CHAR_LETTER = 0x04, // a-z,A-Z
213 CHAR_NUMBER = 0x08, // 0-9
214 CHAR_UNDER = 0x10, // _
215 CHAR_PERIOD = 0x20 // .
216};
217
218static void InitCharacterInfo() {
219 static bool isInited = false;
220 if (isInited) return;
221 isInited = true;
222
223 // Intiialize the CharInfo table.
224 // TODO: statically initialize this.
225 CharInfo[(int)' '] = CharInfo[(int)'\t'] =
226 CharInfo[(int)'\f'] = CharInfo[(int)'\v'] = CHAR_HORZ_WS;
227 CharInfo[(int)'\n'] = CharInfo[(int)'\r'] = CHAR_VERT_WS;
228
229 CharInfo[(int)'_'] = CHAR_UNDER;
230 CharInfo[(int)'.'] = CHAR_PERIOD;
231 for (unsigned i = 'a'; i <= 'z'; ++i)
232 CharInfo[i] = CharInfo[i+'A'-'a'] = CHAR_LETTER;
233 for (unsigned i = '0'; i <= '9'; ++i)
234 CharInfo[i] = CHAR_NUMBER;
235}
236
237/// isIdentifierBody - Return true if this is the body character of an
238/// identifier, which is [a-zA-Z0-9_].
239static inline bool isIdentifierBody(unsigned char c) {
Hartmut Kaiserc62f6b92007-10-18 12:47:01 +0000240 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER)) ? true : false;
Chris Lattner4b009652007-07-25 00:24:17 +0000241}
242
243/// isHorizontalWhitespace - Return true if this character is horizontal
244/// whitespace: ' ', '\t', '\f', '\v'. Note that this returns false for '\0'.
245static inline bool isHorizontalWhitespace(unsigned char c) {
Hartmut Kaiserc62f6b92007-10-18 12:47:01 +0000246 return (CharInfo[c] & CHAR_HORZ_WS) ? true : false;
Chris Lattner4b009652007-07-25 00:24:17 +0000247}
248
249/// isWhitespace - Return true if this character is horizontal or vertical
250/// whitespace: ' ', '\t', '\f', '\v', '\n', '\r'. Note that this returns false
251/// for '\0'.
252static inline bool isWhitespace(unsigned char c) {
Hartmut Kaiserc62f6b92007-10-18 12:47:01 +0000253 return (CharInfo[c] & (CHAR_HORZ_WS|CHAR_VERT_WS)) ? true : false;
Chris Lattner4b009652007-07-25 00:24:17 +0000254}
255
256/// isNumberBody - Return true if this is the body character of an
257/// preprocessing number, which is [a-zA-Z0-9_.].
258static inline bool isNumberBody(unsigned char c) {
Hartmut Kaiserc62f6b92007-10-18 12:47:01 +0000259 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER|CHAR_PERIOD)) ?
260 true : false;
Chris Lattner4b009652007-07-25 00:24:17 +0000261}
262
263
264//===----------------------------------------------------------------------===//
265// Diagnostics forwarding code.
266//===----------------------------------------------------------------------===//
267
268/// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
269/// lexer buffer was all instantiated at a single point, perform the mapping.
270/// This is currently only used for _Pragma implementation, so it is the slow
271/// path of the hot getSourceLocation method. Do not allow it to be inlined.
272static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
273 SourceLocation FileLoc,
274 unsigned CharNo) DISABLE_INLINE;
275static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
276 SourceLocation FileLoc,
277 unsigned CharNo) {
278 // Otherwise, we're lexing "mapped tokens". This is used for things like
279 // _Pragma handling. Combine the instantiation location of FileLoc with the
280 // physical location.
281 SourceManager &SourceMgr = PP.getSourceManager();
282
283 // Create a new SLoc which is expanded from logical(FileLoc) but whose
284 // characters come from phys(FileLoc)+Offset.
285 SourceLocation VirtLoc = SourceMgr.getLogicalLoc(FileLoc);
286 SourceLocation PhysLoc = SourceMgr.getPhysicalLoc(FileLoc);
287 PhysLoc = SourceLocation::getFileLoc(PhysLoc.getFileID(), CharNo);
288 return SourceMgr.getInstantiationLoc(PhysLoc, VirtLoc);
289}
290
291/// getSourceLocation - Return a source location identifier for the specified
292/// offset in the current file.
293SourceLocation Lexer::getSourceLocation(const char *Loc) const {
294 assert(Loc >= BufferStart && Loc <= BufferEnd &&
295 "Location out of range for this buffer!");
296
297 // In the normal case, we're just lexing from a simple file buffer, return
298 // the file id from FileLoc with the offset specified.
299 unsigned CharNo = Loc-BufferStart;
300 if (FileLoc.isFileID())
301 return SourceLocation::getFileLoc(FileLoc.getFileID(), CharNo);
302
Chris Lattner342dccb2007-10-17 20:41:00 +0000303 assert(PP && "This doesn't work on raw lexers");
304 return GetMappedTokenLoc(*PP, FileLoc, CharNo);
Chris Lattner4b009652007-07-25 00:24:17 +0000305}
306
307/// Diag - Forwarding function for diagnostics. This translate a source
308/// position in the current buffer into a SourceLocation object for rendering.
309void Lexer::Diag(const char *Loc, unsigned DiagID,
310 const std::string &Msg) const {
Chris Lattner4478db92007-11-30 22:53:43 +0000311 if (LexingRawMode && Diagnostic::isBuiltinNoteWarningOrExtension(DiagID))
Chris Lattner4b009652007-07-25 00:24:17 +0000312 return;
Chris Lattner342dccb2007-10-17 20:41:00 +0000313 PP->Diag(getSourceLocation(Loc), DiagID, Msg);
Chris Lattner4b009652007-07-25 00:24:17 +0000314}
315void Lexer::Diag(SourceLocation Loc, unsigned DiagID,
316 const std::string &Msg) const {
Chris Lattner4478db92007-11-30 22:53:43 +0000317 if (LexingRawMode && Diagnostic::isBuiltinNoteWarningOrExtension(DiagID))
Chris Lattner4b009652007-07-25 00:24:17 +0000318 return;
Chris Lattner342dccb2007-10-17 20:41:00 +0000319 PP->Diag(Loc, DiagID, Msg);
Chris Lattner4b009652007-07-25 00:24:17 +0000320}
321
322
323//===----------------------------------------------------------------------===//
324// Trigraph and Escaped Newline Handling Code.
325//===----------------------------------------------------------------------===//
326
327/// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
328/// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
329static char GetTrigraphCharForLetter(char Letter) {
330 switch (Letter) {
331 default: return 0;
332 case '=': return '#';
333 case ')': return ']';
334 case '(': return '[';
335 case '!': return '|';
336 case '\'': return '^';
337 case '>': return '}';
338 case '/': return '\\';
339 case '<': return '{';
340 case '-': return '~';
341 }
342}
343
344/// DecodeTrigraphChar - If the specified character is a legal trigraph when
345/// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
346/// return the result character. Finally, emit a warning about trigraph use
347/// whether trigraphs are enabled or not.
348static char DecodeTrigraphChar(const char *CP, Lexer *L) {
349 char Res = GetTrigraphCharForLetter(*CP);
350 if (Res && L) {
351 if (!L->getFeatures().Trigraphs) {
352 L->Diag(CP-2, diag::trigraph_ignored);
353 return 0;
354 } else {
355 L->Diag(CP-2, diag::trigraph_converted, std::string()+Res);
356 }
357 }
358 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.
398 if (SizeTmp != 1 && Tok)
399 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;
518 FormTokenWithChars(Result, CurPtr);
519 Result.setKind(tok::identifier);
520
521 // If we are in raw mode, return this identifier raw. There is no need to
522 // look up identifier information or attempt to macro expand it.
523 if (LexingRawMode) return;
524
525 // Fill in Result.IdentifierInfo, looking up the identifier in the
526 // identifier table.
Chris Lattner342dccb2007-10-17 20:41:00 +0000527 PP->LookUpIdentifierInfo(Result, IdStart);
Chris Lattner4b009652007-07-25 00:24:17 +0000528
529 // Finally, now that we know we have an identifier, pass this off to the
530 // preprocessor, which may macro expand it or something.
Chris Lattner342dccb2007-10-17 20:41:00 +0000531 return PP->HandleIdentifier(Result);
Chris Lattner4b009652007-07-25 00:24:17 +0000532 }
533
534 // Otherwise, $,\,? in identifier found. Enter slower path.
535
536 C = getCharAndSize(CurPtr, Size);
537 while (1) {
538 if (C == '$') {
539 // If we hit a $ and they are not supported in identifiers, we are done.
540 if (!Features.DollarIdents) goto FinishIdentifier;
541
542 // Otherwise, emit a diagnostic and continue.
543 Diag(CurPtr, diag::ext_dollar_in_identifier);
544 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
586 Result.setKind(tok::numeric_constant);
587
588 // Update the location of token as well as BufferPtr.
589 FormTokenWithChars(Result, CurPtr);
590}
591
592/// LexStringLiteral - Lex the remainder of a string literal, after having lexed
593/// either " or L".
Chris Lattner867a87b2008-10-12 04:05:48 +0000594void Lexer::LexStringLiteral(Token &Result, const char *CurPtr, bool Wide) {
Chris Lattner4b009652007-07-25 00:24:17 +0000595 const char *NulCharacter = 0; // Does this string contain the \0 character?
596
597 char C = getAndAdvanceChar(CurPtr, Result);
598 while (C != '"') {
599 // Skip escaped characters.
600 if (C == '\\') {
601 // Skip the escaped character.
602 C = getAndAdvanceChar(CurPtr, Result);
603 } else if (C == '\n' || C == '\r' || // Newline.
604 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
605 if (!LexingRawMode) Diag(BufferPtr, diag::err_unterminated_string);
606 Result.setKind(tok::unknown);
607 FormTokenWithChars(Result, CurPtr-1);
608 return;
609 } else if (C == 0) {
610 NulCharacter = CurPtr-1;
611 }
612 C = getAndAdvanceChar(CurPtr, Result);
613 }
614
615 // If a nul character existed in the string, warn about it.
616 if (NulCharacter) Diag(NulCharacter, diag::null_in_string);
617
618 Result.setKind(Wide ? tok::wide_string_literal : tok::string_literal);
619
620 // Update the location of the token as well as the BufferPtr instance var.
621 FormTokenWithChars(Result, CurPtr);
622}
623
624/// LexAngledStringLiteral - Lex the remainder of an angled string literal,
625/// after having lexed the '<' character. This is used for #include filenames.
626void Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
627 const char *NulCharacter = 0; // Does this string contain the \0 character?
628
629 char C = getAndAdvanceChar(CurPtr, Result);
630 while (C != '>') {
631 // Skip escaped characters.
632 if (C == '\\') {
633 // Skip the escaped character.
634 C = getAndAdvanceChar(CurPtr, Result);
635 } else if (C == '\n' || C == '\r' || // Newline.
636 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
637 if (!LexingRawMode) Diag(BufferPtr, diag::err_unterminated_string);
638 Result.setKind(tok::unknown);
639 FormTokenWithChars(Result, CurPtr-1);
640 return;
641 } else if (C == 0) {
642 NulCharacter = CurPtr-1;
643 }
644 C = getAndAdvanceChar(CurPtr, Result);
645 }
646
647 // If a nul character existed in the string, warn about it.
648 if (NulCharacter) Diag(NulCharacter, diag::null_in_string);
649
650 Result.setKind(tok::angle_string_literal);
651
652 // Update the location of token as well as BufferPtr.
653 FormTokenWithChars(Result, CurPtr);
654}
655
656
657/// LexCharConstant - Lex the remainder of a character constant, after having
658/// lexed either ' or L'.
659void Lexer::LexCharConstant(Token &Result, const char *CurPtr) {
660 const char *NulCharacter = 0; // Does this character contain the \0 character?
661
662 // Handle the common case of 'x' and '\y' efficiently.
663 char C = getAndAdvanceChar(CurPtr, Result);
664 if (C == '\'') {
665 if (!LexingRawMode) Diag(BufferPtr, diag::err_empty_character);
666 Result.setKind(tok::unknown);
667 FormTokenWithChars(Result, CurPtr);
668 return;
669 } else if (C == '\\') {
670 // Skip the escaped character.
671 // FIXME: UCN's.
672 C = getAndAdvanceChar(CurPtr, Result);
673 }
674
675 if (C && C != '\n' && C != '\r' && CurPtr[0] == '\'') {
676 ++CurPtr;
677 } else {
678 // Fall back on generic code for embedded nulls, newlines, wide chars.
679 do {
680 // Skip escaped characters.
681 if (C == '\\') {
682 // Skip the escaped character.
683 C = getAndAdvanceChar(CurPtr, Result);
684 } else if (C == '\n' || C == '\r' || // Newline.
685 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
686 if (!LexingRawMode) Diag(BufferPtr, diag::err_unterminated_char);
687 Result.setKind(tok::unknown);
688 FormTokenWithChars(Result, CurPtr-1);
689 return;
690 } else if (C == 0) {
691 NulCharacter = CurPtr-1;
692 }
693 C = getAndAdvanceChar(CurPtr, Result);
694 } while (C != '\'');
695 }
696
697 if (NulCharacter) Diag(NulCharacter, diag::null_in_char);
698
699 Result.setKind(tok::char_constant);
700
701 // Update the location of token as well as BufferPtr.
702 FormTokenWithChars(Result, CurPtr);
703}
704
705/// SkipWhitespace - Efficiently skip over a series of whitespace characters.
706/// Update BufferPtr to point to the next non-whitespace character and return.
Chris Lattner867a87b2008-10-12 04:05:48 +0000707///
708/// This method forms a token and returns true if KeepWhitespaceMode is enabled.
709///
710bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr) {
Chris Lattner4b009652007-07-25 00:24:17 +0000711 // Whitespace - Skip it, then return the token after the whitespace.
712 unsigned char Char = *CurPtr; // Skip consequtive spaces efficiently.
713 while (1) {
714 // Skip horizontal whitespace very aggressively.
715 while (isHorizontalWhitespace(Char))
716 Char = *++CurPtr;
717
718 // Otherwise if we something other than whitespace, we're done.
719 if (Char != '\n' && Char != '\r')
720 break;
721
722 if (ParsingPreprocessorDirective) {
723 // End of preprocessor directive line, let LexTokenInternal handle this.
724 BufferPtr = CurPtr;
Chris Lattner867a87b2008-10-12 04:05:48 +0000725 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000726 }
727
728 // ok, but handle newline.
729 // The returned token is at the start of the line.
730 Result.setFlag(Token::StartOfLine);
731 // No leading whitespace seen so far.
732 Result.clearFlag(Token::LeadingSpace);
733 Char = *++CurPtr;
734 }
735
736 // If this isn't immediately after a newline, there is leading space.
737 char PrevChar = CurPtr[-1];
738 if (PrevChar != '\n' && PrevChar != '\r')
739 Result.setFlag(Token::LeadingSpace);
740
Chris Lattner867a87b2008-10-12 04:05:48 +0000741 // If the client wants us to return whitespace, return it now.
742 if (isKeepWhitespaceMode()) {
743 Result.setKind(tok::unknown);
744 FormTokenWithChars(Result, CurPtr);
745 return true;
746 }
747
Chris Lattner4b009652007-07-25 00:24:17 +0000748 BufferPtr = CurPtr;
Chris Lattner867a87b2008-10-12 04:05:48 +0000749 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000750}
751
752// SkipBCPLComment - We have just read the // characters from input. Skip until
753// we find the newline character thats terminate the comment. Then update
754/// BufferPtr and return.
755bool Lexer::SkipBCPLComment(Token &Result, const char *CurPtr) {
756 // If BCPL comments aren't explicitly enabled for this language, emit an
757 // extension warning.
758 if (!Features.BCPLComment) {
759 Diag(BufferPtr, diag::ext_bcpl_comment);
760
761 // Mark them enabled so we only emit one warning for this translation
762 // unit.
763 Features.BCPLComment = true;
764 }
765
766 // Scan over the body of the comment. The common case, when scanning, is that
767 // the comment contains normal ascii characters with nothing interesting in
768 // them. As such, optimize for this case with the inner loop.
769 char C;
770 do {
771 C = *CurPtr;
772 // FIXME: Speedup BCPL comment lexing. Just scan for a \n or \r character.
773 // If we find a \n character, scan backwards, checking to see if it's an
774 // escaped newline, like we do for block comments.
775
776 // Skip over characters in the fast loop.
777 while (C != 0 && // Potentially EOF.
778 C != '\\' && // Potentially escaped newline.
779 C != '?' && // Potentially trigraph.
780 C != '\n' && C != '\r') // Newline or DOS-style newline.
781 C = *++CurPtr;
782
783 // If this is a newline, we're done.
784 if (C == '\n' || C == '\r')
785 break; // Found the newline? Break out!
786
787 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
788 // properly decode the character.
789 const char *OldPtr = CurPtr;
790 C = getAndAdvanceChar(CurPtr, Result);
791
792 // If we read multiple characters, and one of those characters was a \r or
793 // \n, then we had an escaped newline within the comment. Emit diagnostic
794 // unless the next line is also a // comment.
795 if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') {
796 for (; OldPtr != CurPtr; ++OldPtr)
797 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
798 // Okay, we found a // comment that ends in a newline, if the next
799 // line is also a // comment, but has spaces, don't emit a diagnostic.
800 if (isspace(C)) {
801 const char *ForwardPtr = CurPtr;
802 while (isspace(*ForwardPtr)) // Skip whitespace.
803 ++ForwardPtr;
804 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
805 break;
806 }
807
808 Diag(OldPtr-1, diag::ext_multi_line_bcpl_comment);
809 break;
810 }
811 }
812
813 if (CurPtr == BufferEnd+1) { --CurPtr; break; }
814 } while (C != '\n' && C != '\r');
815
816 // Found but did not consume the newline.
817
818 // If we are returning comments as tokens, return this comment as a token.
Chris Lattner170adb12008-10-12 03:22:02 +0000819 if (inKeepCommentMode())
Chris Lattner4b009652007-07-25 00:24:17 +0000820 return SaveBCPLComment(Result, CurPtr);
821
822 // If we are inside a preprocessor directive and we see the end of line,
823 // return immediately, so that the lexer can return this as an EOM token.
824 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
825 BufferPtr = CurPtr;
826 return true;
827 }
828
829 // Otherwise, eat the \n character. We don't care if this is a \n\r or
Chris Lattner43d38202008-10-12 00:23:07 +0000830 // \r\n sequence. This is an efficiency hack (because we know the \n can't
Chris Lattner867a87b2008-10-12 04:05:48 +0000831 // contribute to another token), it isn't needed for correctness. Note that
832 // this is ok even in KeepWhitespaceMode, because we would have returned the
833 /// comment above in that mode.
Chris Lattner4b009652007-07-25 00:24:17 +0000834 ++CurPtr;
835
836 // The next returned token is at the start of the line.
837 Result.setFlag(Token::StartOfLine);
838 // No leading whitespace seen so far.
839 Result.clearFlag(Token::LeadingSpace);
840 BufferPtr = CurPtr;
841 return true;
842}
843
844/// SaveBCPLComment - If in save-comment mode, package up this BCPL comment in
845/// an appropriate way and return it.
846bool Lexer::SaveBCPLComment(Token &Result, const char *CurPtr) {
847 Result.setKind(tok::comment);
Chris Lattner4b009652007-07-25 00:24:17 +0000848
Chris Lattner867a87b2008-10-12 04:05:48 +0000849 if (!ParsingPreprocessorDirective) {
850 // If we're not in a preprocessor directive, just return the // comment
851 // directly.
852 FormTokenWithChars(Result, CurPtr);
853 } else {
854 // If this BCPL-style comment is in a macro definition, transmogrify it into
855 // a C-style block comment.
856 BufferPtr = CurPtr;
857
Chris Lattner342dccb2007-10-17 20:41:00 +0000858 std::string Spelling = PP->getSpelling(Result);
Chris Lattner4b009652007-07-25 00:24:17 +0000859 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not bcpl comment?");
860 Spelling[1] = '*'; // Change prefix to "/*".
861 Spelling += "*/"; // add suffix.
862
Chris Lattner342dccb2007-10-17 20:41:00 +0000863 Result.setLocation(PP->CreateString(&Spelling[0], Spelling.size(),
864 Result.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000865 Result.setLength(Spelling.size());
866 }
867 return false;
868}
869
870/// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
871/// character (either \n or \r) is part of an escaped newline sequence. Issue a
872/// diagnostic if so. We know that the is inside of a block comment.
873static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
874 Lexer *L) {
875 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
876
877 // Back up off the newline.
878 --CurPtr;
879
880 // If this is a two-character newline sequence, skip the other character.
881 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
882 // \n\n or \r\r -> not escaped newline.
883 if (CurPtr[0] == CurPtr[1])
884 return false;
885 // \n\r or \r\n -> skip the newline.
886 --CurPtr;
887 }
888
889 // If we have horizontal whitespace, skip over it. We allow whitespace
890 // between the slash and newline.
891 bool HasSpace = false;
892 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
893 --CurPtr;
894 HasSpace = true;
895 }
896
897 // If we have a slash, we know this is an escaped newline.
898 if (*CurPtr == '\\') {
899 if (CurPtr[-1] != '*') return false;
900 } else {
901 // It isn't a slash, is it the ?? / trigraph?
902 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
903 CurPtr[-3] != '*')
904 return false;
905
906 // This is the trigraph ending the comment. Emit a stern warning!
907 CurPtr -= 2;
908
909 // If no trigraphs are enabled, warn that we ignored this trigraph and
910 // ignore this * character.
911 if (!L->getFeatures().Trigraphs) {
912 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
913 return false;
914 }
915 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
916 }
917
918 // Warn about having an escaped newline between the */ characters.
919 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
920
921 // If there was space between the backslash and newline, warn about it.
922 if (HasSpace) L->Diag(CurPtr, diag::backslash_newline_space);
923
924 return true;
925}
926
927#ifdef __SSE2__
928#include <emmintrin.h>
929#elif __ALTIVEC__
930#include <altivec.h>
931#undef bool
932#endif
933
934/// SkipBlockComment - We have just read the /* characters from input. Read
935/// until we find the */ characters that terminate the comment. Note that we
936/// don't bother decoding trigraphs or escaped newlines in block comments,
937/// because they cannot cause the comment to end. The only thing that can
938/// happen is the comment could end with an escaped newline between the */ end
939/// of comment.
940bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr) {
941 // Scan one character past where we should, looking for a '/' character. Once
942 // we find it, check to see if it was preceeded by a *. This common
943 // optimization helps people who like to put a lot of * characters in their
944 // comments.
945
946 // The first character we get with newlines and trigraphs skipped to handle
947 // the degenerate /*/ case below correctly if the * has an escaped newline
948 // after it.
949 unsigned CharSize;
950 unsigned char C = getCharAndSize(CurPtr, CharSize);
951 CurPtr += CharSize;
952 if (C == 0 && CurPtr == BufferEnd+1) {
Chris Lattnere5eca952008-10-12 01:31:51 +0000953 if (!LexingRawMode)
954 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner4b009652007-07-25 00:24:17 +0000955 BufferPtr = CurPtr-1;
956 return true;
957 }
958
959 // Check to see if the first character after the '/*' is another /. If so,
960 // then this slash does not end the block comment, it is part of it.
961 if (C == '/')
962 C = *CurPtr++;
963
964 while (1) {
965 // Skip over all non-interesting characters until we find end of buffer or a
966 // (probably ending) '/' character.
967 if (CurPtr + 24 < BufferEnd) {
968 // While not aligned to a 16-byte boundary.
969 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
970 C = *CurPtr++;
971
972 if (C == '/') goto FoundSlash;
973
974#ifdef __SSE2__
975 __m128i Slashes = _mm_set_epi8('/', '/', '/', '/', '/', '/', '/', '/',
976 '/', '/', '/', '/', '/', '/', '/', '/');
977 while (CurPtr+16 <= BufferEnd &&
978 _mm_movemask_epi8(_mm_cmpeq_epi8(*(__m128i*)CurPtr, Slashes)) == 0)
979 CurPtr += 16;
980#elif __ALTIVEC__
981 __vector unsigned char Slashes = {
982 '/', '/', '/', '/', '/', '/', '/', '/',
983 '/', '/', '/', '/', '/', '/', '/', '/'
984 };
985 while (CurPtr+16 <= BufferEnd &&
986 !vec_any_eq(*(vector unsigned char*)CurPtr, Slashes))
987 CurPtr += 16;
988#else
989 // Scan for '/' quickly. Many block comments are very large.
990 while (CurPtr[0] != '/' &&
991 CurPtr[1] != '/' &&
992 CurPtr[2] != '/' &&
993 CurPtr[3] != '/' &&
994 CurPtr+4 < BufferEnd) {
995 CurPtr += 4;
996 }
997#endif
998
999 // It has to be one of the bytes scanned, increment to it and read one.
1000 C = *CurPtr++;
1001 }
1002
1003 // Loop to scan the remainder.
1004 while (C != '/' && C != '\0')
1005 C = *CurPtr++;
1006
1007 FoundSlash:
1008 if (C == '/') {
1009 if (CurPtr[-2] == '*') // We found the final */. We're done!
1010 break;
1011
1012 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
1013 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
1014 // We found the final */, though it had an escaped newline between the
1015 // * and /. We're done!
1016 break;
1017 }
1018 }
1019 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
1020 // If this is a /* inside of the comment, emit a warning. Don't do this
1021 // if this is a /*/, which will end the comment. This misses cases with
1022 // embedded escaped newlines, but oh well.
Chris Lattnere5eca952008-10-12 01:31:51 +00001023 Diag(CurPtr-1, diag::warn_nested_block_comment);
Chris Lattner4b009652007-07-25 00:24:17 +00001024 }
1025 } else if (C == 0 && CurPtr == BufferEnd+1) {
Chris Lattnere5eca952008-10-12 01:31:51 +00001026 if (!LexingRawMode) Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner4b009652007-07-25 00:24:17 +00001027 // Note: the user probably forgot a */. We could continue immediately
1028 // after the /*, but this would involve lexing a lot of what really is the
1029 // comment, which surely would confuse the parser.
1030 BufferPtr = CurPtr-1;
1031 return true;
1032 }
1033 C = *CurPtr++;
1034 }
1035
1036 // If we are returning comments as tokens, return this comment as a token.
Chris Lattner170adb12008-10-12 03:22:02 +00001037 if (inKeepCommentMode()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001038 Result.setKind(tok::comment);
1039 FormTokenWithChars(Result, CurPtr);
1040 return false;
1041 }
1042
1043 // It is common for the tokens immediately after a /**/ comment to be
1044 // whitespace. Instead of going through the big switch, handle it
Chris Lattner867a87b2008-10-12 04:05:48 +00001045 // efficiently now. This is safe even in KeepWhitespaceMode because we would
1046 // have already returned above with the comment as a token.
Chris Lattner4b009652007-07-25 00:24:17 +00001047 if (isHorizontalWhitespace(*CurPtr)) {
1048 Result.setFlag(Token::LeadingSpace);
1049 SkipWhitespace(Result, CurPtr+1);
1050 return true;
1051 }
1052
1053 // Otherwise, just return so that the next character will be lexed as a token.
1054 BufferPtr = CurPtr;
1055 Result.setFlag(Token::LeadingSpace);
1056 return true;
1057}
1058
1059//===----------------------------------------------------------------------===//
1060// Primary Lexing Entry Points
1061//===----------------------------------------------------------------------===//
1062
1063/// LexIncludeFilename - After the preprocessor has parsed a #include, lex and
1064/// (potentially) macro expand the filename.
1065void Lexer::LexIncludeFilename(Token &FilenameTok) {
1066 assert(ParsingPreprocessorDirective &&
1067 ParsingFilename == false &&
1068 "Must be in a preprocessing directive!");
1069
1070 // We are now parsing a filename!
1071 ParsingFilename = true;
1072
1073 // Lex the filename.
1074 Lex(FilenameTok);
1075
1076 // We should have obtained the filename now.
1077 ParsingFilename = false;
1078
1079 // No filename?
Chris Lattnercb8e41c2007-10-09 18:02:16 +00001080 if (FilenameTok.is(tok::eom))
Chris Lattner4b009652007-07-25 00:24:17 +00001081 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1082}
1083
1084/// 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;
1135 Result.setKind(tok::eom);
1136 // Update the location of token as well as BufferPtr.
1137 FormTokenWithChars(Result, CurPtr);
1138
1139 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattner1c1bed12008-10-12 03:27:19 +00001140 SetCommentRetentionState(PP->getCommentRetentionState());
Chris Lattner4b009652007-07-25 00:24:17 +00001141 return true; // Have a token.
1142 }
1143
1144 // If we are in raw mode, return this event as an EOF token. Let the caller
1145 // that put us in raw mode handle the event.
1146 if (LexingRawMode) {
1147 Result.startToken();
1148 BufferPtr = BufferEnd;
1149 FormTokenWithChars(Result, BufferEnd);
1150 Result.setKind(tok::eof);
1151 return true;
1152 }
1153
1154 // Otherwise, issue diagnostics for unterminated #if and missing newline.
1155
1156 // If we are in a #if directive, emit an error.
1157 while (!ConditionalStack.empty()) {
1158 Diag(ConditionalStack.back().IfLoc, diag::err_pp_unterminated_conditional);
1159 ConditionalStack.pop_back();
1160 }
1161
Chris Lattner5c337fa2008-04-12 05:54:25 +00001162 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
1163 // a pedwarn.
1164 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r'))
Chris Lattner4b009652007-07-25 00:24:17 +00001165 Diag(BufferEnd, diag::ext_no_newline_eof);
1166
1167 BufferPtr = CurPtr;
1168
1169 // Finally, let the preprocessor handle this.
Chris Lattner342dccb2007-10-17 20:41:00 +00001170 return PP->HandleEndOfFile(Result);
Chris Lattner4b009652007-07-25 00:24:17 +00001171}
1172
1173/// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
1174/// the specified lexer will return a tok::l_paren token, 0 if it is something
1175/// else and 2 if there are no more tokens in the buffer controlled by the
1176/// lexer.
1177unsigned Lexer::isNextPPTokenLParen() {
1178 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
1179
1180 // Switch to 'skipping' mode. This will ensure that we can lex a token
1181 // without emitting diagnostics, disables macro expansion, and will cause EOF
1182 // to return an EOF token instead of popping the include stack.
1183 LexingRawMode = true;
1184
1185 // Save state that can be changed while lexing so that we can restore it.
1186 const char *TmpBufferPtr = BufferPtr;
1187
1188 Token Tok;
1189 Tok.startToken();
1190 LexTokenInternal(Tok);
1191
1192 // Restore state that may have changed.
1193 BufferPtr = TmpBufferPtr;
1194
1195 // Restore the lexer back to non-skipping mode.
1196 LexingRawMode = false;
1197
Chris Lattnercb8e41c2007-10-09 18:02:16 +00001198 if (Tok.is(tok::eof))
Chris Lattner4b009652007-07-25 00:24:17 +00001199 return 2;
Chris Lattnercb8e41c2007-10-09 18:02:16 +00001200 return Tok.is(tok::l_paren);
Chris Lattner4b009652007-07-25 00:24:17 +00001201}
1202
1203
1204/// LexTokenInternal - This implements a simple C family lexer. It is an
1205/// extremely performance critical piece of code. This assumes that the buffer
1206/// has a null character at the end of the file. Return true if an error
1207/// occurred and compilation should terminate, false if normal. This returns a
1208/// preprocessing token, not a normal token, as such, it is an internal
1209/// interface. It assumes that the Flags of result have been cleared before
1210/// calling this.
1211void Lexer::LexTokenInternal(Token &Result) {
1212LexNextToken:
1213 // New token, can't need cleaning yet.
1214 Result.clearFlag(Token::NeedsCleaning);
1215 Result.setIdentifierInfo(0);
1216
1217 // CurPtr - Cache BufferPtr in an automatic variable.
1218 const char *CurPtr = BufferPtr;
1219
1220 // Small amounts of horizontal whitespace is very common between tokens.
1221 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
1222 ++CurPtr;
1223 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
1224 ++CurPtr;
Chris Lattner867a87b2008-10-12 04:05:48 +00001225
1226 // If we are keeping whitespace and other tokens, just return what we just
1227 // skipped. The next lexer invocation will return the token after the
1228 // whitespace.
1229 if (isKeepWhitespaceMode()) {
1230 Result.setKind(tok::unknown);
1231 FormTokenWithChars(Result, CurPtr);
1232 return;
1233 }
1234
Chris Lattner4b009652007-07-25 00:24:17 +00001235 BufferPtr = CurPtr;
1236 Result.setFlag(Token::LeadingSpace);
1237 }
1238
1239 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
1240
1241 // Read a character, advancing over it.
1242 char Char = getAndAdvanceChar(CurPtr, Result);
1243 switch (Char) {
1244 case 0: // Null.
1245 // Found end of file?
1246 if (CurPtr-1 == BufferEnd) {
1247 // Read the PP instance variable into an automatic variable, because
1248 // LexEndOfFile will often delete 'this'.
Chris Lattner342dccb2007-10-17 20:41:00 +00001249 Preprocessor *PPCache = PP;
Chris Lattner4b009652007-07-25 00:24:17 +00001250 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
1251 return; // Got a token to return.
Chris Lattner342dccb2007-10-17 20:41:00 +00001252 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
1253 return PPCache->Lex(Result);
Chris Lattner4b009652007-07-25 00:24:17 +00001254 }
1255
1256 Diag(CurPtr-1, diag::null_in_file);
1257 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
1276 Result.setKind(tok::eom);
1277 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) {
1351 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
1352 // Notify MIOpt that we read a non-whitespace/non-comment token.
1353 MIOpt.ReadToken();
1354 return LexIdentifier(Result, CurPtr);
1355 }
Chris Lattner4b009652007-07-25 00:24:17 +00001356
Chris Lattner0ffadcc2008-01-03 17:58:54 +00001357 Result.setKind(tok::unknown);
1358 break;
Chris Lattner4b009652007-07-25 00:24:17 +00001359
1360 // C99 6.4.4: Character Constants.
1361 case '\'':
1362 // Notify MIOpt that we read a non-whitespace/non-comment token.
1363 MIOpt.ReadToken();
1364 return LexCharConstant(Result, CurPtr);
1365
1366 // C99 6.4.5: String Literals.
1367 case '"':
1368 // Notify MIOpt that we read a non-whitespace/non-comment token.
1369 MIOpt.ReadToken();
1370 return LexStringLiteral(Result, CurPtr, false);
1371
1372 // C99 6.4.6: Punctuators.
1373 case '?':
1374 Result.setKind(tok::question);
1375 break;
1376 case '[':
1377 Result.setKind(tok::l_square);
1378 break;
1379 case ']':
1380 Result.setKind(tok::r_square);
1381 break;
1382 case '(':
1383 Result.setKind(tok::l_paren);
1384 break;
1385 case ')':
1386 Result.setKind(tok::r_paren);
1387 break;
1388 case '{':
1389 Result.setKind(tok::l_brace);
1390 break;
1391 case '}':
1392 Result.setKind(tok::r_brace);
1393 break;
1394 case '.':
1395 Char = getCharAndSize(CurPtr, SizeTmp);
1396 if (Char >= '0' && Char <= '9') {
1397 // Notify MIOpt that we read a non-whitespace/non-comment token.
1398 MIOpt.ReadToken();
1399
1400 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
1401 } else if (Features.CPlusPlus && Char == '*') {
1402 Result.setKind(tok::periodstar);
1403 CurPtr += SizeTmp;
1404 } else if (Char == '.' &&
1405 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
1406 Result.setKind(tok::ellipsis);
1407 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1408 SizeTmp2, Result);
1409 } else {
1410 Result.setKind(tok::period);
1411 }
1412 break;
1413 case '&':
1414 Char = getCharAndSize(CurPtr, SizeTmp);
1415 if (Char == '&') {
1416 Result.setKind(tok::ampamp);
1417 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1418 } else if (Char == '=') {
1419 Result.setKind(tok::ampequal);
1420 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1421 } else {
1422 Result.setKind(tok::amp);
1423 }
1424 break;
1425 case '*':
1426 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
1427 Result.setKind(tok::starequal);
1428 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1429 } else {
1430 Result.setKind(tok::star);
1431 }
1432 break;
1433 case '+':
1434 Char = getCharAndSize(CurPtr, SizeTmp);
1435 if (Char == '+') {
1436 Result.setKind(tok::plusplus);
1437 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1438 } else if (Char == '=') {
1439 Result.setKind(tok::plusequal);
1440 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1441 } else {
1442 Result.setKind(tok::plus);
1443 }
1444 break;
1445 case '-':
1446 Char = getCharAndSize(CurPtr, SizeTmp);
1447 if (Char == '-') {
1448 Result.setKind(tok::minusminus);
1449 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1450 } else if (Char == '>' && Features.CPlusPlus &&
1451 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') {
1452 Result.setKind(tok::arrowstar); // C++ ->*
1453 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1454 SizeTmp2, Result);
1455 } else if (Char == '>') {
1456 Result.setKind(tok::arrow);
1457 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1458 } else if (Char == '=') {
1459 Result.setKind(tok::minusequal);
1460 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1461 } else {
1462 Result.setKind(tok::minus);
1463 }
1464 break;
1465 case '~':
1466 Result.setKind(tok::tilde);
1467 break;
1468 case '!':
1469 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
1470 Result.setKind(tok::exclaimequal);
1471 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1472 } else {
1473 Result.setKind(tok::exclaim);
1474 }
1475 break;
1476 case '/':
1477 // 6.4.9: Comments
1478 Char = getCharAndSize(CurPtr, SizeTmp);
1479 if (Char == '/') { // BCPL comment.
1480 if (SkipBCPLComment(Result, ConsumeChar(CurPtr, SizeTmp, Result))) {
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;
1485 }
1486 return; // KeepCommentMode
1487 } else if (Char == '*') { // /**/ comment.
1488 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
1489 goto LexNextToken; // GCC isn't tail call eliminating.
1490 return; // KeepCommentMode
1491 } else if (Char == '=') {
1492 Result.setKind(tok::slashequal);
1493 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1494 } else {
1495 Result.setKind(tok::slash);
1496 }
1497 break;
1498 case '%':
1499 Char = getCharAndSize(CurPtr, SizeTmp);
1500 if (Char == '=') {
1501 Result.setKind(tok::percentequal);
1502 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1503 } else if (Features.Digraphs && Char == '>') {
1504 Result.setKind(tok::r_brace); // '%>' -> '}'
1505 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1506 } else if (Features.Digraphs && Char == ':') {
1507 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1508 Char = getCharAndSize(CurPtr, SizeTmp);
1509 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
1510 Result.setKind(tok::hashhash); // '%:%:' -> '##'
1511 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1512 SizeTmp2, Result);
1513 } else if (Char == '@' && Features.Microsoft) { // %:@ -> #@ -> Charize
1514 Result.setKind(tok::hashat);
1515 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1516 Diag(BufferPtr, diag::charize_microsoft_ext);
1517 } else {
1518 Result.setKind(tok::hash); // '%:' -> '#'
1519
1520 // We parsed a # character. If this occurs at the start of the line,
1521 // it's actually the start of a preprocessing directive. Callback to
1522 // the preprocessor to handle it.
1523 // FIXME: -fpreprocessed mode??
1524 if (Result.isAtStartOfLine() && !LexingRawMode) {
1525 BufferPtr = CurPtr;
Chris Lattner342dccb2007-10-17 20:41:00 +00001526 PP->HandleDirective(Result);
Chris Lattner4b009652007-07-25 00:24:17 +00001527
1528 // As an optimization, if the preprocessor didn't switch lexers, tail
1529 // recurse.
Chris Lattner342dccb2007-10-17 20:41:00 +00001530 if (PP->isCurrentLexer(this)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001531 // Start a new token. If this is a #include or something, the PP may
1532 // want us starting at the beginning of the line again. If so, set
1533 // the StartOfLine flag.
1534 if (IsAtStartOfLine) {
1535 Result.setFlag(Token::StartOfLine);
1536 IsAtStartOfLine = false;
1537 }
1538 goto LexNextToken; // GCC isn't tail call eliminating.
1539 }
1540
Chris Lattner342dccb2007-10-17 20:41:00 +00001541 return PP->Lex(Result);
Chris Lattner4b009652007-07-25 00:24:17 +00001542 }
1543 }
1544 } else {
1545 Result.setKind(tok::percent);
1546 }
1547 break;
1548 case '<':
1549 Char = getCharAndSize(CurPtr, SizeTmp);
1550 if (ParsingFilename) {
1551 return LexAngledStringLiteral(Result, CurPtr+SizeTmp);
1552 } else if (Char == '<' &&
1553 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '=') {
1554 Result.setKind(tok::lesslessequal);
1555 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1556 SizeTmp2, Result);
1557 } else if (Char == '<') {
1558 Result.setKind(tok::lessless);
1559 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1560 } else if (Char == '=') {
1561 Result.setKind(tok::lessequal);
1562 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1563 } else if (Features.Digraphs && Char == ':') {
1564 Result.setKind(tok::l_square); // '<:' -> '['
1565 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner0297c762008-02-25 04:01:39 +00001566 } else if (Features.Digraphs && Char == '%') {
Chris Lattner4b009652007-07-25 00:24:17 +00001567 Result.setKind(tok::l_brace); // '<%' -> '{'
1568 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1569 } else {
1570 Result.setKind(tok::less);
1571 }
1572 break;
1573 case '>':
1574 Char = getCharAndSize(CurPtr, SizeTmp);
1575 if (Char == '=') {
1576 Result.setKind(tok::greaterequal);
1577 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1578 } else if (Char == '>' &&
1579 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '=') {
1580 Result.setKind(tok::greatergreaterequal);
1581 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1582 SizeTmp2, Result);
1583 } else if (Char == '>') {
1584 Result.setKind(tok::greatergreater);
1585 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1586 } else {
1587 Result.setKind(tok::greater);
1588 }
1589 break;
1590 case '^':
1591 Char = getCharAndSize(CurPtr, SizeTmp);
1592 if (Char == '=') {
1593 Result.setKind(tok::caretequal);
1594 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1595 } else {
1596 Result.setKind(tok::caret);
1597 }
1598 break;
1599 case '|':
1600 Char = getCharAndSize(CurPtr, SizeTmp);
1601 if (Char == '=') {
1602 Result.setKind(tok::pipeequal);
1603 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1604 } else if (Char == '|') {
1605 Result.setKind(tok::pipepipe);
1606 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1607 } else {
1608 Result.setKind(tok::pipe);
1609 }
1610 break;
1611 case ':':
1612 Char = getCharAndSize(CurPtr, SizeTmp);
1613 if (Features.Digraphs && Char == '>') {
1614 Result.setKind(tok::r_square); // ':>' -> ']'
1615 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1616 } else if (Features.CPlusPlus && Char == ':') {
1617 Result.setKind(tok::coloncolon);
1618 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1619 } else {
1620 Result.setKind(tok::colon);
1621 }
1622 break;
1623 case ';':
1624 Result.setKind(tok::semi);
1625 break;
1626 case '=':
1627 Char = getCharAndSize(CurPtr, SizeTmp);
1628 if (Char == '=') {
1629 Result.setKind(tok::equalequal);
1630 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1631 } else {
1632 Result.setKind(tok::equal);
1633 }
1634 break;
1635 case ',':
1636 Result.setKind(tok::comma);
1637 break;
1638 case '#':
1639 Char = getCharAndSize(CurPtr, SizeTmp);
1640 if (Char == '#') {
1641 Result.setKind(tok::hashhash);
1642 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1643 } else if (Char == '@' && Features.Microsoft) { // #@ -> Charize
1644 Result.setKind(tok::hashat);
1645 Diag(BufferPtr, diag::charize_microsoft_ext);
1646 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1647 } else {
1648 Result.setKind(tok::hash);
1649 // 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)
1677 Result.setKind(tok::at);
1678 else
1679 Result.setKind(tok::unknown);
1680 break;
1681
Chris Lattner4b009652007-07-25 00:24:17 +00001682 case '\\':
1683 // FIXME: UCN's.
1684 // FALL THROUGH.
1685 default:
Chris Lattner4b009652007-07-25 00:24:17 +00001686 Result.setKind(tok::unknown);
1687 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.
1694 FormTokenWithChars(Result, CurPtr);
1695}