blob: c7f54ca8ff3c9cd0f2b9d0000ece4b8120c8938f [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- Lexer.cpp - C Language Family Lexer ------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chris Lattnerd2177732007-07-20 16:59:19 +000010// This file implements the Lexer and Token interfaces.
Reid Spencer5f016e22007-07-11 17:01:13 +000011//
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"
Chris Lattner9dc1f532007-07-20 16:37:10 +000030#include "clang/Basic/SourceManager.h"
Chris Lattner409a0362007-07-22 18:38:25 +000031#include "llvm/Support/Compiler.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000032#include "llvm/Support/MemoryBuffer.h"
33#include <cctype>
34using namespace clang;
35
36static void InitCharacterInfo();
37
Chris Lattnerdbf388b2007-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 Lattner22f6bbc2007-10-09 18:02:16 +000044 return is(tok::identifier) &&
45 getIdentifierInfo()->getObjCKeywordID() == objcKey;
Chris Lattnerdbf388b2007-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
54//===----------------------------------------------------------------------===//
55// Lexer Class Implementation
56//===----------------------------------------------------------------------===//
57
58
Chris Lattner168ae2d2007-10-17 20:41:00 +000059/// Lexer constructor - Create a new lexer object for the specified buffer
60/// with the specified preprocessor managing the lexing process. This lexer
61/// assumes that the associated file buffer and Preprocessor objects will
62/// outlive it, so it doesn't take ownership of either of them.
Chris Lattner25bdb512007-07-20 16:52:03 +000063Lexer::Lexer(SourceLocation fileloc, Preprocessor &pp,
64 const char *BufStart, const char *BufEnd)
Chris Lattner168ae2d2007-10-17 20:41:00 +000065 : FileLoc(fileloc), PP(&pp), Features(pp.getLangOptions()) {
Chris Lattner25bdb512007-07-20 16:52:03 +000066
Chris Lattner168ae2d2007-10-17 20:41:00 +000067 SourceManager &SourceMgr = PP->getSourceManager();
Chris Lattner448cec42007-07-22 18:44:36 +000068 unsigned InputFileID = SourceMgr.getPhysicalLoc(FileLoc).getFileID();
69 const llvm::MemoryBuffer *InputFile = SourceMgr.getBuffer(InputFileID);
Chris Lattner25bdb512007-07-20 16:52:03 +000070
Reid Spencer5f016e22007-07-11 17:01:13 +000071 Is_PragmaLexer = false;
Reid Spencer5f016e22007-07-11 17:01:13 +000072 InitCharacterInfo();
Chris Lattner448cec42007-07-22 18:44:36 +000073
74 // BufferStart must always be InputFile->getBufferStart().
75 BufferStart = InputFile->getBufferStart();
76
77 // BufferPtr and BufferEnd can start out somewhere inside the current buffer.
78 // If unspecified, they starts at the start/end of the buffer.
79 BufferPtr = BufStart ? BufStart : BufferStart;
Chris Lattner25bdb512007-07-20 16:52:03 +000080 BufferEnd = BufEnd ? BufEnd : InputFile->getBufferEnd();
81
Reid Spencer5f016e22007-07-11 17:01:13 +000082 assert(BufferEnd[0] == 0 &&
83 "We assume that the input buffer has a null character at the end"
84 " to simplify lexing!");
Chris Lattner25bdb512007-07-20 16:52:03 +000085
Reid Spencer5f016e22007-07-11 17:01:13 +000086 // Start of the file is a start of line.
87 IsAtStartOfLine = true;
88
89 // We are not after parsing a #.
90 ParsingPreprocessorDirective = false;
91
92 // We are not after parsing #include.
93 ParsingFilename = false;
94
95 // We are not in raw mode. Raw mode disables diagnostics and interpretation
96 // of tokens (e.g. identifiers, thus disabling macro expansion). It is used
97 // to quickly lex the tokens of the buffer, e.g. when handling a "#if 0" block
98 // or otherwise skipping over tokens.
99 LexingRawMode = false;
100
101 // Default to keeping comments if requested.
Chris Lattner168ae2d2007-10-17 20:41:00 +0000102 KeepCommentMode = PP->getCommentRetentionState();
Reid Spencer5f016e22007-07-11 17:01:13 +0000103}
104
Chris Lattner168ae2d2007-10-17 20:41:00 +0000105/// Lexer constructor - Create a new raw lexer object. This object is only
106/// suitable for calls to 'LexRawToken'. This lexer assumes that the
107/// associated file buffer will outlive it, so it doesn't take ownership of
108/// either of them.
109Lexer::Lexer(SourceLocation fileloc, const LangOptions &features,
110 const char *BufStart, const char *BufEnd)
111 : FileLoc(fileloc), PP(0), Features(features) {
112 Is_PragmaLexer = false;
113 InitCharacterInfo();
114
115 BufferStart = BufStart;
116 BufferPtr = BufStart;
117 BufferEnd = BufEnd;
118
119 assert(BufferEnd[0] == 0 &&
120 "We assume that the input buffer has a null character at the end"
121 " to simplify lexing!");
122
123 // Start of the file is a start of line.
124 IsAtStartOfLine = true;
125
126 // We are not after parsing a #.
127 ParsingPreprocessorDirective = false;
128
129 // We are not after parsing #include.
130 ParsingFilename = false;
131
132 // We *are* in raw mode.
133 LexingRawMode = true;
134
135 // Never keep comments in raw mode.
136 KeepCommentMode = false;
137}
138
139
Reid Spencer5f016e22007-07-11 17:01:13 +0000140/// Stringify - Convert the specified string into a C string, with surrounding
141/// ""'s, and with escaped \ and " characters.
142std::string Lexer::Stringify(const std::string &Str, bool Charify) {
143 std::string Result = Str;
144 char Quote = Charify ? '\'' : '"';
145 for (unsigned i = 0, e = Result.size(); i != e; ++i) {
146 if (Result[i] == '\\' || Result[i] == Quote) {
147 Result.insert(Result.begin()+i, '\\');
148 ++i; ++e;
149 }
150 }
151 return Result;
152}
153
Chris Lattnerd8e30832007-07-24 06:57:14 +0000154/// Stringify - Convert the specified string into a C string by escaping '\'
155/// and " characters. This does not add surrounding ""'s to the string.
156void Lexer::Stringify(llvm::SmallVectorImpl<char> &Str) {
157 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
158 if (Str[i] == '\\' || Str[i] == '"') {
159 Str.insert(Str.begin()+i, '\\');
160 ++i; ++e;
161 }
162 }
163}
164
Reid Spencer5f016e22007-07-11 17:01:13 +0000165
166//===----------------------------------------------------------------------===//
167// Character information.
168//===----------------------------------------------------------------------===//
169
170static unsigned char CharInfo[256];
171
172enum {
173 CHAR_HORZ_WS = 0x01, // ' ', '\t', '\f', '\v'. Note, no '\0'
174 CHAR_VERT_WS = 0x02, // '\r', '\n'
175 CHAR_LETTER = 0x04, // a-z,A-Z
176 CHAR_NUMBER = 0x08, // 0-9
177 CHAR_UNDER = 0x10, // _
178 CHAR_PERIOD = 0x20 // .
179};
180
181static void InitCharacterInfo() {
182 static bool isInited = false;
183 if (isInited) return;
184 isInited = true;
185
186 // Intiialize the CharInfo table.
187 // TODO: statically initialize this.
188 CharInfo[(int)' '] = CharInfo[(int)'\t'] =
189 CharInfo[(int)'\f'] = CharInfo[(int)'\v'] = CHAR_HORZ_WS;
190 CharInfo[(int)'\n'] = CharInfo[(int)'\r'] = CHAR_VERT_WS;
191
192 CharInfo[(int)'_'] = CHAR_UNDER;
193 CharInfo[(int)'.'] = CHAR_PERIOD;
194 for (unsigned i = 'a'; i <= 'z'; ++i)
195 CharInfo[i] = CharInfo[i+'A'-'a'] = CHAR_LETTER;
196 for (unsigned i = '0'; i <= '9'; ++i)
197 CharInfo[i] = CHAR_NUMBER;
198}
199
200/// isIdentifierBody - Return true if this is the body character of an
201/// identifier, which is [a-zA-Z0-9_].
202static inline bool isIdentifierBody(unsigned char c) {
Chris Lattnerdbf388b2007-10-07 08:47:24 +0000203 return CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER);
Reid Spencer5f016e22007-07-11 17:01:13 +0000204}
205
206/// isHorizontalWhitespace - Return true if this character is horizontal
207/// whitespace: ' ', '\t', '\f', '\v'. Note that this returns false for '\0'.
208static inline bool isHorizontalWhitespace(unsigned char c) {
Chris Lattnerdbf388b2007-10-07 08:47:24 +0000209 return CharInfo[c] & CHAR_HORZ_WS;
Reid Spencer5f016e22007-07-11 17:01:13 +0000210}
211
212/// isWhitespace - Return true if this character is horizontal or vertical
213/// whitespace: ' ', '\t', '\f', '\v', '\n', '\r'. Note that this returns false
214/// for '\0'.
215static inline bool isWhitespace(unsigned char c) {
Chris Lattnerdbf388b2007-10-07 08:47:24 +0000216 return CharInfo[c] & (CHAR_HORZ_WS|CHAR_VERT_WS);
Reid Spencer5f016e22007-07-11 17:01:13 +0000217}
218
219/// isNumberBody - Return true if this is the body character of an
220/// preprocessing number, which is [a-zA-Z0-9_.].
221static inline bool isNumberBody(unsigned char c) {
Chris Lattnerdbf388b2007-10-07 08:47:24 +0000222 return CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER|CHAR_PERIOD);
Reid Spencer5f016e22007-07-11 17:01:13 +0000223}
224
225
226//===----------------------------------------------------------------------===//
227// Diagnostics forwarding code.
228//===----------------------------------------------------------------------===//
229
Chris Lattner409a0362007-07-22 18:38:25 +0000230/// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
231/// lexer buffer was all instantiated at a single point, perform the mapping.
232/// This is currently only used for _Pragma implementation, so it is the slow
233/// path of the hot getSourceLocation method. Do not allow it to be inlined.
234static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
235 SourceLocation FileLoc,
236 unsigned CharNo) DISABLE_INLINE;
237static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
238 SourceLocation FileLoc,
239 unsigned CharNo) {
240 // Otherwise, we're lexing "mapped tokens". This is used for things like
241 // _Pragma handling. Combine the instantiation location of FileLoc with the
242 // physical location.
243 SourceManager &SourceMgr = PP.getSourceManager();
244
245 // Create a new SLoc which is expanded from logical(FileLoc) but whose
246 // characters come from phys(FileLoc)+Offset.
247 SourceLocation VirtLoc = SourceMgr.getLogicalLoc(FileLoc);
248 SourceLocation PhysLoc = SourceMgr.getPhysicalLoc(FileLoc);
249 PhysLoc = SourceLocation::getFileLoc(PhysLoc.getFileID(), CharNo);
250 return SourceMgr.getInstantiationLoc(PhysLoc, VirtLoc);
251}
252
Reid Spencer5f016e22007-07-11 17:01:13 +0000253/// getSourceLocation - Return a source location identifier for the specified
254/// offset in the current file.
255SourceLocation Lexer::getSourceLocation(const char *Loc) const {
Chris Lattner448cec42007-07-22 18:44:36 +0000256 assert(Loc >= BufferStart && Loc <= BufferEnd &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000257 "Location out of range for this buffer!");
Chris Lattner9dc1f532007-07-20 16:37:10 +0000258
259 // In the normal case, we're just lexing from a simple file buffer, return
260 // the file id from FileLoc with the offset specified.
Chris Lattner448cec42007-07-22 18:44:36 +0000261 unsigned CharNo = Loc-BufferStart;
Chris Lattner9dc1f532007-07-20 16:37:10 +0000262 if (FileLoc.isFileID())
263 return SourceLocation::getFileLoc(FileLoc.getFileID(), CharNo);
264
Chris Lattner168ae2d2007-10-17 20:41:00 +0000265 assert(PP && "This doesn't work on raw lexers");
266 return GetMappedTokenLoc(*PP, FileLoc, CharNo);
Reid Spencer5f016e22007-07-11 17:01:13 +0000267}
268
Reid Spencer5f016e22007-07-11 17:01:13 +0000269/// Diag - Forwarding function for diagnostics. This translate a source
270/// position in the current buffer into a SourceLocation object for rendering.
271void Lexer::Diag(const char *Loc, unsigned DiagID,
272 const std::string &Msg) const {
273 if (LexingRawMode && Diagnostic::isNoteWarningOrExtension(DiagID))
274 return;
Chris Lattner168ae2d2007-10-17 20:41:00 +0000275 PP->Diag(getSourceLocation(Loc), DiagID, Msg);
Reid Spencer5f016e22007-07-11 17:01:13 +0000276}
277void Lexer::Diag(SourceLocation Loc, unsigned DiagID,
278 const std::string &Msg) const {
279 if (LexingRawMode && Diagnostic::isNoteWarningOrExtension(DiagID))
280 return;
Chris Lattner168ae2d2007-10-17 20:41:00 +0000281 PP->Diag(Loc, DiagID, Msg);
Reid Spencer5f016e22007-07-11 17:01:13 +0000282}
283
284
285//===----------------------------------------------------------------------===//
286// Trigraph and Escaped Newline Handling Code.
287//===----------------------------------------------------------------------===//
288
289/// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
290/// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
291static char GetTrigraphCharForLetter(char Letter) {
292 switch (Letter) {
293 default: return 0;
294 case '=': return '#';
295 case ')': return ']';
296 case '(': return '[';
297 case '!': return '|';
298 case '\'': return '^';
299 case '>': return '}';
300 case '/': return '\\';
301 case '<': return '{';
302 case '-': return '~';
303 }
304}
305
306/// DecodeTrigraphChar - If the specified character is a legal trigraph when
307/// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
308/// return the result character. Finally, emit a warning about trigraph use
309/// whether trigraphs are enabled or not.
310static char DecodeTrigraphChar(const char *CP, Lexer *L) {
311 char Res = GetTrigraphCharForLetter(*CP);
312 if (Res && L) {
313 if (!L->getFeatures().Trigraphs) {
314 L->Diag(CP-2, diag::trigraph_ignored);
315 return 0;
316 } else {
317 L->Diag(CP-2, diag::trigraph_converted, std::string()+Res);
318 }
319 }
320 return Res;
321}
322
323/// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
324/// get its size, and return it. This is tricky in several cases:
325/// 1. If currently at the start of a trigraph, we warn about the trigraph,
326/// then either return the trigraph (skipping 3 chars) or the '?',
327/// depending on whether trigraphs are enabled or not.
328/// 2. If this is an escaped newline (potentially with whitespace between
329/// the backslash and newline), implicitly skip the newline and return
330/// the char after it.
331/// 3. If this is a UCN, return it. FIXME: C++ UCN's?
332///
333/// This handles the slow/uncommon case of the getCharAndSize method. Here we
334/// know that we can accumulate into Size, and that we have already incremented
335/// Ptr by Size bytes.
336///
337/// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
338/// be updated to match.
339///
340char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
Chris Lattnerd2177732007-07-20 16:59:19 +0000341 Token *Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000342 // If we have a slash, look for an escaped newline.
343 if (Ptr[0] == '\\') {
344 ++Size;
345 ++Ptr;
346Slash:
347 // Common case, backslash-char where the char is not whitespace.
348 if (!isWhitespace(Ptr[0])) return '\\';
349
350 // See if we have optional whitespace characters followed by a newline.
351 {
352 unsigned SizeTmp = 0;
353 do {
354 ++SizeTmp;
355 if (Ptr[SizeTmp-1] == '\n' || Ptr[SizeTmp-1] == '\r') {
356 // Remember that this token needs to be cleaned.
Chris Lattnerd2177732007-07-20 16:59:19 +0000357 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +0000358
359 // Warn if there was whitespace between the backslash and newline.
360 if (SizeTmp != 1 && Tok)
361 Diag(Ptr, diag::backslash_newline_space);
362
363 // If this is a \r\n or \n\r, skip the newlines.
364 if ((Ptr[SizeTmp] == '\r' || Ptr[SizeTmp] == '\n') &&
365 Ptr[SizeTmp-1] != Ptr[SizeTmp])
366 ++SizeTmp;
367
368 // Found backslash<whitespace><newline>. Parse the char after it.
369 Size += SizeTmp;
370 Ptr += SizeTmp;
371 // Use slow version to accumulate a correct size field.
372 return getCharAndSizeSlow(Ptr, Size, Tok);
373 }
374 } while (isWhitespace(Ptr[SizeTmp]));
375 }
376
377 // Otherwise, this is not an escaped newline, just return the slash.
378 return '\\';
379 }
380
381 // If this is a trigraph, process it.
382 if (Ptr[0] == '?' && Ptr[1] == '?') {
383 // If this is actually a legal trigraph (not something like "??x"), emit
384 // a trigraph warning. If so, and if trigraphs are enabled, return it.
385 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : 0)) {
386 // Remember that this token needs to be cleaned.
Chris Lattnerd2177732007-07-20 16:59:19 +0000387 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +0000388
389 Ptr += 3;
390 Size += 3;
391 if (C == '\\') goto Slash;
392 return C;
393 }
394 }
395
396 // If this is neither, return a single character.
397 ++Size;
398 return *Ptr;
399}
400
401
402/// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
403/// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
404/// and that we have already incremented Ptr by Size bytes.
405///
406/// NOTE: When this method is updated, getCharAndSizeSlow (above) should
407/// be updated to match.
408char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
409 const LangOptions &Features) {
410 // If we have a slash, look for an escaped newline.
411 if (Ptr[0] == '\\') {
412 ++Size;
413 ++Ptr;
414Slash:
415 // Common case, backslash-char where the char is not whitespace.
416 if (!isWhitespace(Ptr[0])) return '\\';
417
418 // See if we have optional whitespace characters followed by a newline.
419 {
420 unsigned SizeTmp = 0;
421 do {
422 ++SizeTmp;
423 if (Ptr[SizeTmp-1] == '\n' || Ptr[SizeTmp-1] == '\r') {
424
425 // If this is a \r\n or \n\r, skip the newlines.
426 if ((Ptr[SizeTmp] == '\r' || Ptr[SizeTmp] == '\n') &&
427 Ptr[SizeTmp-1] != Ptr[SizeTmp])
428 ++SizeTmp;
429
430 // Found backslash<whitespace><newline>. Parse the char after it.
431 Size += SizeTmp;
432 Ptr += SizeTmp;
433
434 // Use slow version to accumulate a correct size field.
435 return getCharAndSizeSlowNoWarn(Ptr, Size, Features);
436 }
437 } while (isWhitespace(Ptr[SizeTmp]));
438 }
439
440 // Otherwise, this is not an escaped newline, just return the slash.
441 return '\\';
442 }
443
444 // If this is a trigraph, process it.
445 if (Features.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
446 // If this is actually a legal trigraph (not something like "??x"), return
447 // it.
448 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
449 Ptr += 3;
450 Size += 3;
451 if (C == '\\') goto Slash;
452 return C;
453 }
454 }
455
456 // If this is neither, return a single character.
457 ++Size;
458 return *Ptr;
459}
460
461//===----------------------------------------------------------------------===//
462// Helper methods for lexing.
463//===----------------------------------------------------------------------===//
464
Chris Lattnerd2177732007-07-20 16:59:19 +0000465void Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000466 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
467 unsigned Size;
468 unsigned char C = *CurPtr++;
469 while (isIdentifierBody(C)) {
470 C = *CurPtr++;
471 }
472 --CurPtr; // Back up over the skipped character.
473
474 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
475 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
476 // FIXME: UCNs.
477 if (C != '\\' && C != '?' && (C != '$' || !Features.DollarIdents)) {
478FinishIdentifier:
479 const char *IdStart = BufferPtr;
480 FormTokenWithChars(Result, CurPtr);
481 Result.setKind(tok::identifier);
482
483 // If we are in raw mode, return this identifier raw. There is no need to
484 // look up identifier information or attempt to macro expand it.
485 if (LexingRawMode) return;
486
487 // Fill in Result.IdentifierInfo, looking up the identifier in the
488 // identifier table.
Chris Lattner168ae2d2007-10-17 20:41:00 +0000489 PP->LookUpIdentifierInfo(Result, IdStart);
Reid Spencer5f016e22007-07-11 17:01:13 +0000490
491 // Finally, now that we know we have an identifier, pass this off to the
492 // preprocessor, which may macro expand it or something.
Chris Lattner168ae2d2007-10-17 20:41:00 +0000493 return PP->HandleIdentifier(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +0000494 }
495
496 // Otherwise, $,\,? in identifier found. Enter slower path.
497
498 C = getCharAndSize(CurPtr, Size);
499 while (1) {
500 if (C == '$') {
501 // If we hit a $ and they are not supported in identifiers, we are done.
502 if (!Features.DollarIdents) goto FinishIdentifier;
503
504 // Otherwise, emit a diagnostic and continue.
505 Diag(CurPtr, diag::ext_dollar_in_identifier);
506 CurPtr = ConsumeChar(CurPtr, Size, Result);
507 C = getCharAndSize(CurPtr, Size);
508 continue;
509 } else if (!isIdentifierBody(C)) { // FIXME: UCNs.
510 // Found end of identifier.
511 goto FinishIdentifier;
512 }
513
514 // Otherwise, this character is good, consume it.
515 CurPtr = ConsumeChar(CurPtr, Size, Result);
516
517 C = getCharAndSize(CurPtr, Size);
518 while (isIdentifierBody(C)) { // FIXME: UCNs.
519 CurPtr = ConsumeChar(CurPtr, Size, Result);
520 C = getCharAndSize(CurPtr, Size);
521 }
522 }
523}
524
525
526/// LexNumericConstant - Lex the remainer of a integer or floating point
527/// constant. From[-1] is the first character lexed. Return the end of the
528/// constant.
Chris Lattnerd2177732007-07-20 16:59:19 +0000529void Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000530 unsigned Size;
531 char C = getCharAndSize(CurPtr, Size);
532 char PrevCh = 0;
533 while (isNumberBody(C)) { // FIXME: UCNs?
534 CurPtr = ConsumeChar(CurPtr, Size, Result);
535 PrevCh = C;
536 C = getCharAndSize(CurPtr, Size);
537 }
538
539 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
540 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e'))
541 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
542
543 // If we have a hex FP constant, continue.
544 if (Features.HexFloats &&
545 (C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p'))
546 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
547
548 Result.setKind(tok::numeric_constant);
549
550 // Update the location of token as well as BufferPtr.
551 FormTokenWithChars(Result, CurPtr);
552}
553
554/// LexStringLiteral - Lex the remainder of a string literal, after having lexed
555/// either " or L".
Chris Lattnerd2177732007-07-20 16:59:19 +0000556void Lexer::LexStringLiteral(Token &Result, const char *CurPtr, bool Wide){
Reid Spencer5f016e22007-07-11 17:01:13 +0000557 const char *NulCharacter = 0; // Does this string contain the \0 character?
558
559 char C = getAndAdvanceChar(CurPtr, Result);
560 while (C != '"') {
561 // Skip escaped characters.
562 if (C == '\\') {
563 // Skip the escaped character.
564 C = getAndAdvanceChar(CurPtr, Result);
565 } else if (C == '\n' || C == '\r' || // Newline.
566 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
567 if (!LexingRawMode) Diag(BufferPtr, diag::err_unterminated_string);
568 Result.setKind(tok::unknown);
569 FormTokenWithChars(Result, CurPtr-1);
570 return;
571 } else if (C == 0) {
572 NulCharacter = CurPtr-1;
573 }
574 C = getAndAdvanceChar(CurPtr, Result);
575 }
576
577 // If a nul character existed in the string, warn about it.
578 if (NulCharacter) Diag(NulCharacter, diag::null_in_string);
579
580 Result.setKind(Wide ? tok::wide_string_literal : tok::string_literal);
581
582 // Update the location of the token as well as the BufferPtr instance var.
583 FormTokenWithChars(Result, CurPtr);
584}
585
586/// LexAngledStringLiteral - Lex the remainder of an angled string literal,
587/// after having lexed the '<' character. This is used for #include filenames.
Chris Lattnerd2177732007-07-20 16:59:19 +0000588void Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000589 const char *NulCharacter = 0; // Does this string contain the \0 character?
590
591 char C = getAndAdvanceChar(CurPtr, Result);
592 while (C != '>') {
593 // Skip escaped characters.
594 if (C == '\\') {
595 // Skip the escaped character.
596 C = getAndAdvanceChar(CurPtr, Result);
597 } else if (C == '\n' || C == '\r' || // Newline.
598 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
599 if (!LexingRawMode) Diag(BufferPtr, diag::err_unterminated_string);
600 Result.setKind(tok::unknown);
601 FormTokenWithChars(Result, CurPtr-1);
602 return;
603 } else if (C == 0) {
604 NulCharacter = CurPtr-1;
605 }
606 C = getAndAdvanceChar(CurPtr, Result);
607 }
608
609 // If a nul character existed in the string, warn about it.
610 if (NulCharacter) Diag(NulCharacter, diag::null_in_string);
611
612 Result.setKind(tok::angle_string_literal);
613
614 // Update the location of token as well as BufferPtr.
615 FormTokenWithChars(Result, CurPtr);
616}
617
618
619/// LexCharConstant - Lex the remainder of a character constant, after having
620/// lexed either ' or L'.
Chris Lattnerd2177732007-07-20 16:59:19 +0000621void Lexer::LexCharConstant(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000622 const char *NulCharacter = 0; // Does this character contain the \0 character?
623
624 // Handle the common case of 'x' and '\y' efficiently.
625 char C = getAndAdvanceChar(CurPtr, Result);
626 if (C == '\'') {
627 if (!LexingRawMode) Diag(BufferPtr, diag::err_empty_character);
628 Result.setKind(tok::unknown);
629 FormTokenWithChars(Result, CurPtr);
630 return;
631 } else if (C == '\\') {
632 // Skip the escaped character.
633 // FIXME: UCN's.
634 C = getAndAdvanceChar(CurPtr, Result);
635 }
636
637 if (C && C != '\n' && C != '\r' && CurPtr[0] == '\'') {
638 ++CurPtr;
639 } else {
640 // Fall back on generic code for embedded nulls, newlines, wide chars.
641 do {
642 // Skip escaped characters.
643 if (C == '\\') {
644 // Skip the escaped character.
645 C = getAndAdvanceChar(CurPtr, Result);
646 } else if (C == '\n' || C == '\r' || // Newline.
647 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
648 if (!LexingRawMode) Diag(BufferPtr, diag::err_unterminated_char);
649 Result.setKind(tok::unknown);
650 FormTokenWithChars(Result, CurPtr-1);
651 return;
652 } else if (C == 0) {
653 NulCharacter = CurPtr-1;
654 }
655 C = getAndAdvanceChar(CurPtr, Result);
656 } while (C != '\'');
657 }
658
659 if (NulCharacter) Diag(NulCharacter, diag::null_in_char);
660
661 Result.setKind(tok::char_constant);
662
663 // Update the location of token as well as BufferPtr.
664 FormTokenWithChars(Result, CurPtr);
665}
666
667/// SkipWhitespace - Efficiently skip over a series of whitespace characters.
668/// Update BufferPtr to point to the next non-whitespace character and return.
Chris Lattnerd2177732007-07-20 16:59:19 +0000669void Lexer::SkipWhitespace(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000670 // Whitespace - Skip it, then return the token after the whitespace.
671 unsigned char Char = *CurPtr; // Skip consequtive spaces efficiently.
672 while (1) {
673 // Skip horizontal whitespace very aggressively.
674 while (isHorizontalWhitespace(Char))
675 Char = *++CurPtr;
676
677 // Otherwise if we something other than whitespace, we're done.
678 if (Char != '\n' && Char != '\r')
679 break;
680
681 if (ParsingPreprocessorDirective) {
682 // End of preprocessor directive line, let LexTokenInternal handle this.
683 BufferPtr = CurPtr;
684 return;
685 }
686
687 // ok, but handle newline.
688 // The returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +0000689 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +0000690 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +0000691 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +0000692 Char = *++CurPtr;
693 }
694
695 // If this isn't immediately after a newline, there is leading space.
696 char PrevChar = CurPtr[-1];
697 if (PrevChar != '\n' && PrevChar != '\r')
Chris Lattnerd2177732007-07-20 16:59:19 +0000698 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +0000699
Reid Spencer5f016e22007-07-11 17:01:13 +0000700 BufferPtr = CurPtr;
701}
702
703// SkipBCPLComment - We have just read the // characters from input. Skip until
704// we find the newline character thats terminate the comment. Then update
705/// BufferPtr and return.
Chris Lattnerd2177732007-07-20 16:59:19 +0000706bool Lexer::SkipBCPLComment(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000707 // If BCPL comments aren't explicitly enabled for this language, emit an
708 // extension warning.
709 if (!Features.BCPLComment) {
710 Diag(BufferPtr, diag::ext_bcpl_comment);
711
712 // Mark them enabled so we only emit one warning for this translation
713 // unit.
714 Features.BCPLComment = true;
715 }
716
717 // Scan over the body of the comment. The common case, when scanning, is that
718 // the comment contains normal ascii characters with nothing interesting in
719 // them. As such, optimize for this case with the inner loop.
720 char C;
721 do {
722 C = *CurPtr;
723 // FIXME: Speedup BCPL comment lexing. Just scan for a \n or \r character.
724 // If we find a \n character, scan backwards, checking to see if it's an
725 // escaped newline, like we do for block comments.
726
727 // Skip over characters in the fast loop.
728 while (C != 0 && // Potentially EOF.
729 C != '\\' && // Potentially escaped newline.
730 C != '?' && // Potentially trigraph.
731 C != '\n' && C != '\r') // Newline or DOS-style newline.
732 C = *++CurPtr;
733
734 // If this is a newline, we're done.
735 if (C == '\n' || C == '\r')
736 break; // Found the newline? Break out!
737
738 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
739 // properly decode the character.
740 const char *OldPtr = CurPtr;
741 C = getAndAdvanceChar(CurPtr, Result);
742
743 // If we read multiple characters, and one of those characters was a \r or
744 // \n, then we had an escaped newline within the comment. Emit diagnostic
745 // unless the next line is also a // comment.
746 if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') {
747 for (; OldPtr != CurPtr; ++OldPtr)
748 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
749 // Okay, we found a // comment that ends in a newline, if the next
750 // line is also a // comment, but has spaces, don't emit a diagnostic.
751 if (isspace(C)) {
752 const char *ForwardPtr = CurPtr;
753 while (isspace(*ForwardPtr)) // Skip whitespace.
754 ++ForwardPtr;
755 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
756 break;
757 }
758
759 Diag(OldPtr-1, diag::ext_multi_line_bcpl_comment);
760 break;
761 }
762 }
763
764 if (CurPtr == BufferEnd+1) { --CurPtr; break; }
765 } while (C != '\n' && C != '\r');
766
767 // Found but did not consume the newline.
768
769 // If we are returning comments as tokens, return this comment as a token.
770 if (KeepCommentMode)
771 return SaveBCPLComment(Result, CurPtr);
772
773 // If we are inside a preprocessor directive and we see the end of line,
774 // return immediately, so that the lexer can return this as an EOM token.
775 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
776 BufferPtr = CurPtr;
777 return true;
778 }
779
780 // Otherwise, eat the \n character. We don't care if this is a \n\r or
781 // \r\n sequence.
782 ++CurPtr;
783
784 // The next returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +0000785 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +0000786 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +0000787 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +0000788 BufferPtr = CurPtr;
789 return true;
790}
791
792/// SaveBCPLComment - If in save-comment mode, package up this BCPL comment in
793/// an appropriate way and return it.
Chris Lattnerd2177732007-07-20 16:59:19 +0000794bool Lexer::SaveBCPLComment(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000795 Result.setKind(tok::comment);
796 FormTokenWithChars(Result, CurPtr);
797
798 // If this BCPL-style comment is in a macro definition, transmogrify it into
799 // a C-style block comment.
800 if (ParsingPreprocessorDirective) {
Chris Lattner168ae2d2007-10-17 20:41:00 +0000801 std::string Spelling = PP->getSpelling(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +0000802 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not bcpl comment?");
803 Spelling[1] = '*'; // Change prefix to "/*".
804 Spelling += "*/"; // add suffix.
805
Chris Lattner168ae2d2007-10-17 20:41:00 +0000806 Result.setLocation(PP->CreateString(&Spelling[0], Spelling.size(),
807 Result.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000808 Result.setLength(Spelling.size());
809 }
810 return false;
811}
812
813/// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
814/// character (either \n or \r) is part of an escaped newline sequence. Issue a
815/// diagnostic if so. We know that the is inside of a block comment.
816static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
817 Lexer *L) {
818 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
819
820 // Back up off the newline.
821 --CurPtr;
822
823 // If this is a two-character newline sequence, skip the other character.
824 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
825 // \n\n or \r\r -> not escaped newline.
826 if (CurPtr[0] == CurPtr[1])
827 return false;
828 // \n\r or \r\n -> skip the newline.
829 --CurPtr;
830 }
831
832 // If we have horizontal whitespace, skip over it. We allow whitespace
833 // between the slash and newline.
834 bool HasSpace = false;
835 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
836 --CurPtr;
837 HasSpace = true;
838 }
839
840 // If we have a slash, we know this is an escaped newline.
841 if (*CurPtr == '\\') {
842 if (CurPtr[-1] != '*') return false;
843 } else {
844 // It isn't a slash, is it the ?? / trigraph?
845 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
846 CurPtr[-3] != '*')
847 return false;
848
849 // This is the trigraph ending the comment. Emit a stern warning!
850 CurPtr -= 2;
851
852 // If no trigraphs are enabled, warn that we ignored this trigraph and
853 // ignore this * character.
854 if (!L->getFeatures().Trigraphs) {
855 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
856 return false;
857 }
858 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
859 }
860
861 // Warn about having an escaped newline between the */ characters.
862 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
863
864 // If there was space between the backslash and newline, warn about it.
865 if (HasSpace) L->Diag(CurPtr, diag::backslash_newline_space);
866
867 return true;
868}
869
870#ifdef __SSE2__
871#include <emmintrin.h>
872#elif __ALTIVEC__
873#include <altivec.h>
874#undef bool
875#endif
876
877/// SkipBlockComment - We have just read the /* characters from input. Read
878/// until we find the */ characters that terminate the comment. Note that we
879/// don't bother decoding trigraphs or escaped newlines in block comments,
880/// because they cannot cause the comment to end. The only thing that can
881/// happen is the comment could end with an escaped newline between the */ end
882/// of comment.
Chris Lattnerd2177732007-07-20 16:59:19 +0000883bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000884 // Scan one character past where we should, looking for a '/' character. Once
885 // we find it, check to see if it was preceeded by a *. This common
886 // optimization helps people who like to put a lot of * characters in their
887 // comments.
Chris Lattner8146b682007-07-21 23:43:37 +0000888
889 // The first character we get with newlines and trigraphs skipped to handle
890 // the degenerate /*/ case below correctly if the * has an escaped newline
891 // after it.
892 unsigned CharSize;
893 unsigned char C = getCharAndSize(CurPtr, CharSize);
894 CurPtr += CharSize;
Reid Spencer5f016e22007-07-11 17:01:13 +0000895 if (C == 0 && CurPtr == BufferEnd+1) {
896 Diag(BufferPtr, diag::err_unterminated_block_comment);
897 BufferPtr = CurPtr-1;
898 return true;
899 }
900
Chris Lattner8146b682007-07-21 23:43:37 +0000901 // Check to see if the first character after the '/*' is another /. If so,
902 // then this slash does not end the block comment, it is part of it.
903 if (C == '/')
904 C = *CurPtr++;
905
Reid Spencer5f016e22007-07-11 17:01:13 +0000906 while (1) {
907 // Skip over all non-interesting characters until we find end of buffer or a
908 // (probably ending) '/' character.
909 if (CurPtr + 24 < BufferEnd) {
910 // While not aligned to a 16-byte boundary.
911 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
912 C = *CurPtr++;
913
914 if (C == '/') goto FoundSlash;
915
916#ifdef __SSE2__
917 __m128i Slashes = _mm_set_epi8('/', '/', '/', '/', '/', '/', '/', '/',
918 '/', '/', '/', '/', '/', '/', '/', '/');
919 while (CurPtr+16 <= BufferEnd &&
920 _mm_movemask_epi8(_mm_cmpeq_epi8(*(__m128i*)CurPtr, Slashes)) == 0)
921 CurPtr += 16;
922#elif __ALTIVEC__
923 __vector unsigned char Slashes = {
924 '/', '/', '/', '/', '/', '/', '/', '/',
925 '/', '/', '/', '/', '/', '/', '/', '/'
926 };
927 while (CurPtr+16 <= BufferEnd &&
928 !vec_any_eq(*(vector unsigned char*)CurPtr, Slashes))
929 CurPtr += 16;
930#else
931 // Scan for '/' quickly. Many block comments are very large.
932 while (CurPtr[0] != '/' &&
933 CurPtr[1] != '/' &&
934 CurPtr[2] != '/' &&
935 CurPtr[3] != '/' &&
936 CurPtr+4 < BufferEnd) {
937 CurPtr += 4;
938 }
939#endif
940
941 // It has to be one of the bytes scanned, increment to it and read one.
942 C = *CurPtr++;
943 }
944
945 // Loop to scan the remainder.
946 while (C != '/' && C != '\0')
947 C = *CurPtr++;
948
949 FoundSlash:
950 if (C == '/') {
951 if (CurPtr[-2] == '*') // We found the final */. We're done!
952 break;
953
954 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
955 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
956 // We found the final */, though it had an escaped newline between the
957 // * and /. We're done!
958 break;
959 }
960 }
961 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
962 // If this is a /* inside of the comment, emit a warning. Don't do this
963 // if this is a /*/, which will end the comment. This misses cases with
964 // embedded escaped newlines, but oh well.
965 Diag(CurPtr-1, diag::nested_block_comment);
966 }
967 } else if (C == 0 && CurPtr == BufferEnd+1) {
968 Diag(BufferPtr, diag::err_unterminated_block_comment);
969 // Note: the user probably forgot a */. We could continue immediately
970 // after the /*, but this would involve lexing a lot of what really is the
971 // comment, which surely would confuse the parser.
972 BufferPtr = CurPtr-1;
973 return true;
974 }
975 C = *CurPtr++;
976 }
977
978 // If we are returning comments as tokens, return this comment as a token.
979 if (KeepCommentMode) {
980 Result.setKind(tok::comment);
981 FormTokenWithChars(Result, CurPtr);
982 return false;
983 }
984
985 // It is common for the tokens immediately after a /**/ comment to be
986 // whitespace. Instead of going through the big switch, handle it
987 // efficiently now.
988 if (isHorizontalWhitespace(*CurPtr)) {
Chris Lattnerd2177732007-07-20 16:59:19 +0000989 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +0000990 SkipWhitespace(Result, CurPtr+1);
991 return true;
992 }
993
994 // Otherwise, just return so that the next character will be lexed as a token.
995 BufferPtr = CurPtr;
Chris Lattnerd2177732007-07-20 16:59:19 +0000996 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +0000997 return true;
998}
999
1000//===----------------------------------------------------------------------===//
1001// Primary Lexing Entry Points
1002//===----------------------------------------------------------------------===//
1003
1004/// LexIncludeFilename - After the preprocessor has parsed a #include, lex and
1005/// (potentially) macro expand the filename.
Chris Lattnerd2177732007-07-20 16:59:19 +00001006void Lexer::LexIncludeFilename(Token &FilenameTok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001007 assert(ParsingPreprocessorDirective &&
1008 ParsingFilename == false &&
1009 "Must be in a preprocessing directive!");
1010
1011 // We are now parsing a filename!
1012 ParsingFilename = true;
1013
1014 // Lex the filename.
1015 Lex(FilenameTok);
1016
1017 // We should have obtained the filename now.
1018 ParsingFilename = false;
1019
1020 // No filename?
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001021 if (FilenameTok.is(tok::eom))
Reid Spencer5f016e22007-07-11 17:01:13 +00001022 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1023}
1024
1025/// ReadToEndOfLine - Read the rest of the current preprocessor line as an
1026/// uninterpreted string. This switches the lexer out of directive mode.
1027std::string Lexer::ReadToEndOfLine() {
1028 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
1029 "Must be in a preprocessing directive!");
1030 std::string Result;
Chris Lattnerd2177732007-07-20 16:59:19 +00001031 Token Tmp;
Reid Spencer5f016e22007-07-11 17:01:13 +00001032
1033 // CurPtr - Cache BufferPtr in an automatic variable.
1034 const char *CurPtr = BufferPtr;
1035 while (1) {
1036 char Char = getAndAdvanceChar(CurPtr, Tmp);
1037 switch (Char) {
1038 default:
1039 Result += Char;
1040 break;
1041 case 0: // Null.
1042 // Found end of file?
1043 if (CurPtr-1 != BufferEnd) {
1044 // Nope, normal character, continue.
1045 Result += Char;
1046 break;
1047 }
1048 // FALL THROUGH.
1049 case '\r':
1050 case '\n':
1051 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
1052 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
1053 BufferPtr = CurPtr-1;
1054
1055 // Next, lex the character, which should handle the EOM transition.
1056 Lex(Tmp);
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001057 assert(Tmp.is(tok::eom) && "Unexpected token!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001058
1059 // Finally, we're done, return the string we found.
1060 return Result;
1061 }
1062 }
1063}
1064
1065/// LexEndOfFile - CurPtr points to the end of this file. Handle this
1066/// condition, reporting diagnostics and handling other edge cases as required.
1067/// This returns true if Result contains a token, false if PP.Lex should be
1068/// called again.
Chris Lattnerd2177732007-07-20 16:59:19 +00001069bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001070 // If we hit the end of the file while parsing a preprocessor directive,
1071 // end the preprocessor directive first. The next token returned will
1072 // then be the end of file.
1073 if (ParsingPreprocessorDirective) {
1074 // Done parsing the "line".
1075 ParsingPreprocessorDirective = false;
1076 Result.setKind(tok::eom);
1077 // Update the location of token as well as BufferPtr.
1078 FormTokenWithChars(Result, CurPtr);
1079
1080 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattner168ae2d2007-10-17 20:41:00 +00001081 KeepCommentMode = PP->getCommentRetentionState();
Reid Spencer5f016e22007-07-11 17:01:13 +00001082 return true; // Have a token.
1083 }
1084
1085 // If we are in raw mode, return this event as an EOF token. Let the caller
1086 // that put us in raw mode handle the event.
1087 if (LexingRawMode) {
1088 Result.startToken();
1089 BufferPtr = BufferEnd;
1090 FormTokenWithChars(Result, BufferEnd);
1091 Result.setKind(tok::eof);
1092 return true;
1093 }
1094
1095 // Otherwise, issue diagnostics for unterminated #if and missing newline.
1096
1097 // If we are in a #if directive, emit an error.
1098 while (!ConditionalStack.empty()) {
1099 Diag(ConditionalStack.back().IfLoc, diag::err_pp_unterminated_conditional);
1100 ConditionalStack.pop_back();
1101 }
1102
1103 // If the file was empty or didn't end in a newline, issue a pedwarn.
1104 if (CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
1105 Diag(BufferEnd, diag::ext_no_newline_eof);
1106
1107 BufferPtr = CurPtr;
1108
1109 // Finally, let the preprocessor handle this.
Chris Lattner168ae2d2007-10-17 20:41:00 +00001110 return PP->HandleEndOfFile(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001111}
1112
1113/// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
1114/// the specified lexer will return a tok::l_paren token, 0 if it is something
1115/// else and 2 if there are no more tokens in the buffer controlled by the
1116/// lexer.
1117unsigned Lexer::isNextPPTokenLParen() {
1118 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
1119
1120 // Switch to 'skipping' mode. This will ensure that we can lex a token
1121 // without emitting diagnostics, disables macro expansion, and will cause EOF
1122 // to return an EOF token instead of popping the include stack.
1123 LexingRawMode = true;
1124
1125 // Save state that can be changed while lexing so that we can restore it.
1126 const char *TmpBufferPtr = BufferPtr;
1127
Chris Lattnerd2177732007-07-20 16:59:19 +00001128 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001129 Tok.startToken();
1130 LexTokenInternal(Tok);
1131
1132 // Restore state that may have changed.
1133 BufferPtr = TmpBufferPtr;
1134
1135 // Restore the lexer back to non-skipping mode.
1136 LexingRawMode = false;
1137
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001138 if (Tok.is(tok::eof))
Reid Spencer5f016e22007-07-11 17:01:13 +00001139 return 2;
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001140 return Tok.is(tok::l_paren);
Reid Spencer5f016e22007-07-11 17:01:13 +00001141}
1142
1143
1144/// LexTokenInternal - This implements a simple C family lexer. It is an
1145/// extremely performance critical piece of code. This assumes that the buffer
1146/// has a null character at the end of the file. Return true if an error
1147/// occurred and compilation should terminate, false if normal. This returns a
1148/// preprocessing token, not a normal token, as such, it is an internal
1149/// interface. It assumes that the Flags of result have been cleared before
1150/// calling this.
Chris Lattnerd2177732007-07-20 16:59:19 +00001151void Lexer::LexTokenInternal(Token &Result) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001152LexNextToken:
1153 // New token, can't need cleaning yet.
Chris Lattnerd2177732007-07-20 16:59:19 +00001154 Result.clearFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00001155 Result.setIdentifierInfo(0);
1156
1157 // CurPtr - Cache BufferPtr in an automatic variable.
1158 const char *CurPtr = BufferPtr;
1159
1160 // Small amounts of horizontal whitespace is very common between tokens.
1161 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
1162 ++CurPtr;
1163 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
1164 ++CurPtr;
1165 BufferPtr = CurPtr;
Chris Lattnerd2177732007-07-20 16:59:19 +00001166 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001167 }
1168
1169 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
1170
1171 // Read a character, advancing over it.
1172 char Char = getAndAdvanceChar(CurPtr, Result);
1173 switch (Char) {
1174 case 0: // Null.
1175 // Found end of file?
1176 if (CurPtr-1 == BufferEnd) {
1177 // Read the PP instance variable into an automatic variable, because
1178 // LexEndOfFile will often delete 'this'.
Chris Lattner168ae2d2007-10-17 20:41:00 +00001179 Preprocessor *PPCache = PP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001180 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
1181 return; // Got a token to return.
Chris Lattner168ae2d2007-10-17 20:41:00 +00001182 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
1183 return PPCache->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001184 }
1185
1186 Diag(CurPtr-1, diag::null_in_file);
Chris Lattnerd2177732007-07-20 16:59:19 +00001187 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001188 SkipWhitespace(Result, CurPtr);
1189 goto LexNextToken; // GCC isn't tail call eliminating.
1190 case '\n':
1191 case '\r':
1192 // If we are inside a preprocessor directive and we see the end of line,
1193 // we know we are done with the directive, so return an EOM token.
1194 if (ParsingPreprocessorDirective) {
1195 // Done parsing the "line".
1196 ParsingPreprocessorDirective = false;
1197
1198 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattner168ae2d2007-10-17 20:41:00 +00001199 KeepCommentMode = PP->getCommentRetentionState();
Reid Spencer5f016e22007-07-11 17:01:13 +00001200
1201 // Since we consumed a newline, we are back at the start of a line.
1202 IsAtStartOfLine = true;
1203
1204 Result.setKind(tok::eom);
1205 break;
1206 }
1207 // The returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00001208 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00001209 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00001210 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001211 SkipWhitespace(Result, CurPtr);
1212 goto LexNextToken; // GCC isn't tail call eliminating.
1213 case ' ':
1214 case '\t':
1215 case '\f':
1216 case '\v':
Chris Lattner8133cfc2007-07-22 06:29:05 +00001217 SkipHorizontalWhitespace:
Chris Lattnerd2177732007-07-20 16:59:19 +00001218 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001219 SkipWhitespace(Result, CurPtr);
Chris Lattner8133cfc2007-07-22 06:29:05 +00001220
1221 SkipIgnoredUnits:
1222 CurPtr = BufferPtr;
1223
1224 // If the next token is obviously a // or /* */ comment, skip it efficiently
1225 // too (without going through the big switch stmt).
1226 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !KeepCommentMode) {
1227 SkipBCPLComment(Result, CurPtr+2);
1228 goto SkipIgnoredUnits;
1229 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !KeepCommentMode) {
1230 SkipBlockComment(Result, CurPtr+2);
1231 goto SkipIgnoredUnits;
1232 } else if (isHorizontalWhitespace(*CurPtr)) {
1233 goto SkipHorizontalWhitespace;
1234 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001235 goto LexNextToken; // GCC isn't tail call eliminating.
1236
1237 case 'L':
1238 // Notify MIOpt that we read a non-whitespace/non-comment token.
1239 MIOpt.ReadToken();
1240 Char = getCharAndSize(CurPtr, SizeTmp);
1241
1242 // Wide string literal.
1243 if (Char == '"')
1244 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
1245 true);
1246
1247 // Wide character constant.
1248 if (Char == '\'')
1249 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
1250 // FALL THROUGH, treating L like the start of an identifier.
1251
1252 // C99 6.4.2: Identifiers.
1253 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
1254 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
1255 case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U':
1256 case 'V': case 'W': case 'X': case 'Y': case 'Z':
1257 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
1258 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
1259 case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u':
1260 case 'v': case 'w': case 'x': case 'y': case 'z':
1261 case '_':
1262 // Notify MIOpt that we read a non-whitespace/non-comment token.
1263 MIOpt.ReadToken();
1264 return LexIdentifier(Result, CurPtr);
1265
1266 // C99 6.4.4.1: Integer Constants.
1267 // C99 6.4.4.2: Floating Constants.
1268 case '0': case '1': case '2': case '3': case '4':
1269 case '5': case '6': case '7': case '8': case '9':
1270 // Notify MIOpt that we read a non-whitespace/non-comment token.
1271 MIOpt.ReadToken();
1272 return LexNumericConstant(Result, CurPtr);
1273
1274 // C99 6.4.4: Character Constants.
1275 case '\'':
1276 // Notify MIOpt that we read a non-whitespace/non-comment token.
1277 MIOpt.ReadToken();
1278 return LexCharConstant(Result, CurPtr);
1279
1280 // C99 6.4.5: String Literals.
1281 case '"':
1282 // Notify MIOpt that we read a non-whitespace/non-comment token.
1283 MIOpt.ReadToken();
1284 return LexStringLiteral(Result, CurPtr, false);
1285
1286 // C99 6.4.6: Punctuators.
1287 case '?':
1288 Result.setKind(tok::question);
1289 break;
1290 case '[':
1291 Result.setKind(tok::l_square);
1292 break;
1293 case ']':
1294 Result.setKind(tok::r_square);
1295 break;
1296 case '(':
1297 Result.setKind(tok::l_paren);
1298 break;
1299 case ')':
1300 Result.setKind(tok::r_paren);
1301 break;
1302 case '{':
1303 Result.setKind(tok::l_brace);
1304 break;
1305 case '}':
1306 Result.setKind(tok::r_brace);
1307 break;
1308 case '.':
1309 Char = getCharAndSize(CurPtr, SizeTmp);
1310 if (Char >= '0' && Char <= '9') {
1311 // Notify MIOpt that we read a non-whitespace/non-comment token.
1312 MIOpt.ReadToken();
1313
1314 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
1315 } else if (Features.CPlusPlus && Char == '*') {
1316 Result.setKind(tok::periodstar);
1317 CurPtr += SizeTmp;
1318 } else if (Char == '.' &&
1319 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
1320 Result.setKind(tok::ellipsis);
1321 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1322 SizeTmp2, Result);
1323 } else {
1324 Result.setKind(tok::period);
1325 }
1326 break;
1327 case '&':
1328 Char = getCharAndSize(CurPtr, SizeTmp);
1329 if (Char == '&') {
1330 Result.setKind(tok::ampamp);
1331 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1332 } else if (Char == '=') {
1333 Result.setKind(tok::ampequal);
1334 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1335 } else {
1336 Result.setKind(tok::amp);
1337 }
1338 break;
1339 case '*':
1340 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
1341 Result.setKind(tok::starequal);
1342 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1343 } else {
1344 Result.setKind(tok::star);
1345 }
1346 break;
1347 case '+':
1348 Char = getCharAndSize(CurPtr, SizeTmp);
1349 if (Char == '+') {
1350 Result.setKind(tok::plusplus);
1351 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1352 } else if (Char == '=') {
1353 Result.setKind(tok::plusequal);
1354 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1355 } else {
1356 Result.setKind(tok::plus);
1357 }
1358 break;
1359 case '-':
1360 Char = getCharAndSize(CurPtr, SizeTmp);
1361 if (Char == '-') {
1362 Result.setKind(tok::minusminus);
1363 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1364 } else if (Char == '>' && Features.CPlusPlus &&
1365 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') {
1366 Result.setKind(tok::arrowstar); // C++ ->*
1367 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1368 SizeTmp2, Result);
1369 } else if (Char == '>') {
1370 Result.setKind(tok::arrow);
1371 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1372 } else if (Char == '=') {
1373 Result.setKind(tok::minusequal);
1374 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1375 } else {
1376 Result.setKind(tok::minus);
1377 }
1378 break;
1379 case '~':
1380 Result.setKind(tok::tilde);
1381 break;
1382 case '!':
1383 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
1384 Result.setKind(tok::exclaimequal);
1385 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1386 } else {
1387 Result.setKind(tok::exclaim);
1388 }
1389 break;
1390 case '/':
1391 // 6.4.9: Comments
1392 Char = getCharAndSize(CurPtr, SizeTmp);
1393 if (Char == '/') { // BCPL comment.
Chris Lattner8133cfc2007-07-22 06:29:05 +00001394 if (SkipBCPLComment(Result, ConsumeChar(CurPtr, SizeTmp, Result))) {
1395 // It is common for the tokens immediately after a // comment to be
Chris Lattner409a0362007-07-22 18:38:25 +00001396 // whitespace (indentation for the next line). Instead of going through
1397 // the big switch, handle it efficiently now.
Chris Lattner8133cfc2007-07-22 06:29:05 +00001398 goto SkipIgnoredUnits;
1399 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001400 return; // KeepCommentMode
1401 } else if (Char == '*') { // /**/ comment.
1402 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
1403 goto LexNextToken; // GCC isn't tail call eliminating.
1404 return; // KeepCommentMode
1405 } else if (Char == '=') {
1406 Result.setKind(tok::slashequal);
1407 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1408 } else {
1409 Result.setKind(tok::slash);
1410 }
1411 break;
1412 case '%':
1413 Char = getCharAndSize(CurPtr, SizeTmp);
1414 if (Char == '=') {
1415 Result.setKind(tok::percentequal);
1416 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1417 } else if (Features.Digraphs && Char == '>') {
1418 Result.setKind(tok::r_brace); // '%>' -> '}'
1419 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1420 } else if (Features.Digraphs && Char == ':') {
1421 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1422 Char = getCharAndSize(CurPtr, SizeTmp);
1423 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
1424 Result.setKind(tok::hashhash); // '%:%:' -> '##'
1425 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1426 SizeTmp2, Result);
1427 } else if (Char == '@' && Features.Microsoft) { // %:@ -> #@ -> Charize
1428 Result.setKind(tok::hashat);
1429 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1430 Diag(BufferPtr, diag::charize_microsoft_ext);
1431 } else {
1432 Result.setKind(tok::hash); // '%:' -> '#'
1433
1434 // We parsed a # character. If this occurs at the start of the line,
1435 // it's actually the start of a preprocessing directive. Callback to
1436 // the preprocessor to handle it.
1437 // FIXME: -fpreprocessed mode??
1438 if (Result.isAtStartOfLine() && !LexingRawMode) {
1439 BufferPtr = CurPtr;
Chris Lattner168ae2d2007-10-17 20:41:00 +00001440 PP->HandleDirective(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001441
1442 // As an optimization, if the preprocessor didn't switch lexers, tail
1443 // recurse.
Chris Lattner168ae2d2007-10-17 20:41:00 +00001444 if (PP->isCurrentLexer(this)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001445 // Start a new token. If this is a #include or something, the PP may
1446 // want us starting at the beginning of the line again. If so, set
1447 // the StartOfLine flag.
1448 if (IsAtStartOfLine) {
Chris Lattnerd2177732007-07-20 16:59:19 +00001449 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00001450 IsAtStartOfLine = false;
1451 }
1452 goto LexNextToken; // GCC isn't tail call eliminating.
1453 }
1454
Chris Lattner168ae2d2007-10-17 20:41:00 +00001455 return PP->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001456 }
1457 }
1458 } else {
1459 Result.setKind(tok::percent);
1460 }
1461 break;
1462 case '<':
1463 Char = getCharAndSize(CurPtr, SizeTmp);
1464 if (ParsingFilename) {
1465 return LexAngledStringLiteral(Result, CurPtr+SizeTmp);
1466 } else if (Char == '<' &&
1467 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '=') {
1468 Result.setKind(tok::lesslessequal);
1469 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1470 SizeTmp2, Result);
1471 } else if (Char == '<') {
1472 Result.setKind(tok::lessless);
1473 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1474 } else if (Char == '=') {
1475 Result.setKind(tok::lessequal);
1476 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1477 } else if (Features.Digraphs && Char == ':') {
1478 Result.setKind(tok::l_square); // '<:' -> '['
1479 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1480 } else if (Features.Digraphs && Char == '>') {
1481 Result.setKind(tok::l_brace); // '<%' -> '{'
1482 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1483 } else {
1484 Result.setKind(tok::less);
1485 }
1486 break;
1487 case '>':
1488 Char = getCharAndSize(CurPtr, SizeTmp);
1489 if (Char == '=') {
1490 Result.setKind(tok::greaterequal);
1491 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1492 } else if (Char == '>' &&
1493 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '=') {
1494 Result.setKind(tok::greatergreaterequal);
1495 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1496 SizeTmp2, Result);
1497 } else if (Char == '>') {
1498 Result.setKind(tok::greatergreater);
1499 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1500 } else {
1501 Result.setKind(tok::greater);
1502 }
1503 break;
1504 case '^':
1505 Char = getCharAndSize(CurPtr, SizeTmp);
1506 if (Char == '=') {
1507 Result.setKind(tok::caretequal);
1508 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1509 } else {
1510 Result.setKind(tok::caret);
1511 }
1512 break;
1513 case '|':
1514 Char = getCharAndSize(CurPtr, SizeTmp);
1515 if (Char == '=') {
1516 Result.setKind(tok::pipeequal);
1517 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1518 } else if (Char == '|') {
1519 Result.setKind(tok::pipepipe);
1520 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1521 } else {
1522 Result.setKind(tok::pipe);
1523 }
1524 break;
1525 case ':':
1526 Char = getCharAndSize(CurPtr, SizeTmp);
1527 if (Features.Digraphs && Char == '>') {
1528 Result.setKind(tok::r_square); // ':>' -> ']'
1529 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1530 } else if (Features.CPlusPlus && Char == ':') {
1531 Result.setKind(tok::coloncolon);
1532 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1533 } else {
1534 Result.setKind(tok::colon);
1535 }
1536 break;
1537 case ';':
1538 Result.setKind(tok::semi);
1539 break;
1540 case '=':
1541 Char = getCharAndSize(CurPtr, SizeTmp);
1542 if (Char == '=') {
1543 Result.setKind(tok::equalequal);
1544 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1545 } else {
1546 Result.setKind(tok::equal);
1547 }
1548 break;
1549 case ',':
1550 Result.setKind(tok::comma);
1551 break;
1552 case '#':
1553 Char = getCharAndSize(CurPtr, SizeTmp);
1554 if (Char == '#') {
1555 Result.setKind(tok::hashhash);
1556 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1557 } else if (Char == '@' && Features.Microsoft) { // #@ -> Charize
1558 Result.setKind(tok::hashat);
1559 Diag(BufferPtr, diag::charize_microsoft_ext);
1560 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1561 } else {
1562 Result.setKind(tok::hash);
1563 // We parsed a # character. If this occurs at the start of the line,
1564 // it's actually the start of a preprocessing directive. Callback to
1565 // the preprocessor to handle it.
1566 // FIXME: -fpreprocessed mode??
1567 if (Result.isAtStartOfLine() && !LexingRawMode) {
1568 BufferPtr = CurPtr;
Chris Lattner168ae2d2007-10-17 20:41:00 +00001569 PP->HandleDirective(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001570
1571 // As an optimization, if the preprocessor didn't switch lexers, tail
1572 // recurse.
Chris Lattner168ae2d2007-10-17 20:41:00 +00001573 if (PP->isCurrentLexer(this)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001574 // Start a new token. If this is a #include or something, the PP may
1575 // want us starting at the beginning of the line again. If so, set
1576 // the StartOfLine flag.
1577 if (IsAtStartOfLine) {
Chris Lattnerd2177732007-07-20 16:59:19 +00001578 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00001579 IsAtStartOfLine = false;
1580 }
1581 goto LexNextToken; // GCC isn't tail call eliminating.
1582 }
Chris Lattner168ae2d2007-10-17 20:41:00 +00001583 return PP->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001584 }
1585 }
1586 break;
1587
1588 case '\\':
1589 // FIXME: UCN's.
1590 // FALL THROUGH.
1591 default:
1592 // Objective C support.
1593 if (CurPtr[-1] == '@' && Features.ObjC1) {
1594 Result.setKind(tok::at);
1595 break;
1596 } else if (CurPtr[-1] == '$' && Features.DollarIdents) {// $ in identifiers.
1597 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
1598 // Notify MIOpt that we read a non-whitespace/non-comment token.
1599 MIOpt.ReadToken();
1600 return LexIdentifier(Result, CurPtr);
1601 }
1602
1603 Result.setKind(tok::unknown);
1604 break;
1605 }
1606
1607 // Notify MIOpt that we read a non-whitespace/non-comment token.
1608 MIOpt.ReadToken();
1609
1610 // Update the location of token as well as BufferPtr.
1611 FormTokenWithChars(Result, CurPtr);
1612}