blob: 4c25287b07c2b03c3a66fc2702295fb9d876859c [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- Lexer.cpp - C Language Family Lexer ------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
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
Chris Lattner53702cd2007-12-13 01:59:49 +000054
Chris Lattnerdbf388b2007-10-07 08:47:24 +000055//===----------------------------------------------------------------------===//
56// Lexer Class Implementation
57//===----------------------------------------------------------------------===//
58
59
Chris Lattner168ae2d2007-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 Lattner25bdb512007-07-20 16:52:03 +000064Lexer::Lexer(SourceLocation fileloc, Preprocessor &pp,
65 const char *BufStart, const char *BufEnd)
Ted Kremenek41938c82008-11-19 21:57:25 +000066 : PreprocessorLexer(&pp, fileloc), FileLoc(fileloc),
67 Features(pp.getLangOptions()) {
Chris Lattner25bdb512007-07-20 16:52:03 +000068
Chris Lattner168ae2d2007-10-17 20:41:00 +000069 SourceManager &SourceMgr = PP->getSourceManager();
Chris Lattner448cec42007-07-22 18:44:36 +000070 unsigned InputFileID = SourceMgr.getPhysicalLoc(FileLoc).getFileID();
71 const llvm::MemoryBuffer *InputFile = SourceMgr.getBuffer(InputFileID);
Chris Lattner25bdb512007-07-20 16:52:03 +000072
Reid Spencer5f016e22007-07-11 17:01:13 +000073 Is_PragmaLexer = false;
Reid Spencer5f016e22007-07-11 17:01:13 +000074 InitCharacterInfo();
Chris Lattner448cec42007-07-22 18:44:36 +000075
76 // BufferStart must always be InputFile->getBufferStart().
77 BufferStart = InputFile->getBufferStart();
78
79 // BufferPtr and BufferEnd can start out somewhere inside the current buffer.
80 // If unspecified, they starts at the start/end of the buffer.
81 BufferPtr = BufStart ? BufStart : BufferStart;
Chris Lattner25bdb512007-07-20 16:52:03 +000082 BufferEnd = BufEnd ? BufEnd : InputFile->getBufferEnd();
83
Reid Spencer5f016e22007-07-11 17:01:13 +000084 assert(BufferEnd[0] == 0 &&
85 "We assume that the input buffer has a null character at the end"
86 " to simplify lexing!");
Chris Lattner25bdb512007-07-20 16:52:03 +000087
Reid Spencer5f016e22007-07-11 17:01:13 +000088 // Start of the file is a start of line.
89 IsAtStartOfLine = true;
90
91 // We are not after parsing a #.
92 ParsingPreprocessorDirective = false;
93
94 // We are not after parsing #include.
95 ParsingFilename = false;
96
97 // We are not in raw mode. Raw mode disables diagnostics and interpretation
98 // of tokens (e.g. identifiers, thus disabling macro expansion). It is used
99 // to quickly lex the tokens of the buffer, e.g. when handling a "#if 0" block
100 // or otherwise skipping over tokens.
101 LexingRawMode = false;
102
Chris Lattnerd88dc482008-10-12 04:05:48 +0000103 // Default to keeping comments if the preprocessor wants them.
104 ExtendedTokenMode = 0;
Chris Lattnerf744d132008-10-12 03:27:19 +0000105 SetCommentRetentionState(PP->getCommentRetentionState());
Reid Spencer5f016e22007-07-11 17:01:13 +0000106}
107
Chris Lattner168ae2d2007-10-17 20:41:00 +0000108/// Lexer constructor - Create a new raw lexer object. This object is only
Chris Lattner590f0cc2008-10-12 01:15:46 +0000109/// suitable for calls to 'LexRawToken'. This lexer assumes that the text
110/// range will outlive it, so it doesn't take ownership of it.
Chris Lattner168ae2d2007-10-17 20:41:00 +0000111Lexer::Lexer(SourceLocation fileloc, const LangOptions &features,
Chris Lattner590f0cc2008-10-12 01:15:46 +0000112 const char *BufStart, const char *BufEnd,
113 const llvm::MemoryBuffer *FromFile)
Ted Kremenek41938c82008-11-19 21:57:25 +0000114 : PreprocessorLexer(), FileLoc(fileloc),
115 Features(features) {
116
Chris Lattner168ae2d2007-10-17 20:41:00 +0000117 Is_PragmaLexer = false;
118 InitCharacterInfo();
119
Chris Lattner8527b712008-10-12 01:23:27 +0000120 // If a MemoryBuffer was specified, use its start as BufferStart. This affects
121 // the source location objects produced by this lexer.
Chris Lattner590f0cc2008-10-12 01:15:46 +0000122 BufferStart = FromFile ? FromFile->getBufferStart() : BufStart;
Chris Lattner168ae2d2007-10-17 20:41:00 +0000123 BufferPtr = BufStart;
124 BufferEnd = BufEnd;
125
126 assert(BufferEnd[0] == 0 &&
127 "We assume that the input buffer has a null character at the end"
128 " to simplify lexing!");
129
130 // Start of the file is a start of line.
131 IsAtStartOfLine = true;
132
133 // We are not after parsing a #.
134 ParsingPreprocessorDirective = false;
135
136 // We are not after parsing #include.
137 ParsingFilename = false;
138
139 // We *are* in raw mode.
140 LexingRawMode = true;
141
Chris Lattnera2c7ad92008-10-12 01:34:51 +0000142 // Default to not keeping comments in raw mode.
Chris Lattnerd88dc482008-10-12 04:05:48 +0000143 ExtendedTokenMode = 0;
Chris Lattner168ae2d2007-10-17 20:41:00 +0000144}
145
146
Reid Spencer5f016e22007-07-11 17:01:13 +0000147/// Stringify - Convert the specified string into a C string, with surrounding
148/// ""'s, and with escaped \ and " characters.
149std::string Lexer::Stringify(const std::string &Str, bool Charify) {
150 std::string Result = Str;
151 char Quote = Charify ? '\'' : '"';
152 for (unsigned i = 0, e = Result.size(); i != e; ++i) {
153 if (Result[i] == '\\' || Result[i] == Quote) {
154 Result.insert(Result.begin()+i, '\\');
155 ++i; ++e;
156 }
157 }
158 return Result;
159}
160
Chris Lattnerd8e30832007-07-24 06:57:14 +0000161/// Stringify - Convert the specified string into a C string by escaping '\'
162/// and " characters. This does not add surrounding ""'s to the string.
163void Lexer::Stringify(llvm::SmallVectorImpl<char> &Str) {
164 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
165 if (Str[i] == '\\' || Str[i] == '"') {
166 Str.insert(Str.begin()+i, '\\');
167 ++i; ++e;
168 }
169 }
170}
171
Reid Spencer5f016e22007-07-11 17:01:13 +0000172
Chris Lattner9a611942007-10-17 21:18:47 +0000173/// MeasureTokenLength - Relex the token at the specified location and return
174/// its length in bytes in the input file. If the token needs cleaning (e.g.
175/// includes a trigraph or an escaped newline) then this count includes bytes
176/// that are part of that.
177unsigned Lexer::MeasureTokenLength(SourceLocation Loc,
178 const SourceManager &SM) {
179 // If this comes from a macro expansion, we really do want the macro name, not
180 // the token this macro expanded to.
181 Loc = SM.getLogicalLoc(Loc);
182
183 const char *StrData = SM.getCharacterData(Loc);
184
185 // TODO: this could be special cased for common tokens like identifiers, ')',
186 // etc to make this faster, if it mattered. Just look at StrData[0] to handle
187 // all obviously single-char tokens. This could use
188 // Lexer::isObviouslySimpleCharacter for example to handle identifiers or
189 // something.
190
191
192 const char *BufEnd = SM.getBufferData(Loc.getFileID()).second;
193
194 // Create a langops struct and enable trigraphs. This is sufficient for
195 // measuring tokens.
196 LangOptions LangOpts;
197 LangOpts.Trigraphs = true;
198
199 // Create a lexer starting at the beginning of this token.
200 Lexer TheLexer(Loc, LangOpts, StrData, BufEnd);
201 Token TheTok;
Chris Lattner590f0cc2008-10-12 01:15:46 +0000202 TheLexer.LexFromRawLexer(TheTok);
Chris Lattner9a611942007-10-17 21:18:47 +0000203 return TheTok.getLength();
204}
205
Reid Spencer5f016e22007-07-11 17:01:13 +0000206//===----------------------------------------------------------------------===//
207// Character information.
208//===----------------------------------------------------------------------===//
209
210static unsigned char CharInfo[256];
211
212enum {
213 CHAR_HORZ_WS = 0x01, // ' ', '\t', '\f', '\v'. Note, no '\0'
214 CHAR_VERT_WS = 0x02, // '\r', '\n'
215 CHAR_LETTER = 0x04, // a-z,A-Z
216 CHAR_NUMBER = 0x08, // 0-9
217 CHAR_UNDER = 0x10, // _
218 CHAR_PERIOD = 0x20 // .
219};
220
221static void InitCharacterInfo() {
222 static bool isInited = false;
223 if (isInited) return;
224 isInited = true;
225
226 // Intiialize the CharInfo table.
227 // TODO: statically initialize this.
228 CharInfo[(int)' '] = CharInfo[(int)'\t'] =
229 CharInfo[(int)'\f'] = CharInfo[(int)'\v'] = CHAR_HORZ_WS;
230 CharInfo[(int)'\n'] = CharInfo[(int)'\r'] = CHAR_VERT_WS;
231
232 CharInfo[(int)'_'] = CHAR_UNDER;
233 CharInfo[(int)'.'] = CHAR_PERIOD;
234 for (unsigned i = 'a'; i <= 'z'; ++i)
235 CharInfo[i] = CharInfo[i+'A'-'a'] = CHAR_LETTER;
236 for (unsigned i = '0'; i <= '9'; ++i)
237 CharInfo[i] = CHAR_NUMBER;
238}
239
240/// isIdentifierBody - Return true if this is the body character of an
241/// identifier, which is [a-zA-Z0-9_].
242static inline bool isIdentifierBody(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000243 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER)) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000244}
245
246/// isHorizontalWhitespace - Return true if this character is horizontal
247/// whitespace: ' ', '\t', '\f', '\v'. Note that this returns false for '\0'.
248static inline bool isHorizontalWhitespace(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000249 return (CharInfo[c] & CHAR_HORZ_WS) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000250}
251
252/// isWhitespace - Return true if this character is horizontal or vertical
253/// whitespace: ' ', '\t', '\f', '\v', '\n', '\r'. Note that this returns false
254/// for '\0'.
255static inline bool isWhitespace(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000256 return (CharInfo[c] & (CHAR_HORZ_WS|CHAR_VERT_WS)) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000257}
258
259/// isNumberBody - Return true if this is the body character of an
260/// preprocessing number, which is [a-zA-Z0-9_.].
261static inline bool isNumberBody(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000262 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER|CHAR_PERIOD)) ?
263 true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000264}
265
266
267//===----------------------------------------------------------------------===//
268// Diagnostics forwarding code.
269//===----------------------------------------------------------------------===//
270
Chris Lattner409a0362007-07-22 18:38:25 +0000271/// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
272/// lexer buffer was all instantiated at a single point, perform the mapping.
273/// This is currently only used for _Pragma implementation, so it is the slow
274/// path of the hot getSourceLocation method. Do not allow it to be inlined.
275static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
276 SourceLocation FileLoc,
277 unsigned CharNo) DISABLE_INLINE;
278static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
279 SourceLocation FileLoc,
280 unsigned CharNo) {
281 // Otherwise, we're lexing "mapped tokens". This is used for things like
282 // _Pragma handling. Combine the instantiation location of FileLoc with the
283 // physical location.
284 SourceManager &SourceMgr = PP.getSourceManager();
285
286 // Create a new SLoc which is expanded from logical(FileLoc) but whose
287 // characters come from phys(FileLoc)+Offset.
288 SourceLocation VirtLoc = SourceMgr.getLogicalLoc(FileLoc);
289 SourceLocation PhysLoc = SourceMgr.getPhysicalLoc(FileLoc);
290 PhysLoc = SourceLocation::getFileLoc(PhysLoc.getFileID(), CharNo);
291 return SourceMgr.getInstantiationLoc(PhysLoc, VirtLoc);
292}
293
Reid Spencer5f016e22007-07-11 17:01:13 +0000294/// getSourceLocation - Return a source location identifier for the specified
295/// offset in the current file.
296SourceLocation Lexer::getSourceLocation(const char *Loc) const {
Chris Lattner448cec42007-07-22 18:44:36 +0000297 assert(Loc >= BufferStart && Loc <= BufferEnd &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000298 "Location out of range for this buffer!");
Chris Lattner9dc1f532007-07-20 16:37:10 +0000299
300 // In the normal case, we're just lexing from a simple file buffer, return
301 // the file id from FileLoc with the offset specified.
Chris Lattner448cec42007-07-22 18:44:36 +0000302 unsigned CharNo = Loc-BufferStart;
Chris Lattner9dc1f532007-07-20 16:37:10 +0000303 if (FileLoc.isFileID())
304 return SourceLocation::getFileLoc(FileLoc.getFileID(), CharNo);
305
Chris Lattner168ae2d2007-10-17 20:41:00 +0000306 assert(PP && "This doesn't work on raw lexers");
307 return GetMappedTokenLoc(*PP, FileLoc, CharNo);
Reid Spencer5f016e22007-07-11 17:01:13 +0000308}
309
Reid Spencer5f016e22007-07-11 17:01:13 +0000310/// Diag - Forwarding function for diagnostics. This translate a source
311/// position in the current buffer into a SourceLocation object for rendering.
Chris Lattner3cbfe2c2008-11-22 00:59:29 +0000312DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
Chris Lattner07506182007-11-30 22:53:43 +0000313 if (LexingRawMode && Diagnostic::isBuiltinNoteWarningOrExtension(DiagID))
Chris Lattner3cbfe2c2008-11-22 00:59:29 +0000314 return DiagnosticBuilder();
Chris Lattner3692b092008-11-18 07:59:24 +0000315 return PP->Diag(getSourceLocation(Loc), DiagID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000316}
Reid Spencer5f016e22007-07-11 17:01:13 +0000317
318//===----------------------------------------------------------------------===//
319// Trigraph and Escaped Newline Handling Code.
320//===----------------------------------------------------------------------===//
321
322/// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
323/// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
324static char GetTrigraphCharForLetter(char Letter) {
325 switch (Letter) {
326 default: return 0;
327 case '=': return '#';
328 case ')': return ']';
329 case '(': return '[';
330 case '!': return '|';
331 case '\'': return '^';
332 case '>': return '}';
333 case '/': return '\\';
334 case '<': return '{';
335 case '-': return '~';
336 }
337}
338
339/// DecodeTrigraphChar - If the specified character is a legal trigraph when
340/// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
341/// return the result character. Finally, emit a warning about trigraph use
342/// whether trigraphs are enabled or not.
343static char DecodeTrigraphChar(const char *CP, Lexer *L) {
344 char Res = GetTrigraphCharForLetter(*CP);
Chris Lattner3692b092008-11-18 07:59:24 +0000345 if (!Res || !L) return Res;
346
347 if (!L->getFeatures().Trigraphs) {
348 L->Diag(CP-2, diag::trigraph_ignored);
349 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000350 }
Chris Lattner3692b092008-11-18 07:59:24 +0000351
352 L->Diag(CP-2, diag::trigraph_converted) << std::string()+Res;
Reid Spencer5f016e22007-07-11 17:01:13 +0000353 return Res;
354}
355
356/// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
357/// get its size, and return it. This is tricky in several cases:
358/// 1. If currently at the start of a trigraph, we warn about the trigraph,
359/// then either return the trigraph (skipping 3 chars) or the '?',
360/// depending on whether trigraphs are enabled or not.
361/// 2. If this is an escaped newline (potentially with whitespace between
362/// the backslash and newline), implicitly skip the newline and return
363/// the char after it.
364/// 3. If this is a UCN, return it. FIXME: C++ UCN's?
365///
366/// This handles the slow/uncommon case of the getCharAndSize method. Here we
367/// know that we can accumulate into Size, and that we have already incremented
368/// Ptr by Size bytes.
369///
370/// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
371/// be updated to match.
372///
373char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
Chris Lattnerd2177732007-07-20 16:59:19 +0000374 Token *Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000375 // If we have a slash, look for an escaped newline.
376 if (Ptr[0] == '\\') {
377 ++Size;
378 ++Ptr;
379Slash:
380 // Common case, backslash-char where the char is not whitespace.
381 if (!isWhitespace(Ptr[0])) return '\\';
382
383 // See if we have optional whitespace characters followed by a newline.
384 {
385 unsigned SizeTmp = 0;
386 do {
387 ++SizeTmp;
388 if (Ptr[SizeTmp-1] == '\n' || Ptr[SizeTmp-1] == '\r') {
389 // Remember that this token needs to be cleaned.
Chris Lattnerd2177732007-07-20 16:59:19 +0000390 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +0000391
392 // Warn if there was whitespace between the backslash and newline.
393 if (SizeTmp != 1 && Tok)
394 Diag(Ptr, diag::backslash_newline_space);
395
396 // If this is a \r\n or \n\r, skip the newlines.
397 if ((Ptr[SizeTmp] == '\r' || Ptr[SizeTmp] == '\n') &&
398 Ptr[SizeTmp-1] != Ptr[SizeTmp])
399 ++SizeTmp;
400
401 // Found backslash<whitespace><newline>. Parse the char after it.
402 Size += SizeTmp;
403 Ptr += SizeTmp;
404 // Use slow version to accumulate a correct size field.
405 return getCharAndSizeSlow(Ptr, Size, Tok);
406 }
407 } while (isWhitespace(Ptr[SizeTmp]));
408 }
409
410 // Otherwise, this is not an escaped newline, just return the slash.
411 return '\\';
412 }
413
414 // If this is a trigraph, process it.
415 if (Ptr[0] == '?' && Ptr[1] == '?') {
416 // If this is actually a legal trigraph (not something like "??x"), emit
417 // a trigraph warning. If so, and if trigraphs are enabled, return it.
418 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : 0)) {
419 // Remember that this token needs to be cleaned.
Chris Lattnerd2177732007-07-20 16:59:19 +0000420 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +0000421
422 Ptr += 3;
423 Size += 3;
424 if (C == '\\') goto Slash;
425 return C;
426 }
427 }
428
429 // If this is neither, return a single character.
430 ++Size;
431 return *Ptr;
432}
433
434
435/// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
436/// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
437/// and that we have already incremented Ptr by Size bytes.
438///
439/// NOTE: When this method is updated, getCharAndSizeSlow (above) should
440/// be updated to match.
441char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
442 const LangOptions &Features) {
443 // If we have a slash, look for an escaped newline.
444 if (Ptr[0] == '\\') {
445 ++Size;
446 ++Ptr;
447Slash:
448 // Common case, backslash-char where the char is not whitespace.
449 if (!isWhitespace(Ptr[0])) return '\\';
450
451 // See if we have optional whitespace characters followed by a newline.
452 {
453 unsigned SizeTmp = 0;
454 do {
455 ++SizeTmp;
456 if (Ptr[SizeTmp-1] == '\n' || Ptr[SizeTmp-1] == '\r') {
457
458 // If this is a \r\n or \n\r, skip the newlines.
459 if ((Ptr[SizeTmp] == '\r' || Ptr[SizeTmp] == '\n') &&
460 Ptr[SizeTmp-1] != Ptr[SizeTmp])
461 ++SizeTmp;
462
463 // Found backslash<whitespace><newline>. Parse the char after it.
464 Size += SizeTmp;
465 Ptr += SizeTmp;
466
467 // Use slow version to accumulate a correct size field.
468 return getCharAndSizeSlowNoWarn(Ptr, Size, Features);
469 }
470 } while (isWhitespace(Ptr[SizeTmp]));
471 }
472
473 // Otherwise, this is not an escaped newline, just return the slash.
474 return '\\';
475 }
476
477 // If this is a trigraph, process it.
478 if (Features.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
479 // If this is actually a legal trigraph (not something like "??x"), return
480 // it.
481 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
482 Ptr += 3;
483 Size += 3;
484 if (C == '\\') goto Slash;
485 return C;
486 }
487 }
488
489 // If this is neither, return a single character.
490 ++Size;
491 return *Ptr;
492}
493
494//===----------------------------------------------------------------------===//
495// Helper methods for lexing.
496//===----------------------------------------------------------------------===//
497
Chris Lattnerd2177732007-07-20 16:59:19 +0000498void Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000499 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
500 unsigned Size;
501 unsigned char C = *CurPtr++;
502 while (isIdentifierBody(C)) {
503 C = *CurPtr++;
504 }
505 --CurPtr; // Back up over the skipped character.
506
507 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
508 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
509 // FIXME: UCNs.
510 if (C != '\\' && C != '?' && (C != '$' || !Features.DollarIdents)) {
511FinishIdentifier:
512 const char *IdStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +0000513 FormTokenWithChars(Result, CurPtr, tok::identifier);
Reid Spencer5f016e22007-07-11 17:01:13 +0000514
515 // If we are in raw mode, return this identifier raw. There is no need to
516 // look up identifier information or attempt to macro expand it.
517 if (LexingRawMode) return;
518
519 // Fill in Result.IdentifierInfo, looking up the identifier in the
520 // identifier table.
Chris Lattner168ae2d2007-10-17 20:41:00 +0000521 PP->LookUpIdentifierInfo(Result, IdStart);
Reid Spencer5f016e22007-07-11 17:01:13 +0000522
523 // Finally, now that we know we have an identifier, pass this off to the
524 // preprocessor, which may macro expand it or something.
Chris Lattner168ae2d2007-10-17 20:41:00 +0000525 return PP->HandleIdentifier(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +0000526 }
527
528 // Otherwise, $,\,? in identifier found. Enter slower path.
529
530 C = getCharAndSize(CurPtr, Size);
531 while (1) {
532 if (C == '$') {
533 // If we hit a $ and they are not supported in identifiers, we are done.
534 if (!Features.DollarIdents) goto FinishIdentifier;
535
536 // Otherwise, emit a diagnostic and continue.
537 Diag(CurPtr, diag::ext_dollar_in_identifier);
538 CurPtr = ConsumeChar(CurPtr, Size, Result);
539 C = getCharAndSize(CurPtr, Size);
540 continue;
541 } else if (!isIdentifierBody(C)) { // FIXME: UCNs.
542 // Found end of identifier.
543 goto FinishIdentifier;
544 }
545
546 // Otherwise, this character is good, consume it.
547 CurPtr = ConsumeChar(CurPtr, Size, Result);
548
549 C = getCharAndSize(CurPtr, Size);
550 while (isIdentifierBody(C)) { // FIXME: UCNs.
551 CurPtr = ConsumeChar(CurPtr, Size, Result);
552 C = getCharAndSize(CurPtr, Size);
553 }
554 }
555}
556
557
Nate Begeman5253c7f2008-04-14 02:26:39 +0000558/// LexNumericConstant - Lex the remainder of a integer or floating point
Reid Spencer5f016e22007-07-11 17:01:13 +0000559/// constant. From[-1] is the first character lexed. Return the end of the
560/// constant.
Chris Lattnerd2177732007-07-20 16:59:19 +0000561void Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000562 unsigned Size;
563 char C = getCharAndSize(CurPtr, Size);
564 char PrevCh = 0;
565 while (isNumberBody(C)) { // FIXME: UCNs?
566 CurPtr = ConsumeChar(CurPtr, Size, Result);
567 PrevCh = C;
568 C = getCharAndSize(CurPtr, Size);
569 }
570
571 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
572 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e'))
573 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
574
575 // If we have a hex FP constant, continue.
576 if (Features.HexFloats &&
577 (C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p'))
578 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
579
Reid Spencer5f016e22007-07-11 17:01:13 +0000580 // Update the location of token as well as BufferPtr.
Chris Lattner9e6293d2008-10-12 04:51:35 +0000581 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
Reid Spencer5f016e22007-07-11 17:01:13 +0000582}
583
584/// LexStringLiteral - Lex the remainder of a string literal, after having lexed
585/// either " or L".
Chris Lattnerd88dc482008-10-12 04:05:48 +0000586void Lexer::LexStringLiteral(Token &Result, const char *CurPtr, bool Wide) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000587 const char *NulCharacter = 0; // Does this string contain the \0 character?
588
589 char C = getAndAdvanceChar(CurPtr, Result);
590 while (C != '"') {
591 // Skip escaped characters.
592 if (C == '\\') {
593 // Skip the escaped character.
594 C = getAndAdvanceChar(CurPtr, Result);
595 } else if (C == '\n' || C == '\r' || // Newline.
596 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
597 if (!LexingRawMode) Diag(BufferPtr, diag::err_unterminated_string);
Chris Lattner9e6293d2008-10-12 04:51:35 +0000598 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Reid Spencer5f016e22007-07-11 17:01:13 +0000599 return;
600 } else if (C == 0) {
601 NulCharacter = CurPtr-1;
602 }
603 C = getAndAdvanceChar(CurPtr, Result);
604 }
605
606 // If a nul character existed in the string, warn about it.
607 if (NulCharacter) Diag(NulCharacter, diag::null_in_string);
608
Reid Spencer5f016e22007-07-11 17:01:13 +0000609 // Update the location of the token as well as the BufferPtr instance var.
Chris Lattner9e6293d2008-10-12 04:51:35 +0000610 FormTokenWithChars(Result, CurPtr,
611 Wide ? tok::wide_string_literal : tok::string_literal);
Reid Spencer5f016e22007-07-11 17:01:13 +0000612}
613
614/// LexAngledStringLiteral - Lex the remainder of an angled string literal,
615/// after having lexed the '<' character. This is used for #include filenames.
Chris Lattnerd2177732007-07-20 16:59:19 +0000616void Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000617 const char *NulCharacter = 0; // Does this string contain the \0 character?
618
619 char C = getAndAdvanceChar(CurPtr, Result);
620 while (C != '>') {
621 // Skip escaped characters.
622 if (C == '\\') {
623 // Skip the escaped character.
624 C = getAndAdvanceChar(CurPtr, Result);
625 } else if (C == '\n' || C == '\r' || // Newline.
626 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
627 if (!LexingRawMode) Diag(BufferPtr, diag::err_unterminated_string);
Chris Lattner9e6293d2008-10-12 04:51:35 +0000628 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Reid Spencer5f016e22007-07-11 17:01:13 +0000629 return;
630 } else if (C == 0) {
631 NulCharacter = CurPtr-1;
632 }
633 C = getAndAdvanceChar(CurPtr, Result);
634 }
635
636 // If a nul character existed in the string, warn about it.
637 if (NulCharacter) Diag(NulCharacter, diag::null_in_string);
638
Reid Spencer5f016e22007-07-11 17:01:13 +0000639 // Update the location of token as well as BufferPtr.
Chris Lattner9e6293d2008-10-12 04:51:35 +0000640 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
Reid Spencer5f016e22007-07-11 17:01:13 +0000641}
642
643
644/// LexCharConstant - Lex the remainder of a character constant, after having
645/// lexed either ' or L'.
Chris Lattnerd2177732007-07-20 16:59:19 +0000646void Lexer::LexCharConstant(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000647 const char *NulCharacter = 0; // Does this character contain the \0 character?
648
649 // Handle the common case of 'x' and '\y' efficiently.
650 char C = getAndAdvanceChar(CurPtr, Result);
651 if (C == '\'') {
652 if (!LexingRawMode) Diag(BufferPtr, diag::err_empty_character);
Chris Lattner9e6293d2008-10-12 04:51:35 +0000653 FormTokenWithChars(Result, CurPtr, tok::unknown);
Reid Spencer5f016e22007-07-11 17:01:13 +0000654 return;
655 } else if (C == '\\') {
656 // Skip the escaped character.
657 // FIXME: UCN's.
658 C = getAndAdvanceChar(CurPtr, Result);
659 }
660
661 if (C && C != '\n' && C != '\r' && CurPtr[0] == '\'') {
662 ++CurPtr;
663 } else {
664 // Fall back on generic code for embedded nulls, newlines, wide chars.
665 do {
666 // Skip escaped characters.
667 if (C == '\\') {
668 // Skip the escaped character.
669 C = getAndAdvanceChar(CurPtr, Result);
670 } else if (C == '\n' || C == '\r' || // Newline.
671 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
672 if (!LexingRawMode) Diag(BufferPtr, diag::err_unterminated_char);
Chris Lattner9e6293d2008-10-12 04:51:35 +0000673 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Reid Spencer5f016e22007-07-11 17:01:13 +0000674 return;
675 } else if (C == 0) {
676 NulCharacter = CurPtr-1;
677 }
678 C = getAndAdvanceChar(CurPtr, Result);
679 } while (C != '\'');
680 }
681
682 if (NulCharacter) Diag(NulCharacter, diag::null_in_char);
683
Reid Spencer5f016e22007-07-11 17:01:13 +0000684 // Update the location of token as well as BufferPtr.
Chris Lattner9e6293d2008-10-12 04:51:35 +0000685 FormTokenWithChars(Result, CurPtr, tok::char_constant);
Reid Spencer5f016e22007-07-11 17:01:13 +0000686}
687
688/// SkipWhitespace - Efficiently skip over a series of whitespace characters.
689/// Update BufferPtr to point to the next non-whitespace character and return.
Chris Lattnerd88dc482008-10-12 04:05:48 +0000690///
691/// This method forms a token and returns true if KeepWhitespaceMode is enabled.
692///
693bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000694 // Whitespace - Skip it, then return the token after the whitespace.
695 unsigned char Char = *CurPtr; // Skip consequtive spaces efficiently.
696 while (1) {
697 // Skip horizontal whitespace very aggressively.
698 while (isHorizontalWhitespace(Char))
699 Char = *++CurPtr;
700
701 // Otherwise if we something other than whitespace, we're done.
702 if (Char != '\n' && Char != '\r')
703 break;
704
705 if (ParsingPreprocessorDirective) {
706 // End of preprocessor directive line, let LexTokenInternal handle this.
707 BufferPtr = CurPtr;
Chris Lattnerd88dc482008-10-12 04:05:48 +0000708 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000709 }
710
711 // ok, but handle newline.
712 // The returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +0000713 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +0000714 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +0000715 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +0000716 Char = *++CurPtr;
717 }
718
719 // If this isn't immediately after a newline, there is leading space.
720 char PrevChar = CurPtr[-1];
721 if (PrevChar != '\n' && PrevChar != '\r')
Chris Lattnerd2177732007-07-20 16:59:19 +0000722 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +0000723
Chris Lattnerd88dc482008-10-12 04:05:48 +0000724 // If the client wants us to return whitespace, return it now.
725 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +0000726 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd88dc482008-10-12 04:05:48 +0000727 return true;
728 }
729
Reid Spencer5f016e22007-07-11 17:01:13 +0000730 BufferPtr = CurPtr;
Chris Lattnerd88dc482008-10-12 04:05:48 +0000731 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000732}
733
734// SkipBCPLComment - We have just read the // characters from input. Skip until
735// we find the newline character thats terminate the comment. Then update
Chris Lattner2d381892008-10-12 04:15:42 +0000736/// BufferPtr and return. If we're in KeepCommentMode, this will form the token
737/// and return true.
Chris Lattnerd2177732007-07-20 16:59:19 +0000738bool Lexer::SkipBCPLComment(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000739 // If BCPL comments aren't explicitly enabled for this language, emit an
740 // extension warning.
741 if (!Features.BCPLComment) {
742 Diag(BufferPtr, diag::ext_bcpl_comment);
743
744 // Mark them enabled so we only emit one warning for this translation
745 // unit.
746 Features.BCPLComment = true;
747 }
748
749 // Scan over the body of the comment. The common case, when scanning, is that
750 // the comment contains normal ascii characters with nothing interesting in
751 // them. As such, optimize for this case with the inner loop.
752 char C;
753 do {
754 C = *CurPtr;
755 // FIXME: Speedup BCPL comment lexing. Just scan for a \n or \r character.
756 // If we find a \n character, scan backwards, checking to see if it's an
757 // escaped newline, like we do for block comments.
758
759 // Skip over characters in the fast loop.
760 while (C != 0 && // Potentially EOF.
761 C != '\\' && // Potentially escaped newline.
762 C != '?' && // Potentially trigraph.
763 C != '\n' && C != '\r') // Newline or DOS-style newline.
764 C = *++CurPtr;
765
766 // If this is a newline, we're done.
767 if (C == '\n' || C == '\r')
768 break; // Found the newline? Break out!
769
770 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
771 // properly decode the character.
772 const char *OldPtr = CurPtr;
773 C = getAndAdvanceChar(CurPtr, Result);
774
775 // If we read multiple characters, and one of those characters was a \r or
776 // \n, then we had an escaped newline within the comment. Emit diagnostic
777 // unless the next line is also a // comment.
778 if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') {
779 for (; OldPtr != CurPtr; ++OldPtr)
780 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
781 // Okay, we found a // comment that ends in a newline, if the next
782 // line is also a // comment, but has spaces, don't emit a diagnostic.
783 if (isspace(C)) {
784 const char *ForwardPtr = CurPtr;
785 while (isspace(*ForwardPtr)) // Skip whitespace.
786 ++ForwardPtr;
787 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
788 break;
789 }
790
791 Diag(OldPtr-1, diag::ext_multi_line_bcpl_comment);
792 break;
793 }
794 }
795
796 if (CurPtr == BufferEnd+1) { --CurPtr; break; }
797 } while (C != '\n' && C != '\r');
798
799 // Found but did not consume the newline.
800
801 // If we are returning comments as tokens, return this comment as a token.
Chris Lattnerfa95a012008-10-12 03:22:02 +0000802 if (inKeepCommentMode())
Reid Spencer5f016e22007-07-11 17:01:13 +0000803 return SaveBCPLComment(Result, CurPtr);
804
805 // If we are inside a preprocessor directive and we see the end of line,
806 // return immediately, so that the lexer can return this as an EOM token.
807 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
808 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +0000809 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000810 }
811
812 // Otherwise, eat the \n character. We don't care if this is a \n\r or
Chris Lattner7a4f0042008-10-12 00:23:07 +0000813 // \r\n sequence. This is an efficiency hack (because we know the \n can't
Chris Lattnerd88dc482008-10-12 04:05:48 +0000814 // contribute to another token), it isn't needed for correctness. Note that
815 // this is ok even in KeepWhitespaceMode, because we would have returned the
816 /// comment above in that mode.
Reid Spencer5f016e22007-07-11 17:01:13 +0000817 ++CurPtr;
818
819 // The next returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +0000820 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +0000821 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +0000822 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +0000823 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +0000824 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000825}
826
827/// SaveBCPLComment - If in save-comment mode, package up this BCPL comment in
828/// an appropriate way and return it.
Chris Lattnerd2177732007-07-20 16:59:19 +0000829bool Lexer::SaveBCPLComment(Token &Result, const char *CurPtr) {
Chris Lattner9e6293d2008-10-12 04:51:35 +0000830 // If we're not in a preprocessor directive, just return the // comment
831 // directly.
832 FormTokenWithChars(Result, CurPtr, tok::comment);
Reid Spencer5f016e22007-07-11 17:01:13 +0000833
Chris Lattner9e6293d2008-10-12 04:51:35 +0000834 if (!ParsingPreprocessorDirective)
835 return true;
836
837 // If this BCPL-style comment is in a macro definition, transmogrify it into
838 // a C-style block comment.
839 std::string Spelling = PP->getSpelling(Result);
840 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not bcpl comment?");
841 Spelling[1] = '*'; // Change prefix to "/*".
842 Spelling += "*/"; // add suffix.
843
844 Result.setKind(tok::comment);
845 Result.setLocation(PP->CreateString(&Spelling[0], Spelling.size(),
846 Result.getLocation()));
847 Result.setLength(Spelling.size());
Chris Lattner2d381892008-10-12 04:15:42 +0000848 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000849}
850
851/// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
852/// character (either \n or \r) is part of an escaped newline sequence. Issue a
853/// diagnostic if so. We know that the is inside of a block comment.
854static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
855 Lexer *L) {
856 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
857
858 // Back up off the newline.
859 --CurPtr;
860
861 // If this is a two-character newline sequence, skip the other character.
862 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
863 // \n\n or \r\r -> not escaped newline.
864 if (CurPtr[0] == CurPtr[1])
865 return false;
866 // \n\r or \r\n -> skip the newline.
867 --CurPtr;
868 }
869
870 // If we have horizontal whitespace, skip over it. We allow whitespace
871 // between the slash and newline.
872 bool HasSpace = false;
873 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
874 --CurPtr;
875 HasSpace = true;
876 }
877
878 // If we have a slash, we know this is an escaped newline.
879 if (*CurPtr == '\\') {
880 if (CurPtr[-1] != '*') return false;
881 } else {
882 // It isn't a slash, is it the ?? / trigraph?
883 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
884 CurPtr[-3] != '*')
885 return false;
886
887 // This is the trigraph ending the comment. Emit a stern warning!
888 CurPtr -= 2;
889
890 // If no trigraphs are enabled, warn that we ignored this trigraph and
891 // ignore this * character.
892 if (!L->getFeatures().Trigraphs) {
893 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
894 return false;
895 }
896 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
897 }
898
899 // Warn about having an escaped newline between the */ characters.
900 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
901
902 // If there was space between the backslash and newline, warn about it.
903 if (HasSpace) L->Diag(CurPtr, diag::backslash_newline_space);
904
905 return true;
906}
907
908#ifdef __SSE2__
909#include <emmintrin.h>
910#elif __ALTIVEC__
911#include <altivec.h>
912#undef bool
913#endif
914
915/// SkipBlockComment - We have just read the /* characters from input. Read
916/// until we find the */ characters that terminate the comment. Note that we
917/// don't bother decoding trigraphs or escaped newlines in block comments,
918/// because they cannot cause the comment to end. The only thing that can
919/// happen is the comment could end with an escaped newline between the */ end
920/// of comment.
Chris Lattner2d381892008-10-12 04:15:42 +0000921///
922/// If KeepCommentMode is enabled, this forms a token from the comment and
923/// returns true.
Chris Lattnerd2177732007-07-20 16:59:19 +0000924bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000925 // Scan one character past where we should, looking for a '/' character. Once
926 // we find it, check to see if it was preceeded by a *. This common
927 // optimization helps people who like to put a lot of * characters in their
928 // comments.
Chris Lattner8146b682007-07-21 23:43:37 +0000929
930 // The first character we get with newlines and trigraphs skipped to handle
931 // the degenerate /*/ case below correctly if the * has an escaped newline
932 // after it.
933 unsigned CharSize;
934 unsigned char C = getCharAndSize(CurPtr, CharSize);
935 CurPtr += CharSize;
Reid Spencer5f016e22007-07-11 17:01:13 +0000936 if (C == 0 && CurPtr == BufferEnd+1) {
Chris Lattner0af57422008-10-12 01:31:51 +0000937 if (!LexingRawMode)
938 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner31f0eca2008-10-12 04:19:49 +0000939 --CurPtr;
940
941 // KeepWhitespaceMode should return this broken comment as a token. Since
942 // it isn't a well formed comment, just return it as an 'unknown' token.
943 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +0000944 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner31f0eca2008-10-12 04:19:49 +0000945 return true;
946 }
947
948 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +0000949 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000950 }
951
Chris Lattner8146b682007-07-21 23:43:37 +0000952 // Check to see if the first character after the '/*' is another /. If so,
953 // then this slash does not end the block comment, it is part of it.
954 if (C == '/')
955 C = *CurPtr++;
956
Reid Spencer5f016e22007-07-11 17:01:13 +0000957 while (1) {
958 // Skip over all non-interesting characters until we find end of buffer or a
959 // (probably ending) '/' character.
960 if (CurPtr + 24 < BufferEnd) {
961 // While not aligned to a 16-byte boundary.
962 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
963 C = *CurPtr++;
964
965 if (C == '/') goto FoundSlash;
966
967#ifdef __SSE2__
968 __m128i Slashes = _mm_set_epi8('/', '/', '/', '/', '/', '/', '/', '/',
969 '/', '/', '/', '/', '/', '/', '/', '/');
970 while (CurPtr+16 <= BufferEnd &&
971 _mm_movemask_epi8(_mm_cmpeq_epi8(*(__m128i*)CurPtr, Slashes)) == 0)
972 CurPtr += 16;
973#elif __ALTIVEC__
974 __vector unsigned char Slashes = {
975 '/', '/', '/', '/', '/', '/', '/', '/',
976 '/', '/', '/', '/', '/', '/', '/', '/'
977 };
978 while (CurPtr+16 <= BufferEnd &&
979 !vec_any_eq(*(vector unsigned char*)CurPtr, Slashes))
980 CurPtr += 16;
981#else
982 // Scan for '/' quickly. Many block comments are very large.
983 while (CurPtr[0] != '/' &&
984 CurPtr[1] != '/' &&
985 CurPtr[2] != '/' &&
986 CurPtr[3] != '/' &&
987 CurPtr+4 < BufferEnd) {
988 CurPtr += 4;
989 }
990#endif
991
992 // It has to be one of the bytes scanned, increment to it and read one.
993 C = *CurPtr++;
994 }
995
996 // Loop to scan the remainder.
997 while (C != '/' && C != '\0')
998 C = *CurPtr++;
999
1000 FoundSlash:
1001 if (C == '/') {
1002 if (CurPtr[-2] == '*') // We found the final */. We're done!
1003 break;
1004
1005 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
1006 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
1007 // We found the final */, though it had an escaped newline between the
1008 // * and /. We're done!
1009 break;
1010 }
1011 }
1012 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
1013 // If this is a /* inside of the comment, emit a warning. Don't do this
1014 // if this is a /*/, which will end the comment. This misses cases with
1015 // embedded escaped newlines, but oh well.
Chris Lattner0af57422008-10-12 01:31:51 +00001016 Diag(CurPtr-1, diag::warn_nested_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001017 }
1018 } else if (C == 0 && CurPtr == BufferEnd+1) {
Chris Lattner0af57422008-10-12 01:31:51 +00001019 if (!LexingRawMode) Diag(BufferPtr, diag::err_unterminated_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001020 // Note: the user probably forgot a */. We could continue immediately
1021 // after the /*, but this would involve lexing a lot of what really is the
1022 // comment, which surely would confuse the parser.
Chris Lattner31f0eca2008-10-12 04:19:49 +00001023 --CurPtr;
1024
1025 // KeepWhitespaceMode should return this broken comment as a token. Since
1026 // it isn't a well formed comment, just return it as an 'unknown' token.
1027 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001028 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner31f0eca2008-10-12 04:19:49 +00001029 return true;
1030 }
1031
1032 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001033 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001034 }
1035 C = *CurPtr++;
1036 }
1037
1038 // If we are returning comments as tokens, return this comment as a token.
Chris Lattnerfa95a012008-10-12 03:22:02 +00001039 if (inKeepCommentMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001040 FormTokenWithChars(Result, CurPtr, tok::comment);
Chris Lattner2d381892008-10-12 04:15:42 +00001041 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001042 }
1043
1044 // It is common for the tokens immediately after a /**/ comment to be
1045 // whitespace. Instead of going through the big switch, handle it
Chris Lattnerd88dc482008-10-12 04:05:48 +00001046 // efficiently now. This is safe even in KeepWhitespaceMode because we would
1047 // have already returned above with the comment as a token.
Reid Spencer5f016e22007-07-11 17:01:13 +00001048 if (isHorizontalWhitespace(*CurPtr)) {
Chris Lattnerd2177732007-07-20 16:59:19 +00001049 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001050 SkipWhitespace(Result, CurPtr+1);
Chris Lattner2d381892008-10-12 04:15:42 +00001051 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001052 }
1053
1054 // Otherwise, just return so that the next character will be lexed as a token.
1055 BufferPtr = CurPtr;
Chris Lattnerd2177732007-07-20 16:59:19 +00001056 Result.setFlag(Token::LeadingSpace);
Chris Lattner2d381892008-10-12 04:15:42 +00001057 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001058}
1059
1060//===----------------------------------------------------------------------===//
1061// Primary Lexing Entry Points
1062//===----------------------------------------------------------------------===//
1063
Reid Spencer5f016e22007-07-11 17:01:13 +00001064/// ReadToEndOfLine - Read the rest of the current preprocessor line as an
1065/// uninterpreted string. This switches the lexer out of directive mode.
1066std::string Lexer::ReadToEndOfLine() {
1067 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
1068 "Must be in a preprocessing directive!");
1069 std::string Result;
Chris Lattnerd2177732007-07-20 16:59:19 +00001070 Token Tmp;
Reid Spencer5f016e22007-07-11 17:01:13 +00001071
1072 // CurPtr - Cache BufferPtr in an automatic variable.
1073 const char *CurPtr = BufferPtr;
1074 while (1) {
1075 char Char = getAndAdvanceChar(CurPtr, Tmp);
1076 switch (Char) {
1077 default:
1078 Result += Char;
1079 break;
1080 case 0: // Null.
1081 // Found end of file?
1082 if (CurPtr-1 != BufferEnd) {
1083 // Nope, normal character, continue.
1084 Result += Char;
1085 break;
1086 }
1087 // FALL THROUGH.
1088 case '\r':
1089 case '\n':
1090 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
1091 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
1092 BufferPtr = CurPtr-1;
1093
1094 // Next, lex the character, which should handle the EOM transition.
1095 Lex(Tmp);
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001096 assert(Tmp.is(tok::eom) && "Unexpected token!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001097
1098 // Finally, we're done, return the string we found.
1099 return Result;
1100 }
1101 }
1102}
1103
1104/// LexEndOfFile - CurPtr points to the end of this file. Handle this
1105/// condition, reporting diagnostics and handling other edge cases as required.
1106/// This returns true if Result contains a token, false if PP.Lex should be
1107/// called again.
Chris Lattnerd2177732007-07-20 16:59:19 +00001108bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001109 // If we hit the end of the file while parsing a preprocessor directive,
1110 // end the preprocessor directive first. The next token returned will
1111 // then be the end of file.
1112 if (ParsingPreprocessorDirective) {
1113 // Done parsing the "line".
1114 ParsingPreprocessorDirective = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001115 // Update the location of token as well as BufferPtr.
Chris Lattner9e6293d2008-10-12 04:51:35 +00001116 FormTokenWithChars(Result, CurPtr, tok::eom);
Reid Spencer5f016e22007-07-11 17:01:13 +00001117
1118 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattnerf744d132008-10-12 03:27:19 +00001119 SetCommentRetentionState(PP->getCommentRetentionState());
Reid Spencer5f016e22007-07-11 17:01:13 +00001120 return true; // Have a token.
1121 }
1122
1123 // If we are in raw mode, return this event as an EOF token. Let the caller
1124 // that put us in raw mode handle the event.
1125 if (LexingRawMode) {
1126 Result.startToken();
1127 BufferPtr = BufferEnd;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001128 FormTokenWithChars(Result, BufferEnd, tok::eof);
Reid Spencer5f016e22007-07-11 17:01:13 +00001129 return true;
1130 }
1131
1132 // Otherwise, issue diagnostics for unterminated #if and missing newline.
1133
1134 // If we are in a #if directive, emit an error.
1135 while (!ConditionalStack.empty()) {
Ted Kremenekd6a2e7d2008-11-12 23:13:54 +00001136 PreprocessorLexer::Diag(ConditionalStack.back().IfLoc,
1137 diag::err_pp_unterminated_conditional);
1138
Reid Spencer5f016e22007-07-11 17:01:13 +00001139 ConditionalStack.pop_back();
1140 }
1141
Chris Lattnerb25e5d72008-04-12 05:54:25 +00001142 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
1143 // a pedwarn.
1144 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r'))
Reid Spencer5f016e22007-07-11 17:01:13 +00001145 Diag(BufferEnd, diag::ext_no_newline_eof);
1146
1147 BufferPtr = CurPtr;
1148
1149 // Finally, let the preprocessor handle this.
Chris Lattner168ae2d2007-10-17 20:41:00 +00001150 return PP->HandleEndOfFile(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001151}
1152
1153/// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
1154/// the specified lexer will return a tok::l_paren token, 0 if it is something
1155/// else and 2 if there are no more tokens in the buffer controlled by the
1156/// lexer.
1157unsigned Lexer::isNextPPTokenLParen() {
1158 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
1159
1160 // Switch to 'skipping' mode. This will ensure that we can lex a token
1161 // without emitting diagnostics, disables macro expansion, and will cause EOF
1162 // to return an EOF token instead of popping the include stack.
1163 LexingRawMode = true;
1164
1165 // Save state that can be changed while lexing so that we can restore it.
1166 const char *TmpBufferPtr = BufferPtr;
1167
Chris Lattnerd2177732007-07-20 16:59:19 +00001168 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001169 Tok.startToken();
1170 LexTokenInternal(Tok);
1171
1172 // Restore state that may have changed.
1173 BufferPtr = TmpBufferPtr;
1174
1175 // Restore the lexer back to non-skipping mode.
1176 LexingRawMode = false;
1177
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001178 if (Tok.is(tok::eof))
Reid Spencer5f016e22007-07-11 17:01:13 +00001179 return 2;
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001180 return Tok.is(tok::l_paren);
Reid Spencer5f016e22007-07-11 17:01:13 +00001181}
1182
1183
1184/// LexTokenInternal - This implements a simple C family lexer. It is an
1185/// extremely performance critical piece of code. This assumes that the buffer
1186/// has a null character at the end of the file. Return true if an error
1187/// occurred and compilation should terminate, false if normal. This returns a
1188/// preprocessing token, not a normal token, as such, it is an internal
1189/// interface. It assumes that the Flags of result have been cleared before
1190/// calling this.
Chris Lattnerd2177732007-07-20 16:59:19 +00001191void Lexer::LexTokenInternal(Token &Result) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001192LexNextToken:
1193 // New token, can't need cleaning yet.
Chris Lattnerd2177732007-07-20 16:59:19 +00001194 Result.clearFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00001195 Result.setIdentifierInfo(0);
1196
1197 // CurPtr - Cache BufferPtr in an automatic variable.
1198 const char *CurPtr = BufferPtr;
1199
1200 // Small amounts of horizontal whitespace is very common between tokens.
1201 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
1202 ++CurPtr;
1203 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
1204 ++CurPtr;
Chris Lattnerd88dc482008-10-12 04:05:48 +00001205
1206 // If we are keeping whitespace and other tokens, just return what we just
1207 // skipped. The next lexer invocation will return the token after the
1208 // whitespace.
1209 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001210 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd88dc482008-10-12 04:05:48 +00001211 return;
1212 }
1213
Reid Spencer5f016e22007-07-11 17:01:13 +00001214 BufferPtr = CurPtr;
Chris Lattnerd2177732007-07-20 16:59:19 +00001215 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001216 }
1217
1218 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
1219
1220 // Read a character, advancing over it.
1221 char Char = getAndAdvanceChar(CurPtr, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001222 tok::TokenKind Kind;
1223
Reid Spencer5f016e22007-07-11 17:01:13 +00001224 switch (Char) {
1225 case 0: // Null.
1226 // Found end of file?
1227 if (CurPtr-1 == BufferEnd) {
1228 // Read the PP instance variable into an automatic variable, because
1229 // LexEndOfFile will often delete 'this'.
Chris Lattner168ae2d2007-10-17 20:41:00 +00001230 Preprocessor *PPCache = PP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001231 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
1232 return; // Got a token to return.
Chris Lattner168ae2d2007-10-17 20:41:00 +00001233 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
1234 return PPCache->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001235 }
1236
1237 Diag(CurPtr-1, diag::null_in_file);
Chris Lattnerd2177732007-07-20 16:59:19 +00001238 Result.setFlag(Token::LeadingSpace);
Chris Lattnerd88dc482008-10-12 04:05:48 +00001239 if (SkipWhitespace(Result, CurPtr))
1240 return; // KeepWhitespaceMode
1241
Reid Spencer5f016e22007-07-11 17:01:13 +00001242 goto LexNextToken; // GCC isn't tail call eliminating.
1243 case '\n':
1244 case '\r':
1245 // If we are inside a preprocessor directive and we see the end of line,
1246 // we know we are done with the directive, so return an EOM token.
1247 if (ParsingPreprocessorDirective) {
1248 // Done parsing the "line".
1249 ParsingPreprocessorDirective = false;
1250
1251 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattnerf744d132008-10-12 03:27:19 +00001252 SetCommentRetentionState(PP->getCommentRetentionState());
Reid Spencer5f016e22007-07-11 17:01:13 +00001253
1254 // Since we consumed a newline, we are back at the start of a line.
1255 IsAtStartOfLine = true;
1256
Chris Lattner9e6293d2008-10-12 04:51:35 +00001257 Kind = tok::eom;
Reid Spencer5f016e22007-07-11 17:01:13 +00001258 break;
1259 }
1260 // The returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00001261 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00001262 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00001263 Result.clearFlag(Token::LeadingSpace);
Chris Lattnerd88dc482008-10-12 04:05:48 +00001264
1265 if (SkipWhitespace(Result, CurPtr))
1266 return; // KeepWhitespaceMode
Reid Spencer5f016e22007-07-11 17:01:13 +00001267 goto LexNextToken; // GCC isn't tail call eliminating.
1268 case ' ':
1269 case '\t':
1270 case '\f':
1271 case '\v':
Chris Lattner8133cfc2007-07-22 06:29:05 +00001272 SkipHorizontalWhitespace:
Chris Lattnerd2177732007-07-20 16:59:19 +00001273 Result.setFlag(Token::LeadingSpace);
Chris Lattnerd88dc482008-10-12 04:05:48 +00001274 if (SkipWhitespace(Result, CurPtr))
1275 return; // KeepWhitespaceMode
Chris Lattner8133cfc2007-07-22 06:29:05 +00001276
1277 SkipIgnoredUnits:
1278 CurPtr = BufferPtr;
1279
1280 // If the next token is obviously a // or /* */ comment, skip it efficiently
1281 // too (without going through the big switch stmt).
Chris Lattnerfa95a012008-10-12 03:22:02 +00001282 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode()) {
Chris Lattner8133cfc2007-07-22 06:29:05 +00001283 SkipBCPLComment(Result, CurPtr+2);
1284 goto SkipIgnoredUnits;
Chris Lattnerfa95a012008-10-12 03:22:02 +00001285 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
Chris Lattner8133cfc2007-07-22 06:29:05 +00001286 SkipBlockComment(Result, CurPtr+2);
1287 goto SkipIgnoredUnits;
1288 } else if (isHorizontalWhitespace(*CurPtr)) {
1289 goto SkipHorizontalWhitespace;
1290 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001291 goto LexNextToken; // GCC isn't tail call eliminating.
1292
Chris Lattner3a570772008-01-03 17:58:54 +00001293 // C99 6.4.4.1: Integer Constants.
1294 // C99 6.4.4.2: Floating Constants.
1295 case '0': case '1': case '2': case '3': case '4':
1296 case '5': case '6': case '7': case '8': case '9':
1297 // Notify MIOpt that we read a non-whitespace/non-comment token.
1298 MIOpt.ReadToken();
1299 return LexNumericConstant(Result, CurPtr);
1300
1301 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
Reid Spencer5f016e22007-07-11 17:01:13 +00001302 // Notify MIOpt that we read a non-whitespace/non-comment token.
1303 MIOpt.ReadToken();
1304 Char = getCharAndSize(CurPtr, SizeTmp);
1305
1306 // Wide string literal.
1307 if (Char == '"')
1308 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
1309 true);
1310
1311 // Wide character constant.
1312 if (Char == '\'')
1313 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
1314 // FALL THROUGH, treating L like the start of an identifier.
1315
1316 // C99 6.4.2: Identifiers.
1317 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
1318 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
1319 case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U':
1320 case 'V': case 'W': case 'X': case 'Y': case 'Z':
1321 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
1322 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
1323 case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u':
1324 case 'v': case 'w': case 'x': case 'y': case 'z':
1325 case '_':
1326 // Notify MIOpt that we read a non-whitespace/non-comment token.
1327 MIOpt.ReadToken();
1328 return LexIdentifier(Result, CurPtr);
Chris Lattner3a570772008-01-03 17:58:54 +00001329
1330 case '$': // $ in identifiers.
1331 if (Features.DollarIdents) {
1332 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
1333 // Notify MIOpt that we read a non-whitespace/non-comment token.
1334 MIOpt.ReadToken();
1335 return LexIdentifier(Result, CurPtr);
1336 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001337
Chris Lattner9e6293d2008-10-12 04:51:35 +00001338 Kind = tok::unknown;
Chris Lattner3a570772008-01-03 17:58:54 +00001339 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001340
1341 // C99 6.4.4: Character Constants.
1342 case '\'':
1343 // Notify MIOpt that we read a non-whitespace/non-comment token.
1344 MIOpt.ReadToken();
1345 return LexCharConstant(Result, CurPtr);
1346
1347 // C99 6.4.5: String Literals.
1348 case '"':
1349 // Notify MIOpt that we read a non-whitespace/non-comment token.
1350 MIOpt.ReadToken();
1351 return LexStringLiteral(Result, CurPtr, false);
1352
1353 // C99 6.4.6: Punctuators.
1354 case '?':
Chris Lattner9e6293d2008-10-12 04:51:35 +00001355 Kind = tok::question;
Reid Spencer5f016e22007-07-11 17:01:13 +00001356 break;
1357 case '[':
Chris Lattner9e6293d2008-10-12 04:51:35 +00001358 Kind = tok::l_square;
Reid Spencer5f016e22007-07-11 17:01:13 +00001359 break;
1360 case ']':
Chris Lattner9e6293d2008-10-12 04:51:35 +00001361 Kind = tok::r_square;
Reid Spencer5f016e22007-07-11 17:01:13 +00001362 break;
1363 case '(':
Chris Lattner9e6293d2008-10-12 04:51:35 +00001364 Kind = tok::l_paren;
Reid Spencer5f016e22007-07-11 17:01:13 +00001365 break;
1366 case ')':
Chris Lattner9e6293d2008-10-12 04:51:35 +00001367 Kind = tok::r_paren;
Reid Spencer5f016e22007-07-11 17:01:13 +00001368 break;
1369 case '{':
Chris Lattner9e6293d2008-10-12 04:51:35 +00001370 Kind = tok::l_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00001371 break;
1372 case '}':
Chris Lattner9e6293d2008-10-12 04:51:35 +00001373 Kind = tok::r_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00001374 break;
1375 case '.':
1376 Char = getCharAndSize(CurPtr, SizeTmp);
1377 if (Char >= '0' && Char <= '9') {
1378 // Notify MIOpt that we read a non-whitespace/non-comment token.
1379 MIOpt.ReadToken();
1380
1381 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
1382 } else if (Features.CPlusPlus && Char == '*') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001383 Kind = tok::periodstar;
Reid Spencer5f016e22007-07-11 17:01:13 +00001384 CurPtr += SizeTmp;
1385 } else if (Char == '.' &&
1386 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001387 Kind = tok::ellipsis;
Reid Spencer5f016e22007-07-11 17:01:13 +00001388 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1389 SizeTmp2, Result);
1390 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001391 Kind = tok::period;
Reid Spencer5f016e22007-07-11 17:01:13 +00001392 }
1393 break;
1394 case '&':
1395 Char = getCharAndSize(CurPtr, SizeTmp);
1396 if (Char == '&') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001397 Kind = tok::ampamp;
Reid Spencer5f016e22007-07-11 17:01:13 +00001398 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1399 } else if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001400 Kind = tok::ampequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00001401 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1402 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001403 Kind = tok::amp;
Reid Spencer5f016e22007-07-11 17:01:13 +00001404 }
1405 break;
1406 case '*':
1407 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001408 Kind = tok::starequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00001409 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1410 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001411 Kind = tok::star;
Reid Spencer5f016e22007-07-11 17:01:13 +00001412 }
1413 break;
1414 case '+':
1415 Char = getCharAndSize(CurPtr, SizeTmp);
1416 if (Char == '+') {
Reid Spencer5f016e22007-07-11 17:01:13 +00001417 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001418 Kind = tok::plusplus;
Reid Spencer5f016e22007-07-11 17:01:13 +00001419 } else if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00001420 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001421 Kind = tok::plusequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00001422 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001423 Kind = tok::plus;
Reid Spencer5f016e22007-07-11 17:01:13 +00001424 }
1425 break;
1426 case '-':
1427 Char = getCharAndSize(CurPtr, SizeTmp);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001428 if (Char == '-') { // --
Reid Spencer5f016e22007-07-11 17:01:13 +00001429 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001430 Kind = tok::minusminus;
Reid Spencer5f016e22007-07-11 17:01:13 +00001431 } else if (Char == '>' && Features.CPlusPlus &&
Chris Lattner9e6293d2008-10-12 04:51:35 +00001432 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
Reid Spencer5f016e22007-07-11 17:01:13 +00001433 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1434 SizeTmp2, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001435 Kind = tok::arrowstar;
1436 } else if (Char == '>') { // ->
Reid Spencer5f016e22007-07-11 17:01:13 +00001437 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001438 Kind = tok::arrow;
1439 } else if (Char == '=') { // -=
Reid Spencer5f016e22007-07-11 17:01:13 +00001440 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001441 Kind = tok::minusequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00001442 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001443 Kind = tok::minus;
Reid Spencer5f016e22007-07-11 17:01:13 +00001444 }
1445 break;
1446 case '~':
Chris Lattner9e6293d2008-10-12 04:51:35 +00001447 Kind = tok::tilde;
Reid Spencer5f016e22007-07-11 17:01:13 +00001448 break;
1449 case '!':
1450 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001451 Kind = tok::exclaimequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00001452 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1453 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001454 Kind = tok::exclaim;
Reid Spencer5f016e22007-07-11 17:01:13 +00001455 }
1456 break;
1457 case '/':
1458 // 6.4.9: Comments
1459 Char = getCharAndSize(CurPtr, SizeTmp);
1460 if (Char == '/') { // BCPL comment.
Chris Lattner2d381892008-10-12 04:15:42 +00001461 if (SkipBCPLComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
1462 return; // KeepCommentMode
1463
1464 // It is common for the tokens immediately after a // comment to be
1465 // whitespace (indentation for the next line). Instead of going through
1466 // the big switch, handle it efficiently now.
1467 goto SkipIgnoredUnits;
Reid Spencer5f016e22007-07-11 17:01:13 +00001468 } else if (Char == '*') { // /**/ comment.
1469 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattner2d381892008-10-12 04:15:42 +00001470 return; // KeepCommentMode
1471 goto LexNextToken; // GCC isn't tail call eliminating.
Reid Spencer5f016e22007-07-11 17:01:13 +00001472 } else if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00001473 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001474 Kind = tok::slashequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00001475 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001476 Kind = tok::slash;
Reid Spencer5f016e22007-07-11 17:01:13 +00001477 }
1478 break;
1479 case '%':
1480 Char = getCharAndSize(CurPtr, SizeTmp);
1481 if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001482 Kind = tok::percentequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00001483 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1484 } else if (Features.Digraphs && Char == '>') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001485 Kind = tok::r_brace; // '%>' -> '}'
Reid Spencer5f016e22007-07-11 17:01:13 +00001486 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1487 } else if (Features.Digraphs && Char == ':') {
1488 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1489 Char = getCharAndSize(CurPtr, SizeTmp);
1490 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001491 Kind = tok::hashhash; // '%:%:' -> '##'
Reid Spencer5f016e22007-07-11 17:01:13 +00001492 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1493 SizeTmp2, Result);
1494 } else if (Char == '@' && Features.Microsoft) { // %:@ -> #@ -> Charize
Reid Spencer5f016e22007-07-11 17:01:13 +00001495 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1496 Diag(BufferPtr, diag::charize_microsoft_ext);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001497 Kind = tok::hashat;
Reid Spencer5f016e22007-07-11 17:01:13 +00001498 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001499 Kind = tok::hash; // '%:' -> '#'
Reid Spencer5f016e22007-07-11 17:01:13 +00001500
1501 // We parsed a # character. If this occurs at the start of the line,
1502 // it's actually the start of a preprocessing directive. Callback to
1503 // the preprocessor to handle it.
1504 // FIXME: -fpreprocessed mode??
1505 if (Result.isAtStartOfLine() && !LexingRawMode) {
1506 BufferPtr = CurPtr;
Chris Lattner168ae2d2007-10-17 20:41:00 +00001507 PP->HandleDirective(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001508
1509 // As an optimization, if the preprocessor didn't switch lexers, tail
1510 // recurse.
Chris Lattner168ae2d2007-10-17 20:41:00 +00001511 if (PP->isCurrentLexer(this)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001512 // Start a new token. If this is a #include or something, the PP may
1513 // want us starting at the beginning of the line again. If so, set
1514 // the StartOfLine flag.
1515 if (IsAtStartOfLine) {
Chris Lattnerd2177732007-07-20 16:59:19 +00001516 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00001517 IsAtStartOfLine = false;
1518 }
1519 goto LexNextToken; // GCC isn't tail call eliminating.
1520 }
1521
Chris Lattner168ae2d2007-10-17 20:41:00 +00001522 return PP->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001523 }
1524 }
1525 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001526 Kind = tok::percent;
Reid Spencer5f016e22007-07-11 17:01:13 +00001527 }
1528 break;
1529 case '<':
1530 Char = getCharAndSize(CurPtr, SizeTmp);
1531 if (ParsingFilename) {
1532 return LexAngledStringLiteral(Result, CurPtr+SizeTmp);
1533 } else if (Char == '<' &&
1534 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001535 Kind = tok::lesslessequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00001536 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1537 SizeTmp2, Result);
1538 } else if (Char == '<') {
Reid Spencer5f016e22007-07-11 17:01:13 +00001539 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001540 Kind = tok::lessless;
Reid Spencer5f016e22007-07-11 17:01:13 +00001541 } else if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00001542 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001543 Kind = tok::lessequal;
1544 } else if (Features.Digraphs && Char == ':') { // '<:' -> '['
Reid Spencer5f016e22007-07-11 17:01:13 +00001545 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001546 Kind = tok::l_square;
1547 } else if (Features.Digraphs && Char == '%') { // '<%' -> '{'
Reid Spencer5f016e22007-07-11 17:01:13 +00001548 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001549 Kind = tok::l_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00001550 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001551 Kind = tok::less;
Reid Spencer5f016e22007-07-11 17:01:13 +00001552 }
1553 break;
1554 case '>':
1555 Char = getCharAndSize(CurPtr, SizeTmp);
1556 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00001557 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001558 Kind = tok::greaterequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00001559 } else if (Char == '>' &&
1560 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00001561 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1562 SizeTmp2, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001563 Kind = tok::greatergreaterequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00001564 } else if (Char == '>') {
Reid Spencer5f016e22007-07-11 17:01:13 +00001565 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001566 Kind = tok::greatergreater;
Reid Spencer5f016e22007-07-11 17:01:13 +00001567 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001568 Kind = tok::greater;
Reid Spencer5f016e22007-07-11 17:01:13 +00001569 }
1570 break;
1571 case '^':
1572 Char = getCharAndSize(CurPtr, SizeTmp);
1573 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00001574 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001575 Kind = tok::caretequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00001576 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001577 Kind = tok::caret;
Reid Spencer5f016e22007-07-11 17:01:13 +00001578 }
1579 break;
1580 case '|':
1581 Char = getCharAndSize(CurPtr, SizeTmp);
1582 if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001583 Kind = tok::pipeequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00001584 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1585 } else if (Char == '|') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001586 Kind = tok::pipepipe;
Reid Spencer5f016e22007-07-11 17:01:13 +00001587 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1588 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001589 Kind = tok::pipe;
Reid Spencer5f016e22007-07-11 17:01:13 +00001590 }
1591 break;
1592 case ':':
1593 Char = getCharAndSize(CurPtr, SizeTmp);
1594 if (Features.Digraphs && Char == '>') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001595 Kind = tok::r_square; // ':>' -> ']'
Reid Spencer5f016e22007-07-11 17:01:13 +00001596 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1597 } else if (Features.CPlusPlus && Char == ':') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001598 Kind = tok::coloncolon;
Reid Spencer5f016e22007-07-11 17:01:13 +00001599 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1600 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001601 Kind = tok::colon;
Reid Spencer5f016e22007-07-11 17:01:13 +00001602 }
1603 break;
1604 case ';':
Chris Lattner9e6293d2008-10-12 04:51:35 +00001605 Kind = tok::semi;
Reid Spencer5f016e22007-07-11 17:01:13 +00001606 break;
1607 case '=':
1608 Char = getCharAndSize(CurPtr, SizeTmp);
1609 if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001610 Kind = tok::equalequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00001611 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1612 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001613 Kind = tok::equal;
Reid Spencer5f016e22007-07-11 17:01:13 +00001614 }
1615 break;
1616 case ',':
Chris Lattner9e6293d2008-10-12 04:51:35 +00001617 Kind = tok::comma;
Reid Spencer5f016e22007-07-11 17:01:13 +00001618 break;
1619 case '#':
1620 Char = getCharAndSize(CurPtr, SizeTmp);
1621 if (Char == '#') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001622 Kind = tok::hashhash;
Reid Spencer5f016e22007-07-11 17:01:13 +00001623 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1624 } else if (Char == '@' && Features.Microsoft) { // #@ -> Charize
Chris Lattner9e6293d2008-10-12 04:51:35 +00001625 Kind = tok::hashat;
Reid Spencer5f016e22007-07-11 17:01:13 +00001626 Diag(BufferPtr, diag::charize_microsoft_ext);
1627 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1628 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001629 Kind = tok::hash;
Reid Spencer5f016e22007-07-11 17:01:13 +00001630 // We parsed a # character. If this occurs at the start of the line,
1631 // it's actually the start of a preprocessing directive. Callback to
1632 // the preprocessor to handle it.
1633 // FIXME: -fpreprocessed mode??
1634 if (Result.isAtStartOfLine() && !LexingRawMode) {
1635 BufferPtr = CurPtr;
Chris Lattner168ae2d2007-10-17 20:41:00 +00001636 PP->HandleDirective(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001637
1638 // As an optimization, if the preprocessor didn't switch lexers, tail
1639 // recurse.
Chris Lattner168ae2d2007-10-17 20:41:00 +00001640 if (PP->isCurrentLexer(this)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001641 // Start a new token. If this is a #include or something, the PP may
1642 // want us starting at the beginning of the line again. If so, set
1643 // the StartOfLine flag.
1644 if (IsAtStartOfLine) {
Chris Lattnerd2177732007-07-20 16:59:19 +00001645 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00001646 IsAtStartOfLine = false;
1647 }
1648 goto LexNextToken; // GCC isn't tail call eliminating.
1649 }
Chris Lattner168ae2d2007-10-17 20:41:00 +00001650 return PP->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001651 }
1652 }
1653 break;
1654
Chris Lattner3a570772008-01-03 17:58:54 +00001655 case '@':
1656 // Objective C support.
1657 if (CurPtr[-1] == '@' && Features.ObjC1)
Chris Lattner9e6293d2008-10-12 04:51:35 +00001658 Kind = tok::at;
Chris Lattner3a570772008-01-03 17:58:54 +00001659 else
Chris Lattner9e6293d2008-10-12 04:51:35 +00001660 Kind = tok::unknown;
Chris Lattner3a570772008-01-03 17:58:54 +00001661 break;
1662
Reid Spencer5f016e22007-07-11 17:01:13 +00001663 case '\\':
1664 // FIXME: UCN's.
1665 // FALL THROUGH.
1666 default:
Chris Lattner9e6293d2008-10-12 04:51:35 +00001667 Kind = tok::unknown;
Reid Spencer5f016e22007-07-11 17:01:13 +00001668 break;
1669 }
1670
1671 // Notify MIOpt that we read a non-whitespace/non-comment token.
1672 MIOpt.ReadToken();
1673
1674 // Update the location of token as well as BufferPtr.
Chris Lattner9e6293d2008-10-12 04:51:35 +00001675 FormTokenWithChars(Result, CurPtr, Kind);
Reid Spencer5f016e22007-07-11 17:01:13 +00001676}