blob: 4e93600a87763b13854f833dc64412df4765bd55 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- Lexer.cpp - C Language Family Lexer ------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Lexer and Token interfaces.
11//
12//===----------------------------------------------------------------------===//
13//
14// TODO: GCC Diagnostics emitted by the lexer:
15// PEDWARN: (form feed|vertical tab) in preprocessing directive
16//
17// Universal characters, unicode, char mapping:
18// WARNING: `%.*s' is not in NFKC
19// WARNING: `%.*s' is not in NFC
20//
21// Other:
22// TODO: Options to support:
23// -fexec-charset,-fwide-exec-charset
24//
25//===----------------------------------------------------------------------===//
26
27#include "clang/Lex/Lexer.h"
28#include "clang/Lex/Preprocessor.h"
29#include "clang/Basic/Diagnostic.h"
30#include "clang/Basic/SourceManager.h"
31#include "llvm/Support/Compiler.h"
32#include "llvm/Support/MemoryBuffer.h"
33#include <cctype>
34using namespace clang;
35
36static void InitCharacterInfo();
37
Chris Lattneraa9bdf12007-10-07 08:47:24 +000038//===----------------------------------------------------------------------===//
39// Token Class Implementation
40//===----------------------------------------------------------------------===//
41
42/// isObjCAtKeyword - Return true if we have an ObjC keyword identifier.
43bool Token::isObjCAtKeyword(tok::ObjCKeywordKind objcKey) const {
Chris Lattnercb8e41c2007-10-09 18:02:16 +000044 return is(tok::identifier) &&
45 getIdentifierInfo()->getObjCKeywordID() == objcKey;
Chris Lattneraa9bdf12007-10-07 08:47:24 +000046}
47
48/// getObjCKeywordID - Return the ObjC keyword kind.
49tok::ObjCKeywordKind Token::getObjCKeywordID() const {
50 IdentifierInfo *specId = getIdentifierInfo();
51 return specId ? specId->getObjCKeywordID() : tok::objc_not_keyword;
52}
53
Chris Lattner7208a4b2007-12-13 01:59:49 +000054
Chris Lattneraa9bdf12007-10-07 08:47:24 +000055//===----------------------------------------------------------------------===//
56// Lexer Class Implementation
57//===----------------------------------------------------------------------===//
58
59
Chris Lattner342dccb2007-10-17 20:41:00 +000060/// Lexer constructor - Create a new lexer object for the specified buffer
61/// with the specified preprocessor managing the lexing process. This lexer
62/// assumes that the associated file buffer and Preprocessor objects will
63/// outlive it, so it doesn't take ownership of either of them.
Chris Lattner4b009652007-07-25 00:24:17 +000064Lexer::Lexer(SourceLocation fileloc, Preprocessor &pp,
65 const char *BufStart, const char *BufEnd)
Ted Kremenek7ecfa132008-11-12 23:13:54 +000066 : PreprocessorLexer(&pp), FileLoc(fileloc), 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)
Ted Kremenek7ecfa132008-11-12 23:13:54 +0000113 : PreprocessorLexer(0), FileLoc(fileloc), Features(features) {
Chris Lattner342dccb2007-10-17 20:41:00 +0000114 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}
Chris Lattner4b009652007-07-25 00:24:17 +0000315
316//===----------------------------------------------------------------------===//
317// Trigraph and Escaped Newline Handling Code.
318//===----------------------------------------------------------------------===//
319
320/// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
321/// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
322static char GetTrigraphCharForLetter(char Letter) {
323 switch (Letter) {
324 default: return 0;
325 case '=': return '#';
326 case ')': return ']';
327 case '(': return '[';
328 case '!': return '|';
329 case '\'': return '^';
330 case '>': return '}';
331 case '/': return '\\';
332 case '<': return '{';
333 case '-': return '~';
334 }
335}
336
337/// DecodeTrigraphChar - If the specified character is a legal trigraph when
338/// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
339/// return the result character. Finally, emit a warning about trigraph use
340/// whether trigraphs are enabled or not.
341static char DecodeTrigraphChar(const char *CP, Lexer *L) {
342 char Res = GetTrigraphCharForLetter(*CP);
343 if (Res && L) {
344 if (!L->getFeatures().Trigraphs) {
345 L->Diag(CP-2, diag::trigraph_ignored);
346 return 0;
347 } else {
348 L->Diag(CP-2, diag::trigraph_converted, std::string()+Res);
349 }
350 }
351 return Res;
352}
353
354/// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
355/// get its size, and return it. This is tricky in several cases:
356/// 1. If currently at the start of a trigraph, we warn about the trigraph,
357/// then either return the trigraph (skipping 3 chars) or the '?',
358/// depending on whether trigraphs are enabled or not.
359/// 2. If this is an escaped newline (potentially with whitespace between
360/// the backslash and newline), implicitly skip the newline and return
361/// the char after it.
362/// 3. If this is a UCN, return it. FIXME: C++ UCN's?
363///
364/// This handles the slow/uncommon case of the getCharAndSize method. Here we
365/// know that we can accumulate into Size, and that we have already incremented
366/// Ptr by Size bytes.
367///
368/// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
369/// be updated to match.
370///
371char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
372 Token *Tok) {
373 // If we have a slash, look for an escaped newline.
374 if (Ptr[0] == '\\') {
375 ++Size;
376 ++Ptr;
377Slash:
378 // Common case, backslash-char where the char is not whitespace.
379 if (!isWhitespace(Ptr[0])) return '\\';
380
381 // See if we have optional whitespace characters followed by a newline.
382 {
383 unsigned SizeTmp = 0;
384 do {
385 ++SizeTmp;
386 if (Ptr[SizeTmp-1] == '\n' || Ptr[SizeTmp-1] == '\r') {
387 // Remember that this token needs to be cleaned.
388 if (Tok) Tok->setFlag(Token::NeedsCleaning);
389
390 // Warn if there was whitespace between the backslash and newline.
391 if (SizeTmp != 1 && Tok)
392 Diag(Ptr, diag::backslash_newline_space);
393
394 // If this is a \r\n or \n\r, skip the newlines.
395 if ((Ptr[SizeTmp] == '\r' || Ptr[SizeTmp] == '\n') &&
396 Ptr[SizeTmp-1] != Ptr[SizeTmp])
397 ++SizeTmp;
398
399 // Found backslash<whitespace><newline>. Parse the char after it.
400 Size += SizeTmp;
401 Ptr += SizeTmp;
402 // Use slow version to accumulate a correct size field.
403 return getCharAndSizeSlow(Ptr, Size, Tok);
404 }
405 } while (isWhitespace(Ptr[SizeTmp]));
406 }
407
408 // Otherwise, this is not an escaped newline, just return the slash.
409 return '\\';
410 }
411
412 // If this is a trigraph, process it.
413 if (Ptr[0] == '?' && Ptr[1] == '?') {
414 // If this is actually a legal trigraph (not something like "??x"), emit
415 // a trigraph warning. If so, and if trigraphs are enabled, return it.
416 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : 0)) {
417 // Remember that this token needs to be cleaned.
418 if (Tok) Tok->setFlag(Token::NeedsCleaning);
419
420 Ptr += 3;
421 Size += 3;
422 if (C == '\\') goto Slash;
423 return C;
424 }
425 }
426
427 // If this is neither, return a single character.
428 ++Size;
429 return *Ptr;
430}
431
432
433/// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
434/// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
435/// and that we have already incremented Ptr by Size bytes.
436///
437/// NOTE: When this method is updated, getCharAndSizeSlow (above) should
438/// be updated to match.
439char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
440 const LangOptions &Features) {
441 // If we have a slash, look for an escaped newline.
442 if (Ptr[0] == '\\') {
443 ++Size;
444 ++Ptr;
445Slash:
446 // Common case, backslash-char where the char is not whitespace.
447 if (!isWhitespace(Ptr[0])) return '\\';
448
449 // See if we have optional whitespace characters followed by a newline.
450 {
451 unsigned SizeTmp = 0;
452 do {
453 ++SizeTmp;
454 if (Ptr[SizeTmp-1] == '\n' || Ptr[SizeTmp-1] == '\r') {
455
456 // If this is a \r\n or \n\r, skip the newlines.
457 if ((Ptr[SizeTmp] == '\r' || Ptr[SizeTmp] == '\n') &&
458 Ptr[SizeTmp-1] != Ptr[SizeTmp])
459 ++SizeTmp;
460
461 // Found backslash<whitespace><newline>. Parse the char after it.
462 Size += SizeTmp;
463 Ptr += SizeTmp;
464
465 // Use slow version to accumulate a correct size field.
466 return getCharAndSizeSlowNoWarn(Ptr, Size, Features);
467 }
468 } while (isWhitespace(Ptr[SizeTmp]));
469 }
470
471 // Otherwise, this is not an escaped newline, just return the slash.
472 return '\\';
473 }
474
475 // If this is a trigraph, process it.
476 if (Features.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
477 // If this is actually a legal trigraph (not something like "??x"), return
478 // it.
479 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
480 Ptr += 3;
481 Size += 3;
482 if (C == '\\') goto Slash;
483 return C;
484 }
485 }
486
487 // If this is neither, return a single character.
488 ++Size;
489 return *Ptr;
490}
491
492//===----------------------------------------------------------------------===//
493// Helper methods for lexing.
494//===----------------------------------------------------------------------===//
495
496void Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
497 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
498 unsigned Size;
499 unsigned char C = *CurPtr++;
500 while (isIdentifierBody(C)) {
501 C = *CurPtr++;
502 }
503 --CurPtr; // Back up over the skipped character.
504
505 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
506 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
507 // FIXME: UCNs.
508 if (C != '\\' && C != '?' && (C != '$' || !Features.DollarIdents)) {
509FinishIdentifier:
510 const char *IdStart = BufferPtr;
Chris Lattner0344cc72008-10-12 04:51:35 +0000511 FormTokenWithChars(Result, CurPtr, tok::identifier);
Chris Lattner4b009652007-07-25 00:24:17 +0000512
513 // If we are in raw mode, return this identifier raw. There is no need to
514 // look up identifier information or attempt to macro expand it.
515 if (LexingRawMode) return;
516
517 // Fill in Result.IdentifierInfo, looking up the identifier in the
518 // identifier table.
Chris Lattner342dccb2007-10-17 20:41:00 +0000519 PP->LookUpIdentifierInfo(Result, IdStart);
Chris Lattner4b009652007-07-25 00:24:17 +0000520
521 // Finally, now that we know we have an identifier, pass this off to the
522 // preprocessor, which may macro expand it or something.
Chris Lattner342dccb2007-10-17 20:41:00 +0000523 return PP->HandleIdentifier(Result);
Chris Lattner4b009652007-07-25 00:24:17 +0000524 }
525
526 // Otherwise, $,\,? in identifier found. Enter slower path.
527
528 C = getCharAndSize(CurPtr, Size);
529 while (1) {
530 if (C == '$') {
531 // If we hit a $ and they are not supported in identifiers, we are done.
532 if (!Features.DollarIdents) goto FinishIdentifier;
533
534 // Otherwise, emit a diagnostic and continue.
535 Diag(CurPtr, diag::ext_dollar_in_identifier);
536 CurPtr = ConsumeChar(CurPtr, Size, Result);
537 C = getCharAndSize(CurPtr, Size);
538 continue;
539 } else if (!isIdentifierBody(C)) { // FIXME: UCNs.
540 // Found end of identifier.
541 goto FinishIdentifier;
542 }
543
544 // Otherwise, this character is good, consume it.
545 CurPtr = ConsumeChar(CurPtr, Size, Result);
546
547 C = getCharAndSize(CurPtr, Size);
548 while (isIdentifierBody(C)) { // FIXME: UCNs.
549 CurPtr = ConsumeChar(CurPtr, Size, Result);
550 C = getCharAndSize(CurPtr, Size);
551 }
552 }
553}
554
555
Nate Begeman937cac72008-04-14 02:26:39 +0000556/// LexNumericConstant - Lex the remainder of a integer or floating point
Chris Lattner4b009652007-07-25 00:24:17 +0000557/// constant. From[-1] is the first character lexed. Return the end of the
558/// constant.
559void Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
560 unsigned Size;
561 char C = getCharAndSize(CurPtr, Size);
562 char PrevCh = 0;
563 while (isNumberBody(C)) { // FIXME: UCNs?
564 CurPtr = ConsumeChar(CurPtr, Size, Result);
565 PrevCh = C;
566 C = getCharAndSize(CurPtr, Size);
567 }
568
569 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
570 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e'))
571 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
572
573 // If we have a hex FP constant, continue.
574 if (Features.HexFloats &&
575 (C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p'))
576 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
577
Chris Lattner4b009652007-07-25 00:24:17 +0000578 // Update the location of token as well as BufferPtr.
Chris Lattner0344cc72008-10-12 04:51:35 +0000579 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
Chris Lattner4b009652007-07-25 00:24:17 +0000580}
581
582/// LexStringLiteral - Lex the remainder of a string literal, after having lexed
583/// either " or L".
Chris Lattner867a87b2008-10-12 04:05:48 +0000584void Lexer::LexStringLiteral(Token &Result, const char *CurPtr, bool Wide) {
Chris Lattner4b009652007-07-25 00:24:17 +0000585 const char *NulCharacter = 0; // Does this string contain the \0 character?
586
587 char C = getAndAdvanceChar(CurPtr, Result);
588 while (C != '"') {
589 // Skip escaped characters.
590 if (C == '\\') {
591 // Skip the escaped character.
592 C = getAndAdvanceChar(CurPtr, Result);
593 } else if (C == '\n' || C == '\r' || // Newline.
594 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
595 if (!LexingRawMode) Diag(BufferPtr, diag::err_unterminated_string);
Chris Lattner0344cc72008-10-12 04:51:35 +0000596 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Chris Lattner4b009652007-07-25 00:24:17 +0000597 return;
598 } else if (C == 0) {
599 NulCharacter = CurPtr-1;
600 }
601 C = getAndAdvanceChar(CurPtr, Result);
602 }
603
604 // If a nul character existed in the string, warn about it.
605 if (NulCharacter) Diag(NulCharacter, diag::null_in_string);
606
Chris Lattner4b009652007-07-25 00:24:17 +0000607 // Update the location of the token as well as the BufferPtr instance var.
Chris Lattner0344cc72008-10-12 04:51:35 +0000608 FormTokenWithChars(Result, CurPtr,
609 Wide ? tok::wide_string_literal : tok::string_literal);
Chris Lattner4b009652007-07-25 00:24:17 +0000610}
611
612/// LexAngledStringLiteral - Lex the remainder of an angled string literal,
613/// after having lexed the '<' character. This is used for #include filenames.
614void Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
615 const char *NulCharacter = 0; // Does this string contain the \0 character?
616
617 char C = getAndAdvanceChar(CurPtr, Result);
618 while (C != '>') {
619 // Skip escaped characters.
620 if (C == '\\') {
621 // Skip the escaped character.
622 C = getAndAdvanceChar(CurPtr, Result);
623 } else if (C == '\n' || C == '\r' || // Newline.
624 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
625 if (!LexingRawMode) Diag(BufferPtr, diag::err_unterminated_string);
Chris Lattner0344cc72008-10-12 04:51:35 +0000626 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Chris Lattner4b009652007-07-25 00:24:17 +0000627 return;
628 } else if (C == 0) {
629 NulCharacter = CurPtr-1;
630 }
631 C = getAndAdvanceChar(CurPtr, Result);
632 }
633
634 // If a nul character existed in the string, warn about it.
635 if (NulCharacter) Diag(NulCharacter, diag::null_in_string);
636
Chris Lattner4b009652007-07-25 00:24:17 +0000637 // Update the location of token as well as BufferPtr.
Chris Lattner0344cc72008-10-12 04:51:35 +0000638 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
Chris Lattner4b009652007-07-25 00:24:17 +0000639}
640
641
642/// LexCharConstant - Lex the remainder of a character constant, after having
643/// lexed either ' or L'.
644void Lexer::LexCharConstant(Token &Result, const char *CurPtr) {
645 const char *NulCharacter = 0; // Does this character contain the \0 character?
646
647 // Handle the common case of 'x' and '\y' efficiently.
648 char C = getAndAdvanceChar(CurPtr, Result);
649 if (C == '\'') {
650 if (!LexingRawMode) Diag(BufferPtr, diag::err_empty_character);
Chris Lattner0344cc72008-10-12 04:51:35 +0000651 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner4b009652007-07-25 00:24:17 +0000652 return;
653 } else if (C == '\\') {
654 // Skip the escaped character.
655 // FIXME: UCN's.
656 C = getAndAdvanceChar(CurPtr, Result);
657 }
658
659 if (C && C != '\n' && C != '\r' && CurPtr[0] == '\'') {
660 ++CurPtr;
661 } else {
662 // Fall back on generic code for embedded nulls, newlines, wide chars.
663 do {
664 // Skip escaped characters.
665 if (C == '\\') {
666 // Skip the escaped character.
667 C = getAndAdvanceChar(CurPtr, Result);
668 } else if (C == '\n' || C == '\r' || // Newline.
669 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
670 if (!LexingRawMode) Diag(BufferPtr, diag::err_unterminated_char);
Chris Lattner0344cc72008-10-12 04:51:35 +0000671 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Chris Lattner4b009652007-07-25 00:24:17 +0000672 return;
673 } else if (C == 0) {
674 NulCharacter = CurPtr-1;
675 }
676 C = getAndAdvanceChar(CurPtr, Result);
677 } while (C != '\'');
678 }
679
680 if (NulCharacter) Diag(NulCharacter, diag::null_in_char);
681
Chris Lattner4b009652007-07-25 00:24:17 +0000682 // Update the location of token as well as BufferPtr.
Chris Lattner0344cc72008-10-12 04:51:35 +0000683 FormTokenWithChars(Result, CurPtr, tok::char_constant);
Chris Lattner4b009652007-07-25 00:24:17 +0000684}
685
686/// SkipWhitespace - Efficiently skip over a series of whitespace characters.
687/// Update BufferPtr to point to the next non-whitespace character and return.
Chris Lattner867a87b2008-10-12 04:05:48 +0000688///
689/// This method forms a token and returns true if KeepWhitespaceMode is enabled.
690///
691bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr) {
Chris Lattner4b009652007-07-25 00:24:17 +0000692 // Whitespace - Skip it, then return the token after the whitespace.
693 unsigned char Char = *CurPtr; // Skip consequtive spaces efficiently.
694 while (1) {
695 // Skip horizontal whitespace very aggressively.
696 while (isHorizontalWhitespace(Char))
697 Char = *++CurPtr;
698
699 // Otherwise if we something other than whitespace, we're done.
700 if (Char != '\n' && Char != '\r')
701 break;
702
703 if (ParsingPreprocessorDirective) {
704 // End of preprocessor directive line, let LexTokenInternal handle this.
705 BufferPtr = CurPtr;
Chris Lattner867a87b2008-10-12 04:05:48 +0000706 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000707 }
708
709 // ok, but handle newline.
710 // The returned token is at the start of the line.
711 Result.setFlag(Token::StartOfLine);
712 // No leading whitespace seen so far.
713 Result.clearFlag(Token::LeadingSpace);
714 Char = *++CurPtr;
715 }
716
717 // If this isn't immediately after a newline, there is leading space.
718 char PrevChar = CurPtr[-1];
719 if (PrevChar != '\n' && PrevChar != '\r')
720 Result.setFlag(Token::LeadingSpace);
721
Chris Lattner867a87b2008-10-12 04:05:48 +0000722 // If the client wants us to return whitespace, return it now.
723 if (isKeepWhitespaceMode()) {
Chris Lattner0344cc72008-10-12 04:51:35 +0000724 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner867a87b2008-10-12 04:05:48 +0000725 return true;
726 }
727
Chris Lattner4b009652007-07-25 00:24:17 +0000728 BufferPtr = CurPtr;
Chris Lattner867a87b2008-10-12 04:05:48 +0000729 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000730}
731
732// SkipBCPLComment - We have just read the // characters from input. Skip until
733// we find the newline character thats terminate the comment. Then update
Chris Lattnerf03b00c2008-10-12 04:15:42 +0000734/// BufferPtr and return. If we're in KeepCommentMode, this will form the token
735/// and return true.
Chris Lattner4b009652007-07-25 00:24:17 +0000736bool Lexer::SkipBCPLComment(Token &Result, const char *CurPtr) {
737 // If BCPL comments aren't explicitly enabled for this language, emit an
738 // extension warning.
739 if (!Features.BCPLComment) {
740 Diag(BufferPtr, diag::ext_bcpl_comment);
741
742 // Mark them enabled so we only emit one warning for this translation
743 // unit.
744 Features.BCPLComment = true;
745 }
746
747 // Scan over the body of the comment. The common case, when scanning, is that
748 // the comment contains normal ascii characters with nothing interesting in
749 // them. As such, optimize for this case with the inner loop.
750 char C;
751 do {
752 C = *CurPtr;
753 // FIXME: Speedup BCPL comment lexing. Just scan for a \n or \r character.
754 // If we find a \n character, scan backwards, checking to see if it's an
755 // escaped newline, like we do for block comments.
756
757 // Skip over characters in the fast loop.
758 while (C != 0 && // Potentially EOF.
759 C != '\\' && // Potentially escaped newline.
760 C != '?' && // Potentially trigraph.
761 C != '\n' && C != '\r') // Newline or DOS-style newline.
762 C = *++CurPtr;
763
764 // If this is a newline, we're done.
765 if (C == '\n' || C == '\r')
766 break; // Found the newline? Break out!
767
768 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
769 // properly decode the character.
770 const char *OldPtr = CurPtr;
771 C = getAndAdvanceChar(CurPtr, Result);
772
773 // If we read multiple characters, and one of those characters was a \r or
774 // \n, then we had an escaped newline within the comment. Emit diagnostic
775 // unless the next line is also a // comment.
776 if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') {
777 for (; OldPtr != CurPtr; ++OldPtr)
778 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
779 // Okay, we found a // comment that ends in a newline, if the next
780 // line is also a // comment, but has spaces, don't emit a diagnostic.
781 if (isspace(C)) {
782 const char *ForwardPtr = CurPtr;
783 while (isspace(*ForwardPtr)) // Skip whitespace.
784 ++ForwardPtr;
785 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
786 break;
787 }
788
789 Diag(OldPtr-1, diag::ext_multi_line_bcpl_comment);
790 break;
791 }
792 }
793
794 if (CurPtr == BufferEnd+1) { --CurPtr; break; }
795 } while (C != '\n' && C != '\r');
796
797 // Found but did not consume the newline.
798
799 // If we are returning comments as tokens, return this comment as a token.
Chris Lattner170adb12008-10-12 03:22:02 +0000800 if (inKeepCommentMode())
Chris Lattner4b009652007-07-25 00:24:17 +0000801 return SaveBCPLComment(Result, CurPtr);
802
803 // If we are inside a preprocessor directive and we see the end of line,
804 // return immediately, so that the lexer can return this as an EOM token.
805 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
806 BufferPtr = CurPtr;
Chris Lattnerf03b00c2008-10-12 04:15:42 +0000807 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000808 }
809
810 // Otherwise, eat the \n character. We don't care if this is a \n\r or
Chris Lattner43d38202008-10-12 00:23:07 +0000811 // \r\n sequence. This is an efficiency hack (because we know the \n can't
Chris Lattner867a87b2008-10-12 04:05:48 +0000812 // contribute to another token), it isn't needed for correctness. Note that
813 // this is ok even in KeepWhitespaceMode, because we would have returned the
814 /// comment above in that mode.
Chris Lattner4b009652007-07-25 00:24:17 +0000815 ++CurPtr;
816
817 // The next returned token is at the start of the line.
818 Result.setFlag(Token::StartOfLine);
819 // No leading whitespace seen so far.
820 Result.clearFlag(Token::LeadingSpace);
821 BufferPtr = CurPtr;
Chris Lattnerf03b00c2008-10-12 04:15:42 +0000822 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000823}
824
825/// SaveBCPLComment - If in save-comment mode, package up this BCPL comment in
826/// an appropriate way and return it.
827bool Lexer::SaveBCPLComment(Token &Result, const char *CurPtr) {
Chris Lattner0344cc72008-10-12 04:51:35 +0000828 // If we're not in a preprocessor directive, just return the // comment
829 // directly.
830 FormTokenWithChars(Result, CurPtr, tok::comment);
Chris Lattner4b009652007-07-25 00:24:17 +0000831
Chris Lattner0344cc72008-10-12 04:51:35 +0000832 if (!ParsingPreprocessorDirective)
833 return true;
834
835 // If this BCPL-style comment is in a macro definition, transmogrify it into
836 // a C-style block comment.
837 std::string Spelling = PP->getSpelling(Result);
838 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not bcpl comment?");
839 Spelling[1] = '*'; // Change prefix to "/*".
840 Spelling += "*/"; // add suffix.
841
842 Result.setKind(tok::comment);
843 Result.setLocation(PP->CreateString(&Spelling[0], Spelling.size(),
844 Result.getLocation()));
845 Result.setLength(Spelling.size());
Chris Lattnerf03b00c2008-10-12 04:15:42 +0000846 return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000847}
848
849/// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
850/// character (either \n or \r) is part of an escaped newline sequence. Issue a
851/// diagnostic if so. We know that the is inside of a block comment.
852static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
853 Lexer *L) {
854 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
855
856 // Back up off the newline.
857 --CurPtr;
858
859 // If this is a two-character newline sequence, skip the other character.
860 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
861 // \n\n or \r\r -> not escaped newline.
862 if (CurPtr[0] == CurPtr[1])
863 return false;
864 // \n\r or \r\n -> skip the newline.
865 --CurPtr;
866 }
867
868 // If we have horizontal whitespace, skip over it. We allow whitespace
869 // between the slash and newline.
870 bool HasSpace = false;
871 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
872 --CurPtr;
873 HasSpace = true;
874 }
875
876 // If we have a slash, we know this is an escaped newline.
877 if (*CurPtr == '\\') {
878 if (CurPtr[-1] != '*') return false;
879 } else {
880 // It isn't a slash, is it the ?? / trigraph?
881 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
882 CurPtr[-3] != '*')
883 return false;
884
885 // This is the trigraph ending the comment. Emit a stern warning!
886 CurPtr -= 2;
887
888 // If no trigraphs are enabled, warn that we ignored this trigraph and
889 // ignore this * character.
890 if (!L->getFeatures().Trigraphs) {
891 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
892 return false;
893 }
894 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
895 }
896
897 // Warn about having an escaped newline between the */ characters.
898 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
899
900 // If there was space between the backslash and newline, warn about it.
901 if (HasSpace) L->Diag(CurPtr, diag::backslash_newline_space);
902
903 return true;
904}
905
906#ifdef __SSE2__
907#include <emmintrin.h>
908#elif __ALTIVEC__
909#include <altivec.h>
910#undef bool
911#endif
912
913/// SkipBlockComment - We have just read the /* characters from input. Read
914/// until we find the */ characters that terminate the comment. Note that we
915/// don't bother decoding trigraphs or escaped newlines in block comments,
916/// because they cannot cause the comment to end. The only thing that can
917/// happen is the comment could end with an escaped newline between the */ end
918/// of comment.
Chris Lattnerf03b00c2008-10-12 04:15:42 +0000919///
920/// If KeepCommentMode is enabled, this forms a token from the comment and
921/// returns true.
Chris Lattner4b009652007-07-25 00:24:17 +0000922bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr) {
923 // Scan one character past where we should, looking for a '/' character. Once
924 // we find it, check to see if it was preceeded by a *. This common
925 // optimization helps people who like to put a lot of * characters in their
926 // comments.
927
928 // The first character we get with newlines and trigraphs skipped to handle
929 // the degenerate /*/ case below correctly if the * has an escaped newline
930 // after it.
931 unsigned CharSize;
932 unsigned char C = getCharAndSize(CurPtr, CharSize);
933 CurPtr += CharSize;
934 if (C == 0 && CurPtr == BufferEnd+1) {
Chris Lattnere5eca952008-10-12 01:31:51 +0000935 if (!LexingRawMode)
936 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattnerd66f4542008-10-12 04:19:49 +0000937 --CurPtr;
938
939 // KeepWhitespaceMode should return this broken comment as a token. Since
940 // it isn't a well formed comment, just return it as an 'unknown' token.
941 if (isKeepWhitespaceMode()) {
Chris Lattner0344cc72008-10-12 04:51:35 +0000942 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd66f4542008-10-12 04:19:49 +0000943 return true;
944 }
945
946 BufferPtr = CurPtr;
Chris Lattnerf03b00c2008-10-12 04:15:42 +0000947 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000948 }
949
950 // Check to see if the first character after the '/*' is another /. If so,
951 // then this slash does not end the block comment, it is part of it.
952 if (C == '/')
953 C = *CurPtr++;
954
955 while (1) {
956 // Skip over all non-interesting characters until we find end of buffer or a
957 // (probably ending) '/' character.
958 if (CurPtr + 24 < BufferEnd) {
959 // While not aligned to a 16-byte boundary.
960 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
961 C = *CurPtr++;
962
963 if (C == '/') goto FoundSlash;
964
965#ifdef __SSE2__
966 __m128i Slashes = _mm_set_epi8('/', '/', '/', '/', '/', '/', '/', '/',
967 '/', '/', '/', '/', '/', '/', '/', '/');
968 while (CurPtr+16 <= BufferEnd &&
969 _mm_movemask_epi8(_mm_cmpeq_epi8(*(__m128i*)CurPtr, Slashes)) == 0)
970 CurPtr += 16;
971#elif __ALTIVEC__
972 __vector unsigned char Slashes = {
973 '/', '/', '/', '/', '/', '/', '/', '/',
974 '/', '/', '/', '/', '/', '/', '/', '/'
975 };
976 while (CurPtr+16 <= BufferEnd &&
977 !vec_any_eq(*(vector unsigned char*)CurPtr, Slashes))
978 CurPtr += 16;
979#else
980 // Scan for '/' quickly. Many block comments are very large.
981 while (CurPtr[0] != '/' &&
982 CurPtr[1] != '/' &&
983 CurPtr[2] != '/' &&
984 CurPtr[3] != '/' &&
985 CurPtr+4 < BufferEnd) {
986 CurPtr += 4;
987 }
988#endif
989
990 // It has to be one of the bytes scanned, increment to it and read one.
991 C = *CurPtr++;
992 }
993
994 // Loop to scan the remainder.
995 while (C != '/' && C != '\0')
996 C = *CurPtr++;
997
998 FoundSlash:
999 if (C == '/') {
1000 if (CurPtr[-2] == '*') // We found the final */. We're done!
1001 break;
1002
1003 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
1004 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
1005 // We found the final */, though it had an escaped newline between the
1006 // * and /. We're done!
1007 break;
1008 }
1009 }
1010 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
1011 // If this is a /* inside of the comment, emit a warning. Don't do this
1012 // if this is a /*/, which will end the comment. This misses cases with
1013 // embedded escaped newlines, but oh well.
Chris Lattnere5eca952008-10-12 01:31:51 +00001014 Diag(CurPtr-1, diag::warn_nested_block_comment);
Chris Lattner4b009652007-07-25 00:24:17 +00001015 }
1016 } else if (C == 0 && CurPtr == BufferEnd+1) {
Chris Lattnere5eca952008-10-12 01:31:51 +00001017 if (!LexingRawMode) Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner4b009652007-07-25 00:24:17 +00001018 // Note: the user probably forgot a */. We could continue immediately
1019 // after the /*, but this would involve lexing a lot of what really is the
1020 // comment, which surely would confuse the parser.
Chris Lattnerd66f4542008-10-12 04:19:49 +00001021 --CurPtr;
1022
1023 // KeepWhitespaceMode should return this broken comment as a token. Since
1024 // it isn't a well formed comment, just return it as an 'unknown' token.
1025 if (isKeepWhitespaceMode()) {
Chris Lattner0344cc72008-10-12 04:51:35 +00001026 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd66f4542008-10-12 04:19:49 +00001027 return true;
1028 }
1029
1030 BufferPtr = CurPtr;
Chris Lattnerf03b00c2008-10-12 04:15:42 +00001031 return false;
Chris Lattner4b009652007-07-25 00:24:17 +00001032 }
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 Lattner0344cc72008-10-12 04:51:35 +00001038 FormTokenWithChars(Result, CurPtr, tok::comment);
Chris Lattnerf03b00c2008-10-12 04:15:42 +00001039 return true;
Chris Lattner4b009652007-07-25 00:24:17 +00001040 }
1041
1042 // It is common for the tokens immediately after a /**/ comment to be
1043 // whitespace. Instead of going through the big switch, handle it
Chris Lattner867a87b2008-10-12 04:05:48 +00001044 // efficiently now. This is safe even in KeepWhitespaceMode because we would
1045 // have already returned above with the comment as a token.
Chris Lattner4b009652007-07-25 00:24:17 +00001046 if (isHorizontalWhitespace(*CurPtr)) {
1047 Result.setFlag(Token::LeadingSpace);
1048 SkipWhitespace(Result, CurPtr+1);
Chris Lattnerf03b00c2008-10-12 04:15:42 +00001049 return false;
Chris Lattner4b009652007-07-25 00:24:17 +00001050 }
1051
1052 // Otherwise, just return so that the next character will be lexed as a token.
1053 BufferPtr = CurPtr;
1054 Result.setFlag(Token::LeadingSpace);
Chris Lattnerf03b00c2008-10-12 04:15:42 +00001055 return false;
Chris Lattner4b009652007-07-25 00:24:17 +00001056}
1057
1058//===----------------------------------------------------------------------===//
1059// Primary Lexing Entry Points
1060//===----------------------------------------------------------------------===//
1061
Chris Lattner4b009652007-07-25 00:24:17 +00001062/// ReadToEndOfLine - Read the rest of the current preprocessor line as an
1063/// uninterpreted string. This switches the lexer out of directive mode.
1064std::string Lexer::ReadToEndOfLine() {
1065 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
1066 "Must be in a preprocessing directive!");
1067 std::string Result;
1068 Token Tmp;
1069
1070 // CurPtr - Cache BufferPtr in an automatic variable.
1071 const char *CurPtr = BufferPtr;
1072 while (1) {
1073 char Char = getAndAdvanceChar(CurPtr, Tmp);
1074 switch (Char) {
1075 default:
1076 Result += Char;
1077 break;
1078 case 0: // Null.
1079 // Found end of file?
1080 if (CurPtr-1 != BufferEnd) {
1081 // Nope, normal character, continue.
1082 Result += Char;
1083 break;
1084 }
1085 // FALL THROUGH.
1086 case '\r':
1087 case '\n':
1088 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
1089 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
1090 BufferPtr = CurPtr-1;
1091
1092 // Next, lex the character, which should handle the EOM transition.
1093 Lex(Tmp);
Chris Lattnercb8e41c2007-10-09 18:02:16 +00001094 assert(Tmp.is(tok::eom) && "Unexpected token!");
Chris Lattner4b009652007-07-25 00:24:17 +00001095
1096 // Finally, we're done, return the string we found.
1097 return Result;
1098 }
1099 }
1100}
1101
1102/// LexEndOfFile - CurPtr points to the end of this file. Handle this
1103/// condition, reporting diagnostics and handling other edge cases as required.
1104/// This returns true if Result contains a token, false if PP.Lex should be
1105/// called again.
1106bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
1107 // If we hit the end of the file while parsing a preprocessor directive,
1108 // end the preprocessor directive first. The next token returned will
1109 // then be the end of file.
1110 if (ParsingPreprocessorDirective) {
1111 // Done parsing the "line".
1112 ParsingPreprocessorDirective = false;
Chris Lattner4b009652007-07-25 00:24:17 +00001113 // Update the location of token as well as BufferPtr.
Chris Lattner0344cc72008-10-12 04:51:35 +00001114 FormTokenWithChars(Result, CurPtr, tok::eom);
Chris Lattner4b009652007-07-25 00:24:17 +00001115
1116 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattner1c1bed12008-10-12 03:27:19 +00001117 SetCommentRetentionState(PP->getCommentRetentionState());
Chris Lattner4b009652007-07-25 00:24:17 +00001118 return true; // Have a token.
1119 }
1120
1121 // If we are in raw mode, return this event as an EOF token. Let the caller
1122 // that put us in raw mode handle the event.
1123 if (LexingRawMode) {
1124 Result.startToken();
1125 BufferPtr = BufferEnd;
Chris Lattner0344cc72008-10-12 04:51:35 +00001126 FormTokenWithChars(Result, BufferEnd, tok::eof);
Chris Lattner4b009652007-07-25 00:24:17 +00001127 return true;
1128 }
1129
1130 // Otherwise, issue diagnostics for unterminated #if and missing newline.
1131
1132 // If we are in a #if directive, emit an error.
1133 while (!ConditionalStack.empty()) {
Ted Kremenek7ecfa132008-11-12 23:13:54 +00001134 PreprocessorLexer::Diag(ConditionalStack.back().IfLoc,
1135 diag::err_pp_unterminated_conditional);
1136
Chris Lattner4b009652007-07-25 00:24:17 +00001137 ConditionalStack.pop_back();
1138 }
1139
Chris Lattner5c337fa2008-04-12 05:54:25 +00001140 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
1141 // a pedwarn.
1142 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r'))
Chris Lattner4b009652007-07-25 00:24:17 +00001143 Diag(BufferEnd, diag::ext_no_newline_eof);
1144
1145 BufferPtr = CurPtr;
1146
1147 // Finally, let the preprocessor handle this.
Chris Lattner342dccb2007-10-17 20:41:00 +00001148 return PP->HandleEndOfFile(Result);
Chris Lattner4b009652007-07-25 00:24:17 +00001149}
1150
1151/// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
1152/// the specified lexer will return a tok::l_paren token, 0 if it is something
1153/// else and 2 if there are no more tokens in the buffer controlled by the
1154/// lexer.
1155unsigned Lexer::isNextPPTokenLParen() {
1156 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
1157
1158 // Switch to 'skipping' mode. This will ensure that we can lex a token
1159 // without emitting diagnostics, disables macro expansion, and will cause EOF
1160 // to return an EOF token instead of popping the include stack.
1161 LexingRawMode = true;
1162
1163 // Save state that can be changed while lexing so that we can restore it.
1164 const char *TmpBufferPtr = BufferPtr;
1165
1166 Token Tok;
1167 Tok.startToken();
1168 LexTokenInternal(Tok);
1169
1170 // Restore state that may have changed.
1171 BufferPtr = TmpBufferPtr;
1172
1173 // Restore the lexer back to non-skipping mode.
1174 LexingRawMode = false;
1175
Chris Lattnercb8e41c2007-10-09 18:02:16 +00001176 if (Tok.is(tok::eof))
Chris Lattner4b009652007-07-25 00:24:17 +00001177 return 2;
Chris Lattnercb8e41c2007-10-09 18:02:16 +00001178 return Tok.is(tok::l_paren);
Chris Lattner4b009652007-07-25 00:24:17 +00001179}
1180
1181
1182/// LexTokenInternal - This implements a simple C family lexer. It is an
1183/// extremely performance critical piece of code. This assumes that the buffer
1184/// has a null character at the end of the file. Return true if an error
1185/// occurred and compilation should terminate, false if normal. This returns a
1186/// preprocessing token, not a normal token, as such, it is an internal
1187/// interface. It assumes that the Flags of result have been cleared before
1188/// calling this.
1189void Lexer::LexTokenInternal(Token &Result) {
1190LexNextToken:
1191 // New token, can't need cleaning yet.
1192 Result.clearFlag(Token::NeedsCleaning);
1193 Result.setIdentifierInfo(0);
1194
1195 // CurPtr - Cache BufferPtr in an automatic variable.
1196 const char *CurPtr = BufferPtr;
1197
1198 // Small amounts of horizontal whitespace is very common between tokens.
1199 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
1200 ++CurPtr;
1201 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
1202 ++CurPtr;
Chris Lattner867a87b2008-10-12 04:05:48 +00001203
1204 // If we are keeping whitespace and other tokens, just return what we just
1205 // skipped. The next lexer invocation will return the token after the
1206 // whitespace.
1207 if (isKeepWhitespaceMode()) {
Chris Lattner0344cc72008-10-12 04:51:35 +00001208 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner867a87b2008-10-12 04:05:48 +00001209 return;
1210 }
1211
Chris Lattner4b009652007-07-25 00:24:17 +00001212 BufferPtr = CurPtr;
1213 Result.setFlag(Token::LeadingSpace);
1214 }
1215
1216 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
1217
1218 // Read a character, advancing over it.
1219 char Char = getAndAdvanceChar(CurPtr, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001220 tok::TokenKind Kind;
1221
Chris Lattner4b009652007-07-25 00:24:17 +00001222 switch (Char) {
1223 case 0: // Null.
1224 // Found end of file?
1225 if (CurPtr-1 == BufferEnd) {
1226 // Read the PP instance variable into an automatic variable, because
1227 // LexEndOfFile will often delete 'this'.
Chris Lattner342dccb2007-10-17 20:41:00 +00001228 Preprocessor *PPCache = PP;
Chris Lattner4b009652007-07-25 00:24:17 +00001229 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
1230 return; // Got a token to return.
Chris Lattner342dccb2007-10-17 20:41:00 +00001231 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
1232 return PPCache->Lex(Result);
Chris Lattner4b009652007-07-25 00:24:17 +00001233 }
1234
1235 Diag(CurPtr-1, diag::null_in_file);
1236 Result.setFlag(Token::LeadingSpace);
Chris Lattner867a87b2008-10-12 04:05:48 +00001237 if (SkipWhitespace(Result, CurPtr))
1238 return; // KeepWhitespaceMode
1239
Chris Lattner4b009652007-07-25 00:24:17 +00001240 goto LexNextToken; // GCC isn't tail call eliminating.
1241 case '\n':
1242 case '\r':
1243 // If we are inside a preprocessor directive and we see the end of line,
1244 // we know we are done with the directive, so return an EOM token.
1245 if (ParsingPreprocessorDirective) {
1246 // Done parsing the "line".
1247 ParsingPreprocessorDirective = false;
1248
1249 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattner1c1bed12008-10-12 03:27:19 +00001250 SetCommentRetentionState(PP->getCommentRetentionState());
Chris Lattner4b009652007-07-25 00:24:17 +00001251
1252 // Since we consumed a newline, we are back at the start of a line.
1253 IsAtStartOfLine = true;
1254
Chris Lattner0344cc72008-10-12 04:51:35 +00001255 Kind = tok::eom;
Chris Lattner4b009652007-07-25 00:24:17 +00001256 break;
1257 }
1258 // The returned token is at the start of the line.
1259 Result.setFlag(Token::StartOfLine);
1260 // No leading whitespace seen so far.
1261 Result.clearFlag(Token::LeadingSpace);
Chris Lattner867a87b2008-10-12 04:05:48 +00001262
1263 if (SkipWhitespace(Result, CurPtr))
1264 return; // KeepWhitespaceMode
Chris Lattner4b009652007-07-25 00:24:17 +00001265 goto LexNextToken; // GCC isn't tail call eliminating.
1266 case ' ':
1267 case '\t':
1268 case '\f':
1269 case '\v':
1270 SkipHorizontalWhitespace:
1271 Result.setFlag(Token::LeadingSpace);
Chris Lattner867a87b2008-10-12 04:05:48 +00001272 if (SkipWhitespace(Result, CurPtr))
1273 return; // KeepWhitespaceMode
Chris Lattner4b009652007-07-25 00:24:17 +00001274
1275 SkipIgnoredUnits:
1276 CurPtr = BufferPtr;
1277
1278 // If the next token is obviously a // or /* */ comment, skip it efficiently
1279 // too (without going through the big switch stmt).
Chris Lattner170adb12008-10-12 03:22:02 +00001280 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001281 SkipBCPLComment(Result, CurPtr+2);
1282 goto SkipIgnoredUnits;
Chris Lattner170adb12008-10-12 03:22:02 +00001283 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001284 SkipBlockComment(Result, CurPtr+2);
1285 goto SkipIgnoredUnits;
1286 } else if (isHorizontalWhitespace(*CurPtr)) {
1287 goto SkipHorizontalWhitespace;
1288 }
1289 goto LexNextToken; // GCC isn't tail call eliminating.
1290
Chris Lattner0ffadcc2008-01-03 17:58:54 +00001291 // C99 6.4.4.1: Integer Constants.
1292 // C99 6.4.4.2: Floating Constants.
1293 case '0': case '1': case '2': case '3': case '4':
1294 case '5': case '6': case '7': case '8': case '9':
1295 // Notify MIOpt that we read a non-whitespace/non-comment token.
1296 MIOpt.ReadToken();
1297 return LexNumericConstant(Result, CurPtr);
1298
1299 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
Chris Lattner4b009652007-07-25 00:24:17 +00001300 // Notify MIOpt that we read a non-whitespace/non-comment token.
1301 MIOpt.ReadToken();
1302 Char = getCharAndSize(CurPtr, SizeTmp);
1303
1304 // Wide string literal.
1305 if (Char == '"')
1306 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
1307 true);
1308
1309 // Wide character constant.
1310 if (Char == '\'')
1311 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
1312 // FALL THROUGH, treating L like the start of an identifier.
1313
1314 // C99 6.4.2: Identifiers.
1315 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
1316 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
1317 case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U':
1318 case 'V': case 'W': case 'X': case 'Y': case 'Z':
1319 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
1320 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
1321 case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u':
1322 case 'v': case 'w': case 'x': case 'y': case 'z':
1323 case '_':
1324 // Notify MIOpt that we read a non-whitespace/non-comment token.
1325 MIOpt.ReadToken();
1326 return LexIdentifier(Result, CurPtr);
Chris Lattner0ffadcc2008-01-03 17:58:54 +00001327
1328 case '$': // $ in identifiers.
1329 if (Features.DollarIdents) {
1330 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
1331 // Notify MIOpt that we read a non-whitespace/non-comment token.
1332 MIOpt.ReadToken();
1333 return LexIdentifier(Result, CurPtr);
1334 }
Chris Lattner4b009652007-07-25 00:24:17 +00001335
Chris Lattner0344cc72008-10-12 04:51:35 +00001336 Kind = tok::unknown;
Chris Lattner0ffadcc2008-01-03 17:58:54 +00001337 break;
Chris Lattner4b009652007-07-25 00:24:17 +00001338
1339 // C99 6.4.4: Character Constants.
1340 case '\'':
1341 // Notify MIOpt that we read a non-whitespace/non-comment token.
1342 MIOpt.ReadToken();
1343 return LexCharConstant(Result, CurPtr);
1344
1345 // C99 6.4.5: String Literals.
1346 case '"':
1347 // Notify MIOpt that we read a non-whitespace/non-comment token.
1348 MIOpt.ReadToken();
1349 return LexStringLiteral(Result, CurPtr, false);
1350
1351 // C99 6.4.6: Punctuators.
1352 case '?':
Chris Lattner0344cc72008-10-12 04:51:35 +00001353 Kind = tok::question;
Chris Lattner4b009652007-07-25 00:24:17 +00001354 break;
1355 case '[':
Chris Lattner0344cc72008-10-12 04:51:35 +00001356 Kind = tok::l_square;
Chris Lattner4b009652007-07-25 00:24:17 +00001357 break;
1358 case ']':
Chris Lattner0344cc72008-10-12 04:51:35 +00001359 Kind = tok::r_square;
Chris Lattner4b009652007-07-25 00:24:17 +00001360 break;
1361 case '(':
Chris Lattner0344cc72008-10-12 04:51:35 +00001362 Kind = tok::l_paren;
Chris Lattner4b009652007-07-25 00:24:17 +00001363 break;
1364 case ')':
Chris Lattner0344cc72008-10-12 04:51:35 +00001365 Kind = tok::r_paren;
Chris Lattner4b009652007-07-25 00:24:17 +00001366 break;
1367 case '{':
Chris Lattner0344cc72008-10-12 04:51:35 +00001368 Kind = tok::l_brace;
Chris Lattner4b009652007-07-25 00:24:17 +00001369 break;
1370 case '}':
Chris Lattner0344cc72008-10-12 04:51:35 +00001371 Kind = tok::r_brace;
Chris Lattner4b009652007-07-25 00:24:17 +00001372 break;
1373 case '.':
1374 Char = getCharAndSize(CurPtr, SizeTmp);
1375 if (Char >= '0' && Char <= '9') {
1376 // Notify MIOpt that we read a non-whitespace/non-comment token.
1377 MIOpt.ReadToken();
1378
1379 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
1380 } else if (Features.CPlusPlus && Char == '*') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001381 Kind = tok::periodstar;
Chris Lattner4b009652007-07-25 00:24:17 +00001382 CurPtr += SizeTmp;
1383 } else if (Char == '.' &&
1384 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001385 Kind = tok::ellipsis;
Chris Lattner4b009652007-07-25 00:24:17 +00001386 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1387 SizeTmp2, Result);
1388 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001389 Kind = tok::period;
Chris Lattner4b009652007-07-25 00:24:17 +00001390 }
1391 break;
1392 case '&':
1393 Char = getCharAndSize(CurPtr, SizeTmp);
1394 if (Char == '&') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001395 Kind = tok::ampamp;
Chris Lattner4b009652007-07-25 00:24:17 +00001396 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1397 } else if (Char == '=') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001398 Kind = tok::ampequal;
Chris Lattner4b009652007-07-25 00:24:17 +00001399 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1400 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001401 Kind = tok::amp;
Chris Lattner4b009652007-07-25 00:24:17 +00001402 }
1403 break;
1404 case '*':
1405 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001406 Kind = tok::starequal;
Chris Lattner4b009652007-07-25 00:24:17 +00001407 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1408 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001409 Kind = tok::star;
Chris Lattner4b009652007-07-25 00:24:17 +00001410 }
1411 break;
1412 case '+':
1413 Char = getCharAndSize(CurPtr, SizeTmp);
1414 if (Char == '+') {
Chris Lattner4b009652007-07-25 00:24:17 +00001415 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001416 Kind = tok::plusplus;
Chris Lattner4b009652007-07-25 00:24:17 +00001417 } else if (Char == '=') {
Chris Lattner4b009652007-07-25 00:24:17 +00001418 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001419 Kind = tok::plusequal;
Chris Lattner4b009652007-07-25 00:24:17 +00001420 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001421 Kind = tok::plus;
Chris Lattner4b009652007-07-25 00:24:17 +00001422 }
1423 break;
1424 case '-':
1425 Char = getCharAndSize(CurPtr, SizeTmp);
Chris Lattner0344cc72008-10-12 04:51:35 +00001426 if (Char == '-') { // --
Chris Lattner4b009652007-07-25 00:24:17 +00001427 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001428 Kind = tok::minusminus;
Chris Lattner4b009652007-07-25 00:24:17 +00001429 } else if (Char == '>' && Features.CPlusPlus &&
Chris Lattner0344cc72008-10-12 04:51:35 +00001430 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
Chris Lattner4b009652007-07-25 00:24:17 +00001431 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1432 SizeTmp2, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001433 Kind = tok::arrowstar;
1434 } else if (Char == '>') { // ->
Chris Lattner4b009652007-07-25 00:24:17 +00001435 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001436 Kind = tok::arrow;
1437 } else if (Char == '=') { // -=
Chris Lattner4b009652007-07-25 00:24:17 +00001438 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001439 Kind = tok::minusequal;
Chris Lattner4b009652007-07-25 00:24:17 +00001440 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001441 Kind = tok::minus;
Chris Lattner4b009652007-07-25 00:24:17 +00001442 }
1443 break;
1444 case '~':
Chris Lattner0344cc72008-10-12 04:51:35 +00001445 Kind = tok::tilde;
Chris Lattner4b009652007-07-25 00:24:17 +00001446 break;
1447 case '!':
1448 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001449 Kind = tok::exclaimequal;
Chris Lattner4b009652007-07-25 00:24:17 +00001450 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1451 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001452 Kind = tok::exclaim;
Chris Lattner4b009652007-07-25 00:24:17 +00001453 }
1454 break;
1455 case '/':
1456 // 6.4.9: Comments
1457 Char = getCharAndSize(CurPtr, SizeTmp);
1458 if (Char == '/') { // BCPL comment.
Chris Lattnerf03b00c2008-10-12 04:15:42 +00001459 if (SkipBCPLComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
1460 return; // KeepCommentMode
1461
1462 // It is common for the tokens immediately after a // comment to be
1463 // whitespace (indentation for the next line). Instead of going through
1464 // the big switch, handle it efficiently now.
1465 goto SkipIgnoredUnits;
Chris Lattner4b009652007-07-25 00:24:17 +00001466 } else if (Char == '*') { // /**/ comment.
1467 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattnerf03b00c2008-10-12 04:15:42 +00001468 return; // KeepCommentMode
1469 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattner4b009652007-07-25 00:24:17 +00001470 } else if (Char == '=') {
Chris Lattner4b009652007-07-25 00:24:17 +00001471 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001472 Kind = tok::slashequal;
Chris Lattner4b009652007-07-25 00:24:17 +00001473 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001474 Kind = tok::slash;
Chris Lattner4b009652007-07-25 00:24:17 +00001475 }
1476 break;
1477 case '%':
1478 Char = getCharAndSize(CurPtr, SizeTmp);
1479 if (Char == '=') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001480 Kind = tok::percentequal;
Chris Lattner4b009652007-07-25 00:24:17 +00001481 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1482 } else if (Features.Digraphs && Char == '>') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001483 Kind = tok::r_brace; // '%>' -> '}'
Chris Lattner4b009652007-07-25 00:24:17 +00001484 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1485 } else if (Features.Digraphs && Char == ':') {
1486 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1487 Char = getCharAndSize(CurPtr, SizeTmp);
1488 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001489 Kind = tok::hashhash; // '%:%:' -> '##'
Chris Lattner4b009652007-07-25 00:24:17 +00001490 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1491 SizeTmp2, Result);
1492 } else if (Char == '@' && Features.Microsoft) { // %:@ -> #@ -> Charize
Chris Lattner4b009652007-07-25 00:24:17 +00001493 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1494 Diag(BufferPtr, diag::charize_microsoft_ext);
Chris Lattner0344cc72008-10-12 04:51:35 +00001495 Kind = tok::hashat;
Chris Lattner4b009652007-07-25 00:24:17 +00001496 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001497 Kind = tok::hash; // '%:' -> '#'
Chris Lattner4b009652007-07-25 00:24:17 +00001498
1499 // We parsed a # character. If this occurs at the start of the line,
1500 // it's actually the start of a preprocessing directive. Callback to
1501 // the preprocessor to handle it.
1502 // FIXME: -fpreprocessed mode??
1503 if (Result.isAtStartOfLine() && !LexingRawMode) {
1504 BufferPtr = CurPtr;
Chris Lattner342dccb2007-10-17 20:41:00 +00001505 PP->HandleDirective(Result);
Chris Lattner4b009652007-07-25 00:24:17 +00001506
1507 // As an optimization, if the preprocessor didn't switch lexers, tail
1508 // recurse.
Chris Lattner342dccb2007-10-17 20:41:00 +00001509 if (PP->isCurrentLexer(this)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001510 // Start a new token. If this is a #include or something, the PP may
1511 // want us starting at the beginning of the line again. If so, set
1512 // the StartOfLine flag.
1513 if (IsAtStartOfLine) {
1514 Result.setFlag(Token::StartOfLine);
1515 IsAtStartOfLine = false;
1516 }
1517 goto LexNextToken; // GCC isn't tail call eliminating.
1518 }
1519
Chris Lattner342dccb2007-10-17 20:41:00 +00001520 return PP->Lex(Result);
Chris Lattner4b009652007-07-25 00:24:17 +00001521 }
1522 }
1523 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001524 Kind = tok::percent;
Chris Lattner4b009652007-07-25 00:24:17 +00001525 }
1526 break;
1527 case '<':
1528 Char = getCharAndSize(CurPtr, SizeTmp);
1529 if (ParsingFilename) {
1530 return LexAngledStringLiteral(Result, CurPtr+SizeTmp);
1531 } else if (Char == '<' &&
1532 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '=') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001533 Kind = tok::lesslessequal;
Chris Lattner4b009652007-07-25 00:24:17 +00001534 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1535 SizeTmp2, Result);
1536 } else if (Char == '<') {
Chris Lattner4b009652007-07-25 00:24:17 +00001537 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001538 Kind = tok::lessless;
Chris Lattner4b009652007-07-25 00:24:17 +00001539 } else if (Char == '=') {
Chris Lattner4b009652007-07-25 00:24:17 +00001540 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001541 Kind = tok::lessequal;
1542 } else if (Features.Digraphs && Char == ':') { // '<:' -> '['
Chris Lattner4b009652007-07-25 00:24:17 +00001543 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001544 Kind = tok::l_square;
1545 } else if (Features.Digraphs && Char == '%') { // '<%' -> '{'
Chris Lattner4b009652007-07-25 00:24:17 +00001546 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001547 Kind = tok::l_brace;
Chris Lattner4b009652007-07-25 00:24:17 +00001548 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001549 Kind = tok::less;
Chris Lattner4b009652007-07-25 00:24:17 +00001550 }
1551 break;
1552 case '>':
1553 Char = getCharAndSize(CurPtr, SizeTmp);
1554 if (Char == '=') {
Chris Lattner4b009652007-07-25 00:24:17 +00001555 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001556 Kind = tok::greaterequal;
Chris Lattner4b009652007-07-25 00:24:17 +00001557 } else if (Char == '>' &&
1558 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '=') {
Chris Lattner4b009652007-07-25 00:24:17 +00001559 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1560 SizeTmp2, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001561 Kind = tok::greatergreaterequal;
Chris Lattner4b009652007-07-25 00:24:17 +00001562 } else if (Char == '>') {
Chris Lattner4b009652007-07-25 00:24:17 +00001563 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001564 Kind = tok::greatergreater;
Chris Lattner4b009652007-07-25 00:24:17 +00001565 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001566 Kind = tok::greater;
Chris Lattner4b009652007-07-25 00:24:17 +00001567 }
1568 break;
1569 case '^':
1570 Char = getCharAndSize(CurPtr, SizeTmp);
1571 if (Char == '=') {
Chris Lattner4b009652007-07-25 00:24:17 +00001572 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner0344cc72008-10-12 04:51:35 +00001573 Kind = tok::caretequal;
Chris Lattner4b009652007-07-25 00:24:17 +00001574 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001575 Kind = tok::caret;
Chris Lattner4b009652007-07-25 00:24:17 +00001576 }
1577 break;
1578 case '|':
1579 Char = getCharAndSize(CurPtr, SizeTmp);
1580 if (Char == '=') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001581 Kind = tok::pipeequal;
Chris Lattner4b009652007-07-25 00:24:17 +00001582 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1583 } else if (Char == '|') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001584 Kind = tok::pipepipe;
Chris Lattner4b009652007-07-25 00:24:17 +00001585 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1586 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001587 Kind = tok::pipe;
Chris Lattner4b009652007-07-25 00:24:17 +00001588 }
1589 break;
1590 case ':':
1591 Char = getCharAndSize(CurPtr, SizeTmp);
1592 if (Features.Digraphs && Char == '>') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001593 Kind = tok::r_square; // ':>' -> ']'
Chris Lattner4b009652007-07-25 00:24:17 +00001594 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1595 } else if (Features.CPlusPlus && Char == ':') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001596 Kind = tok::coloncolon;
Chris Lattner4b009652007-07-25 00:24:17 +00001597 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1598 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001599 Kind = tok::colon;
Chris Lattner4b009652007-07-25 00:24:17 +00001600 }
1601 break;
1602 case ';':
Chris Lattner0344cc72008-10-12 04:51:35 +00001603 Kind = tok::semi;
Chris Lattner4b009652007-07-25 00:24:17 +00001604 break;
1605 case '=':
1606 Char = getCharAndSize(CurPtr, SizeTmp);
1607 if (Char == '=') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001608 Kind = tok::equalequal;
Chris Lattner4b009652007-07-25 00:24:17 +00001609 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1610 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001611 Kind = tok::equal;
Chris Lattner4b009652007-07-25 00:24:17 +00001612 }
1613 break;
1614 case ',':
Chris Lattner0344cc72008-10-12 04:51:35 +00001615 Kind = tok::comma;
Chris Lattner4b009652007-07-25 00:24:17 +00001616 break;
1617 case '#':
1618 Char = getCharAndSize(CurPtr, SizeTmp);
1619 if (Char == '#') {
Chris Lattner0344cc72008-10-12 04:51:35 +00001620 Kind = tok::hashhash;
Chris Lattner4b009652007-07-25 00:24:17 +00001621 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1622 } else if (Char == '@' && Features.Microsoft) { // #@ -> Charize
Chris Lattner0344cc72008-10-12 04:51:35 +00001623 Kind = tok::hashat;
Chris Lattner4b009652007-07-25 00:24:17 +00001624 Diag(BufferPtr, diag::charize_microsoft_ext);
1625 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1626 } else {
Chris Lattner0344cc72008-10-12 04:51:35 +00001627 Kind = tok::hash;
Chris Lattner4b009652007-07-25 00:24:17 +00001628 // We parsed a # character. If this occurs at the start of the line,
1629 // it's actually the start of a preprocessing directive. Callback to
1630 // the preprocessor to handle it.
1631 // FIXME: -fpreprocessed mode??
1632 if (Result.isAtStartOfLine() && !LexingRawMode) {
1633 BufferPtr = CurPtr;
Chris Lattner342dccb2007-10-17 20:41:00 +00001634 PP->HandleDirective(Result);
Chris Lattner4b009652007-07-25 00:24:17 +00001635
1636 // As an optimization, if the preprocessor didn't switch lexers, tail
1637 // recurse.
Chris Lattner342dccb2007-10-17 20:41:00 +00001638 if (PP->isCurrentLexer(this)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001639 // Start a new token. If this is a #include or something, the PP may
1640 // want us starting at the beginning of the line again. If so, set
1641 // the StartOfLine flag.
1642 if (IsAtStartOfLine) {
1643 Result.setFlag(Token::StartOfLine);
1644 IsAtStartOfLine = false;
1645 }
1646 goto LexNextToken; // GCC isn't tail call eliminating.
1647 }
Chris Lattner342dccb2007-10-17 20:41:00 +00001648 return PP->Lex(Result);
Chris Lattner4b009652007-07-25 00:24:17 +00001649 }
1650 }
1651 break;
1652
Chris Lattner0ffadcc2008-01-03 17:58:54 +00001653 case '@':
1654 // Objective C support.
1655 if (CurPtr[-1] == '@' && Features.ObjC1)
Chris Lattner0344cc72008-10-12 04:51:35 +00001656 Kind = tok::at;
Chris Lattner0ffadcc2008-01-03 17:58:54 +00001657 else
Chris Lattner0344cc72008-10-12 04:51:35 +00001658 Kind = tok::unknown;
Chris Lattner0ffadcc2008-01-03 17:58:54 +00001659 break;
1660
Chris Lattner4b009652007-07-25 00:24:17 +00001661 case '\\':
1662 // FIXME: UCN's.
1663 // FALL THROUGH.
1664 default:
Chris Lattner0344cc72008-10-12 04:51:35 +00001665 Kind = tok::unknown;
Chris Lattner4b009652007-07-25 00:24:17 +00001666 break;
1667 }
1668
1669 // Notify MIOpt that we read a non-whitespace/non-comment token.
1670 MIOpt.ReadToken();
1671
1672 // Update the location of token as well as BufferPtr.
Chris Lattner0344cc72008-10-12 04:51:35 +00001673 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner4b009652007-07-25 00:24:17 +00001674}