blob: fff6f10fa9fef680acd1b0915986e0f10d083993 [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"
Chris Lattner500d3292009-01-29 05:15:15 +000029#include "clang/Lex/LexDiagnostic.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 {
Douglas Gregorbec1c9d2008-12-01 21:46:47 +000044 if (IdentifierInfo *II = getIdentifierInfo())
45 return II->getObjCKeywordID() == objcKey;
46 return false;
Chris Lattnerdbf388b2007-10-07 08:47:24 +000047}
48
49/// getObjCKeywordID - Return the ObjC keyword kind.
50tok::ObjCKeywordKind Token::getObjCKeywordID() const {
51 IdentifierInfo *specId = getIdentifierInfo();
52 return specId ? specId->getObjCKeywordID() : tok::objc_not_keyword;
53}
54
Chris Lattner53702cd2007-12-13 01:59:49 +000055
Chris Lattnerdbf388b2007-10-07 08:47:24 +000056//===----------------------------------------------------------------------===//
57// Lexer Class Implementation
58//===----------------------------------------------------------------------===//
59
Chris Lattner22d91ca2009-01-17 06:55:17 +000060void Lexer::InitLexer(const char *BufStart, const char *BufPtr,
61 const char *BufEnd) {
62 InitCharacterInfo();
63
64 BufferStart = BufStart;
65 BufferPtr = BufPtr;
66 BufferEnd = BufEnd;
67
68 assert(BufEnd[0] == 0 &&
69 "We assume that the input buffer has a null character at the end"
70 " to simplify lexing!");
71
72 Is_PragmaLexer = false;
73
74 // Start of the file is a start of line.
75 IsAtStartOfLine = true;
76
77 // We are not after parsing a #.
78 ParsingPreprocessorDirective = false;
79
80 // We are not after parsing #include.
81 ParsingFilename = false;
82
83 // We are not in raw mode. Raw mode disables diagnostics and interpretation
84 // of tokens (e.g. identifiers, thus disabling macro expansion). It is used
85 // to quickly lex the tokens of the buffer, e.g. when handling a "#if 0" block
86 // or otherwise skipping over tokens.
87 LexingRawMode = false;
88
89 // Default to not keeping comments.
90 ExtendedTokenMode = 0;
91}
92
Chris Lattner0770dab2009-01-17 07:56:59 +000093/// Lexer constructor - Create a new lexer object for the specified buffer
94/// with the specified preprocessor managing the lexing process. This lexer
95/// assumes that the associated file buffer and Preprocessor objects will
96/// outlive it, so it doesn't take ownership of either of them.
Chris Lattner88d3ac12009-01-17 08:03:42 +000097Lexer::Lexer(FileID FID, Preprocessor &PP)
98 : PreprocessorLexer(&PP, FID),
99 FileLoc(PP.getSourceManager().getLocForStartOfFile(FID)),
100 Features(PP.getLangOptions()) {
Chris Lattner0770dab2009-01-17 07:56:59 +0000101
Chris Lattner88d3ac12009-01-17 08:03:42 +0000102 const llvm::MemoryBuffer *InputFile = PP.getSourceManager().getBuffer(FID);
Chris Lattner0770dab2009-01-17 07:56:59 +0000103
104 InitLexer(InputFile->getBufferStart(), InputFile->getBufferStart(),
105 InputFile->getBufferEnd());
106
107 // Default to keeping comments if the preprocessor wants them.
108 SetCommentRetentionState(PP.getCommentRetentionState());
109}
Chris Lattnerdbf388b2007-10-07 08:47:24 +0000110
Chris Lattner168ae2d2007-10-17 20:41:00 +0000111/// Lexer constructor - Create a new raw lexer object. This object is only
Chris Lattner590f0cc2008-10-12 01:15:46 +0000112/// suitable for calls to 'LexRawToken'. This lexer assumes that the text
113/// range will outlive it, so it doesn't take ownership of it.
Chris Lattner168ae2d2007-10-17 20:41:00 +0000114Lexer::Lexer(SourceLocation fileloc, const LangOptions &features,
Chris Lattnerde96c0f2009-01-17 07:42:27 +0000115 const char *BufStart, const char *BufPtr, const char *BufEnd)
Chris Lattnerc6fe32a2009-01-17 03:48:08 +0000116 : FileLoc(fileloc), Features(features) {
Chris Lattner22d91ca2009-01-17 06:55:17 +0000117
Chris Lattner22d91ca2009-01-17 06:55:17 +0000118 InitLexer(BufStart, BufPtr, BufEnd);
Chris Lattner168ae2d2007-10-17 20:41:00 +0000119
120 // We *are* in raw mode.
121 LexingRawMode = true;
Chris Lattner168ae2d2007-10-17 20:41:00 +0000122}
123
Chris Lattner025c3a62009-01-17 07:35:14 +0000124/// Lexer constructor - Create a new raw lexer object. This object is only
125/// suitable for calls to 'LexRawToken'. This lexer assumes that the text
126/// range will outlive it, so it doesn't take ownership of it.
127Lexer::Lexer(FileID FID, const SourceManager &SM, const LangOptions &features)
128 : FileLoc(SM.getLocForStartOfFile(FID)), Features(features) {
129 const llvm::MemoryBuffer *FromFile = SM.getBuffer(FID);
130
131 InitLexer(FromFile->getBufferStart(), FromFile->getBufferStart(),
132 FromFile->getBufferEnd());
133
134 // We *are* in raw mode.
135 LexingRawMode = true;
136}
137
Chris Lattner42e00d12009-01-17 08:27:52 +0000138/// Create_PragmaLexer: Lexer constructor - Create a new lexer object for
139/// _Pragma expansion. This has a variety of magic semantics that this method
140/// sets up. It returns a new'd Lexer that must be delete'd when done.
141///
142/// On entrance to this routine, TokStartLoc is a macro location which has a
143/// spelling loc that indicates the bytes to be lexed for the token and an
144/// instantiation location that indicates where all lexed tokens should be
145/// "expanded from".
146///
147/// FIXME: It would really be nice to make _Pragma just be a wrapper around a
148/// normal lexer that remaps tokens as they fly by. This would require making
149/// Preprocessor::Lex virtual. Given that, we could just dump in a magic lexer
150/// interface that could handle this stuff. This would pull GetMappedTokenLoc
151/// out of the critical path of the lexer!
152///
Chris Lattnerbcc2a672009-01-19 06:46:35 +0000153Lexer *Lexer::Create_PragmaLexer(SourceLocation SpellingLoc,
Chris Lattnere7fb4842009-02-15 20:52:18 +0000154 SourceLocation InstantiationLocStart,
155 SourceLocation InstantiationLocEnd,
Chris Lattnerbcc2a672009-01-19 06:46:35 +0000156 unsigned TokLen, Preprocessor &PP) {
Chris Lattner42e00d12009-01-17 08:27:52 +0000157 SourceManager &SM = PP.getSourceManager();
Chris Lattner42e00d12009-01-17 08:27:52 +0000158
159 // Create the lexer as if we were going to lex the file normally.
Chris Lattnera11d6172009-01-19 07:46:45 +0000160 FileID SpellingFID = SM.getFileID(SpellingLoc);
Chris Lattnerbcc2a672009-01-19 06:46:35 +0000161 Lexer *L = new Lexer(SpellingFID, PP);
Chris Lattner42e00d12009-01-17 08:27:52 +0000162
163 // Now that the lexer is created, change the start/end locations so that we
164 // just lex the subsection of the file that we want. This is lexing from a
165 // scratch buffer.
166 const char *StrData = SM.getCharacterData(SpellingLoc);
167
168 L->BufferPtr = StrData;
169 L->BufferEnd = StrData+TokLen;
Chris Lattner1fa49532009-03-08 08:08:45 +0000170 assert(L->BufferEnd[0] == 0 && "Buffer is not nul terminated!");
Chris Lattner42e00d12009-01-17 08:27:52 +0000171
172 // Set the SourceLocation with the remapping information. This ensures that
173 // GetMappedTokenLoc will remap the tokens as they are lexed.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000174 L->FileLoc = SM.createInstantiationLoc(SM.getLocForStartOfFile(SpellingFID),
Chris Lattnere7fb4842009-02-15 20:52:18 +0000175 InstantiationLocStart,
176 InstantiationLocEnd, TokLen);
Chris Lattner42e00d12009-01-17 08:27:52 +0000177
178 // Ensure that the lexer thinks it is inside a directive, so that end \n will
179 // return an EOM token.
180 L->ParsingPreprocessorDirective = true;
181
182 // This lexer really is for _Pragma.
183 L->Is_PragmaLexer = true;
184 return L;
185}
186
Chris Lattner168ae2d2007-10-17 20:41:00 +0000187
Reid Spencer5f016e22007-07-11 17:01:13 +0000188/// Stringify - Convert the specified string into a C string, with surrounding
189/// ""'s, and with escaped \ and " characters.
190std::string Lexer::Stringify(const std::string &Str, bool Charify) {
191 std::string Result = Str;
192 char Quote = Charify ? '\'' : '"';
193 for (unsigned i = 0, e = Result.size(); i != e; ++i) {
194 if (Result[i] == '\\' || Result[i] == Quote) {
195 Result.insert(Result.begin()+i, '\\');
196 ++i; ++e;
197 }
198 }
199 return Result;
200}
201
Chris Lattnerd8e30832007-07-24 06:57:14 +0000202/// Stringify - Convert the specified string into a C string by escaping '\'
203/// and " characters. This does not add surrounding ""'s to the string.
204void Lexer::Stringify(llvm::SmallVectorImpl<char> &Str) {
205 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
206 if (Str[i] == '\\' || Str[i] == '"') {
207 Str.insert(Str.begin()+i, '\\');
208 ++i; ++e;
209 }
210 }
211}
212
Reid Spencer5f016e22007-07-11 17:01:13 +0000213
Chris Lattner9a611942007-10-17 21:18:47 +0000214/// MeasureTokenLength - Relex the token at the specified location and return
215/// its length in bytes in the input file. If the token needs cleaning (e.g.
216/// includes a trigraph or an escaped newline) then this count includes bytes
217/// that are part of that.
218unsigned Lexer::MeasureTokenLength(SourceLocation Loc,
Chris Lattner2c78b872009-04-14 23:22:57 +0000219 const SourceManager &SM,
220 const LangOptions &LangOpts) {
Chris Lattner9a611942007-10-17 21:18:47 +0000221 // TODO: this could be special cased for common tokens like identifiers, ')',
222 // etc to make this faster, if it mattered. Just look at StrData[0] to handle
223 // all obviously single-char tokens. This could use
224 // Lexer::isObviouslySimpleCharacter for example to handle identifiers or
225 // something.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000226
227 // If this comes from a macro expansion, we really do want the macro name, not
228 // the token this macro expanded to.
Chris Lattner363fdc22009-01-26 22:24:27 +0000229 Loc = SM.getInstantiationLoc(Loc);
230 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
Chris Lattner83503942009-01-17 08:30:10 +0000231 std::pair<const char *,const char *> Buffer = SM.getBufferData(LocInfo.first);
232 const char *StrData = Buffer.first+LocInfo.second;
233
Chris Lattner9a611942007-10-17 21:18:47 +0000234 // Create a lexer starting at the beginning of this token.
Chris Lattnerde96c0f2009-01-17 07:42:27 +0000235 Lexer TheLexer(Loc, LangOpts, Buffer.first, StrData, Buffer.second);
Chris Lattner9a611942007-10-17 21:18:47 +0000236 Token TheTok;
Chris Lattner590f0cc2008-10-12 01:15:46 +0000237 TheLexer.LexFromRawLexer(TheTok);
Chris Lattner9a611942007-10-17 21:18:47 +0000238 return TheTok.getLength();
239}
240
Reid Spencer5f016e22007-07-11 17:01:13 +0000241//===----------------------------------------------------------------------===//
242// Character information.
243//===----------------------------------------------------------------------===//
244
245static unsigned char CharInfo[256];
246
247enum {
248 CHAR_HORZ_WS = 0x01, // ' ', '\t', '\f', '\v'. Note, no '\0'
249 CHAR_VERT_WS = 0x02, // '\r', '\n'
250 CHAR_LETTER = 0x04, // a-z,A-Z
251 CHAR_NUMBER = 0x08, // 0-9
252 CHAR_UNDER = 0x10, // _
253 CHAR_PERIOD = 0x20 // .
254};
255
256static void InitCharacterInfo() {
257 static bool isInited = false;
258 if (isInited) return;
259 isInited = true;
260
261 // Intiialize the CharInfo table.
262 // TODO: statically initialize this.
263 CharInfo[(int)' '] = CharInfo[(int)'\t'] =
264 CharInfo[(int)'\f'] = CharInfo[(int)'\v'] = CHAR_HORZ_WS;
265 CharInfo[(int)'\n'] = CharInfo[(int)'\r'] = CHAR_VERT_WS;
266
267 CharInfo[(int)'_'] = CHAR_UNDER;
268 CharInfo[(int)'.'] = CHAR_PERIOD;
269 for (unsigned i = 'a'; i <= 'z'; ++i)
270 CharInfo[i] = CharInfo[i+'A'-'a'] = CHAR_LETTER;
271 for (unsigned i = '0'; i <= '9'; ++i)
272 CharInfo[i] = CHAR_NUMBER;
273}
274
275/// isIdentifierBody - Return true if this is the body character of an
276/// identifier, which is [a-zA-Z0-9_].
277static inline bool isIdentifierBody(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000278 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER)) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000279}
280
281/// isHorizontalWhitespace - Return true if this character is horizontal
282/// whitespace: ' ', '\t', '\f', '\v'. Note that this returns false for '\0'.
283static inline bool isHorizontalWhitespace(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000284 return (CharInfo[c] & CHAR_HORZ_WS) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000285}
286
287/// isWhitespace - Return true if this character is horizontal or vertical
288/// whitespace: ' ', '\t', '\f', '\v', '\n', '\r'. Note that this returns false
289/// for '\0'.
290static inline bool isWhitespace(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000291 return (CharInfo[c] & (CHAR_HORZ_WS|CHAR_VERT_WS)) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000292}
293
294/// isNumberBody - Return true if this is the body character of an
295/// preprocessing number, which is [a-zA-Z0-9_.].
296static inline bool isNumberBody(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000297 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER|CHAR_PERIOD)) ?
298 true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000299}
300
301
302//===----------------------------------------------------------------------===//
303// Diagnostics forwarding code.
304//===----------------------------------------------------------------------===//
305
Chris Lattner409a0362007-07-22 18:38:25 +0000306/// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
307/// lexer buffer was all instantiated at a single point, perform the mapping.
308/// This is currently only used for _Pragma implementation, so it is the slow
309/// path of the hot getSourceLocation method. Do not allow it to be inlined.
310static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
311 SourceLocation FileLoc,
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000312 unsigned CharNo,
313 unsigned TokLen) DISABLE_INLINE;
Chris Lattner409a0362007-07-22 18:38:25 +0000314static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
315 SourceLocation FileLoc,
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000316 unsigned CharNo, unsigned TokLen) {
Chris Lattnere7fb4842009-02-15 20:52:18 +0000317 assert(FileLoc.isMacroID() && "Must be an instantiation");
318
Chris Lattner409a0362007-07-22 18:38:25 +0000319 // Otherwise, we're lexing "mapped tokens". This is used for things like
320 // _Pragma handling. Combine the instantiation location of FileLoc with the
Chris Lattnerdf7c17a2009-01-16 07:00:02 +0000321 // spelling location.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000322 SourceManager &SM = PP.getSourceManager();
Chris Lattner409a0362007-07-22 18:38:25 +0000323
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000324 // Create a new SLoc which is expanded from Instantiation(FileLoc) but whose
Chris Lattnerdf7c17a2009-01-16 07:00:02 +0000325 // characters come from spelling(FileLoc)+Offset.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000326 SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc);
Chris Lattnerbcc2a672009-01-19 06:46:35 +0000327 SpellingLoc = SpellingLoc.getFileLocWithOffset(CharNo);
Chris Lattnere7fb4842009-02-15 20:52:18 +0000328
329 // Figure out the expansion loc range, which is the range covered by the
330 // original _Pragma(...) sequence.
331 std::pair<SourceLocation,SourceLocation> II =
332 SM.getImmediateInstantiationRange(FileLoc);
333
334 return SM.createInstantiationLoc(SpellingLoc, II.first, II.second, TokLen);
Chris Lattner409a0362007-07-22 18:38:25 +0000335}
336
Reid Spencer5f016e22007-07-11 17:01:13 +0000337/// getSourceLocation - Return a source location identifier for the specified
338/// offset in the current file.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000339SourceLocation Lexer::getSourceLocation(const char *Loc,
340 unsigned TokLen) const {
Chris Lattner448cec42007-07-22 18:44:36 +0000341 assert(Loc >= BufferStart && Loc <= BufferEnd &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000342 "Location out of range for this buffer!");
Chris Lattner9dc1f532007-07-20 16:37:10 +0000343
344 // In the normal case, we're just lexing from a simple file buffer, return
345 // the file id from FileLoc with the offset specified.
Chris Lattner448cec42007-07-22 18:44:36 +0000346 unsigned CharNo = Loc-BufferStart;
Chris Lattner9dc1f532007-07-20 16:37:10 +0000347 if (FileLoc.isFileID())
Chris Lattnerbcc2a672009-01-19 06:46:35 +0000348 return FileLoc.getFileLocWithOffset(CharNo);
Chris Lattner9dc1f532007-07-20 16:37:10 +0000349
Chris Lattner2b2453a2009-01-17 06:22:33 +0000350 // Otherwise, this is the _Pragma lexer case, which pretends that all of the
351 // tokens are lexed from where the _Pragma was defined.
Chris Lattner168ae2d2007-10-17 20:41:00 +0000352 assert(PP && "This doesn't work on raw lexers");
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000353 return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen);
Reid Spencer5f016e22007-07-11 17:01:13 +0000354}
355
Reid Spencer5f016e22007-07-11 17:01:13 +0000356/// Diag - Forwarding function for diagnostics. This translate a source
357/// position in the current buffer into a SourceLocation object for rendering.
Chris Lattner3cbfe2c2008-11-22 00:59:29 +0000358DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
Chris Lattner3692b092008-11-18 07:59:24 +0000359 return PP->Diag(getSourceLocation(Loc), DiagID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000360}
Reid Spencer5f016e22007-07-11 17:01:13 +0000361
362//===----------------------------------------------------------------------===//
363// Trigraph and Escaped Newline Handling Code.
364//===----------------------------------------------------------------------===//
365
366/// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
367/// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
368static char GetTrigraphCharForLetter(char Letter) {
369 switch (Letter) {
370 default: return 0;
371 case '=': return '#';
372 case ')': return ']';
373 case '(': return '[';
374 case '!': return '|';
375 case '\'': return '^';
376 case '>': return '}';
377 case '/': return '\\';
378 case '<': return '{';
379 case '-': return '~';
380 }
381}
382
383/// DecodeTrigraphChar - If the specified character is a legal trigraph when
384/// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
385/// return the result character. Finally, emit a warning about trigraph use
386/// whether trigraphs are enabled or not.
387static char DecodeTrigraphChar(const char *CP, Lexer *L) {
388 char Res = GetTrigraphCharForLetter(*CP);
Chris Lattner3692b092008-11-18 07:59:24 +0000389 if (!Res || !L) return Res;
390
391 if (!L->getFeatures().Trigraphs) {
Chris Lattner74d15df2008-11-22 02:02:22 +0000392 if (!L->isLexingRawMode())
393 L->Diag(CP-2, diag::trigraph_ignored);
Chris Lattner3692b092008-11-18 07:59:24 +0000394 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000395 }
Chris Lattner3692b092008-11-18 07:59:24 +0000396
Chris Lattner74d15df2008-11-22 02:02:22 +0000397 if (!L->isLexingRawMode())
398 L->Diag(CP-2, diag::trigraph_converted) << std::string()+Res;
Reid Spencer5f016e22007-07-11 17:01:13 +0000399 return Res;
400}
401
Chris Lattner24f0e482009-04-18 22:05:41 +0000402/// getEscapedNewLineSize - Return the size of the specified escaped newline,
403/// or 0 if it is not an escaped newline. P[-1] is known to be a "\" or a
404/// trigraph equivalent on entry to this function.
405unsigned Lexer::getEscapedNewLineSize(const char *Ptr) {
406 unsigned Size = 0;
407 while (isWhitespace(Ptr[Size])) {
408 ++Size;
409
410 if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r')
411 continue;
412
413 // If this is a \r\n or \n\r, skip the other half.
414 if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') &&
415 Ptr[Size-1] != Ptr[Size])
416 ++Size;
417
418 return Size;
419 }
420
421 // Not an escaped newline, must be a \t or something else.
422 return 0;
423}
424
Chris Lattner03374952009-04-18 22:27:02 +0000425/// SkipEscapedNewLines - If P points to an escaped newline (or a series of
426/// them), skip over them and return the first non-escaped-newline found,
427/// otherwise return P.
428const char *Lexer::SkipEscapedNewLines(const char *P) {
429 while (1) {
430 const char *AfterEscape;
431 if (*P == '\\') {
432 AfterEscape = P+1;
433 } else if (*P == '?') {
434 // If not a trigraph for escape, bail out.
435 if (P[1] != '?' || P[2] != '/')
436 return P;
437 AfterEscape = P+3;
438 } else {
439 return P;
440 }
441
442 unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape);
443 if (NewLineSize == 0) return P;
444 P = AfterEscape+NewLineSize;
445 }
446}
447
Chris Lattner24f0e482009-04-18 22:05:41 +0000448
Reid Spencer5f016e22007-07-11 17:01:13 +0000449/// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
450/// get its size, and return it. This is tricky in several cases:
451/// 1. If currently at the start of a trigraph, we warn about the trigraph,
452/// then either return the trigraph (skipping 3 chars) or the '?',
453/// depending on whether trigraphs are enabled or not.
454/// 2. If this is an escaped newline (potentially with whitespace between
455/// the backslash and newline), implicitly skip the newline and return
456/// the char after it.
457/// 3. If this is a UCN, return it. FIXME: C++ UCN's?
458///
459/// This handles the slow/uncommon case of the getCharAndSize method. Here we
460/// know that we can accumulate into Size, and that we have already incremented
461/// Ptr by Size bytes.
462///
463/// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
464/// be updated to match.
465///
466char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
Chris Lattnerd2177732007-07-20 16:59:19 +0000467 Token *Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000468 // If we have a slash, look for an escaped newline.
469 if (Ptr[0] == '\\') {
470 ++Size;
471 ++Ptr;
472Slash:
473 // Common case, backslash-char where the char is not whitespace.
474 if (!isWhitespace(Ptr[0])) return '\\';
475
476 // See if we have optional whitespace characters followed by a newline.
Chris Lattner24f0e482009-04-18 22:05:41 +0000477 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
478 // Remember that this token needs to be cleaned.
479 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +0000480
Chris Lattner24f0e482009-04-18 22:05:41 +0000481 // Warn if there was whitespace between the backslash and newline.
482 if (EscapedNewLineSize != 1 && Tok && !isLexingRawMode())
483 Diag(Ptr, diag::backslash_newline_space);
Chris Lattner0edfab62009-04-18 21:57:20 +0000484
Chris Lattner24f0e482009-04-18 22:05:41 +0000485 // Found backslash<whitespace><newline>. Parse the char after it.
486 Size += EscapedNewLineSize;
487 Ptr += EscapedNewLineSize;
488 // Use slow version to accumulate a correct size field.
489 return getCharAndSizeSlow(Ptr, Size, Tok);
490 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000491
492 // Otherwise, this is not an escaped newline, just return the slash.
493 return '\\';
494 }
495
496 // If this is a trigraph, process it.
497 if (Ptr[0] == '?' && Ptr[1] == '?') {
498 // If this is actually a legal trigraph (not something like "??x"), emit
499 // a trigraph warning. If so, and if trigraphs are enabled, return it.
500 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : 0)) {
501 // Remember that this token needs to be cleaned.
Chris Lattnerd2177732007-07-20 16:59:19 +0000502 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +0000503
504 Ptr += 3;
505 Size += 3;
506 if (C == '\\') goto Slash;
507 return C;
508 }
509 }
510
511 // If this is neither, return a single character.
512 ++Size;
513 return *Ptr;
514}
515
516
517/// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
518/// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
519/// and that we have already incremented Ptr by Size bytes.
520///
521/// NOTE: When this method is updated, getCharAndSizeSlow (above) should
522/// be updated to match.
523char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
524 const LangOptions &Features) {
525 // If we have a slash, look for an escaped newline.
526 if (Ptr[0] == '\\') {
527 ++Size;
528 ++Ptr;
529Slash:
530 // Common case, backslash-char where the char is not whitespace.
531 if (!isWhitespace(Ptr[0])) return '\\';
532
533 // See if we have optional whitespace characters followed by a newline.
Chris Lattner24f0e482009-04-18 22:05:41 +0000534 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
535 // Found backslash<whitespace><newline>. Parse the char after it.
536 Size += EscapedNewLineSize;
537 Ptr += EscapedNewLineSize;
538
539 // Use slow version to accumulate a correct size field.
540 return getCharAndSizeSlowNoWarn(Ptr, Size, Features);
541 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000542
543 // Otherwise, this is not an escaped newline, just return the slash.
544 return '\\';
545 }
546
547 // If this is a trigraph, process it.
548 if (Features.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
549 // If this is actually a legal trigraph (not something like "??x"), return
550 // it.
551 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
552 Ptr += 3;
553 Size += 3;
554 if (C == '\\') goto Slash;
555 return C;
556 }
557 }
558
559 // If this is neither, return a single character.
560 ++Size;
561 return *Ptr;
562}
563
564//===----------------------------------------------------------------------===//
565// Helper methods for lexing.
566//===----------------------------------------------------------------------===//
567
Chris Lattnerd2177732007-07-20 16:59:19 +0000568void Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000569 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
570 unsigned Size;
571 unsigned char C = *CurPtr++;
572 while (isIdentifierBody(C)) {
573 C = *CurPtr++;
574 }
575 --CurPtr; // Back up over the skipped character.
576
577 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
578 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
579 // FIXME: UCNs.
580 if (C != '\\' && C != '?' && (C != '$' || !Features.DollarIdents)) {
581FinishIdentifier:
582 const char *IdStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +0000583 FormTokenWithChars(Result, CurPtr, tok::identifier);
Reid Spencer5f016e22007-07-11 17:01:13 +0000584
585 // If we are in raw mode, return this identifier raw. There is no need to
586 // look up identifier information or attempt to macro expand it.
587 if (LexingRawMode) return;
588
589 // Fill in Result.IdentifierInfo, looking up the identifier in the
590 // identifier table.
Chris Lattnerd1186fa2009-01-21 07:45:14 +0000591 IdentifierInfo *II = PP->LookUpIdentifierInfo(Result, IdStart);
Reid Spencer5f016e22007-07-11 17:01:13 +0000592
Chris Lattner863c4862009-01-23 18:35:48 +0000593 // Change the kind of this identifier to the appropriate token kind, e.g.
594 // turning "for" into a keyword.
595 Result.setKind(II->getTokenID());
596
Reid Spencer5f016e22007-07-11 17:01:13 +0000597 // Finally, now that we know we have an identifier, pass this off to the
598 // preprocessor, which may macro expand it or something.
Chris Lattnerd1186fa2009-01-21 07:45:14 +0000599 if (II->isHandleIdentifierCase())
Chris Lattner6a170eb2009-01-21 07:43:11 +0000600 PP->HandleIdentifier(Result);
601 return;
Reid Spencer5f016e22007-07-11 17:01:13 +0000602 }
603
604 // Otherwise, $,\,? in identifier found. Enter slower path.
605
606 C = getCharAndSize(CurPtr, Size);
607 while (1) {
608 if (C == '$') {
609 // If we hit a $ and they are not supported in identifiers, we are done.
610 if (!Features.DollarIdents) goto FinishIdentifier;
611
612 // Otherwise, emit a diagnostic and continue.
Chris Lattner74d15df2008-11-22 02:02:22 +0000613 if (!isLexingRawMode())
614 Diag(CurPtr, diag::ext_dollar_in_identifier);
Reid Spencer5f016e22007-07-11 17:01:13 +0000615 CurPtr = ConsumeChar(CurPtr, Size, Result);
616 C = getCharAndSize(CurPtr, Size);
617 continue;
618 } else if (!isIdentifierBody(C)) { // FIXME: UCNs.
619 // Found end of identifier.
620 goto FinishIdentifier;
621 }
622
623 // Otherwise, this character is good, consume it.
624 CurPtr = ConsumeChar(CurPtr, Size, Result);
625
626 C = getCharAndSize(CurPtr, Size);
627 while (isIdentifierBody(C)) { // FIXME: UCNs.
628 CurPtr = ConsumeChar(CurPtr, Size, Result);
629 C = getCharAndSize(CurPtr, Size);
630 }
631 }
632}
633
634
Nate Begeman5253c7f2008-04-14 02:26:39 +0000635/// LexNumericConstant - Lex the remainder of a integer or floating point
Reid Spencer5f016e22007-07-11 17:01:13 +0000636/// constant. From[-1] is the first character lexed. Return the end of the
637/// constant.
Chris Lattnerd2177732007-07-20 16:59:19 +0000638void Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000639 unsigned Size;
640 char C = getCharAndSize(CurPtr, Size);
641 char PrevCh = 0;
642 while (isNumberBody(C)) { // FIXME: UCNs?
643 CurPtr = ConsumeChar(CurPtr, Size, Result);
644 PrevCh = C;
645 C = getCharAndSize(CurPtr, Size);
646 }
647
648 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
649 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e'))
650 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
651
652 // If we have a hex FP constant, continue.
Chris Lattner49842122008-11-22 07:39:03 +0000653 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p') &&
654 (Features.HexFloats || !Features.NoExtensions))
Reid Spencer5f016e22007-07-11 17:01:13 +0000655 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
656
Reid Spencer5f016e22007-07-11 17:01:13 +0000657 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +0000658 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +0000659 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
Chris Lattner47246be2009-01-26 19:29:26 +0000660 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +0000661}
662
663/// LexStringLiteral - Lex the remainder of a string literal, after having lexed
664/// either " or L".
Chris Lattnerd88dc482008-10-12 04:05:48 +0000665void Lexer::LexStringLiteral(Token &Result, const char *CurPtr, bool Wide) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000666 const char *NulCharacter = 0; // Does this string contain the \0 character?
667
668 char C = getAndAdvanceChar(CurPtr, Result);
669 while (C != '"') {
670 // Skip escaped characters.
671 if (C == '\\') {
672 // Skip the escaped character.
673 C = getAndAdvanceChar(CurPtr, Result);
674 } else if (C == '\n' || C == '\r' || // Newline.
675 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Chris Lattner33ab3f62009-03-18 21:10:12 +0000676 if (!isLexingRawMode() && !Features.AsmPreprocessor)
Chris Lattner74d15df2008-11-22 02:02:22 +0000677 Diag(BufferPtr, diag::err_unterminated_string);
Chris Lattner9e6293d2008-10-12 04:51:35 +0000678 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Reid Spencer5f016e22007-07-11 17:01:13 +0000679 return;
680 } else if (C == 0) {
681 NulCharacter = CurPtr-1;
682 }
683 C = getAndAdvanceChar(CurPtr, Result);
684 }
685
686 // If a nul character existed in the string, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +0000687 if (NulCharacter && !isLexingRawMode())
688 Diag(NulCharacter, diag::null_in_string);
Reid Spencer5f016e22007-07-11 17:01:13 +0000689
Reid Spencer5f016e22007-07-11 17:01:13 +0000690 // Update the location of the token as well as the BufferPtr instance var.
Chris Lattner47246be2009-01-26 19:29:26 +0000691 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +0000692 FormTokenWithChars(Result, CurPtr,
693 Wide ? tok::wide_string_literal : tok::string_literal);
Chris Lattner47246be2009-01-26 19:29:26 +0000694 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +0000695}
696
697/// LexAngledStringLiteral - Lex the remainder of an angled string literal,
698/// after having lexed the '<' character. This is used for #include filenames.
Chris Lattnerd2177732007-07-20 16:59:19 +0000699void Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000700 const char *NulCharacter = 0; // Does this string contain the \0 character?
Chris Lattner9cb51ce2009-04-17 23:56:52 +0000701 const char *AfterLessPos = CurPtr;
Reid Spencer5f016e22007-07-11 17:01:13 +0000702 char C = getAndAdvanceChar(CurPtr, Result);
703 while (C != '>') {
704 // Skip escaped characters.
705 if (C == '\\') {
706 // Skip the escaped character.
707 C = getAndAdvanceChar(CurPtr, Result);
708 } else if (C == '\n' || C == '\r' || // Newline.
709 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Chris Lattner9cb51ce2009-04-17 23:56:52 +0000710 // If the filename is unterminated, then it must just be a lone <
711 // character. Return this as such.
712 FormTokenWithChars(Result, AfterLessPos, tok::less);
Reid Spencer5f016e22007-07-11 17:01:13 +0000713 return;
714 } else if (C == 0) {
715 NulCharacter = CurPtr-1;
716 }
717 C = getAndAdvanceChar(CurPtr, Result);
718 }
719
720 // If a nul character existed in the string, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +0000721 if (NulCharacter && !isLexingRawMode())
722 Diag(NulCharacter, diag::null_in_string);
Reid Spencer5f016e22007-07-11 17:01:13 +0000723
Reid Spencer5f016e22007-07-11 17:01:13 +0000724 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +0000725 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +0000726 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
Chris Lattner47246be2009-01-26 19:29:26 +0000727 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +0000728}
729
730
731/// LexCharConstant - Lex the remainder of a character constant, after having
732/// lexed either ' or L'.
Chris Lattnerd2177732007-07-20 16:59:19 +0000733void Lexer::LexCharConstant(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000734 const char *NulCharacter = 0; // Does this character contain the \0 character?
735
736 // Handle the common case of 'x' and '\y' efficiently.
737 char C = getAndAdvanceChar(CurPtr, Result);
738 if (C == '\'') {
Chris Lattner33ab3f62009-03-18 21:10:12 +0000739 if (!isLexingRawMode() && !Features.AsmPreprocessor)
Chris Lattner74d15df2008-11-22 02:02:22 +0000740 Diag(BufferPtr, diag::err_empty_character);
Chris Lattner9e6293d2008-10-12 04:51:35 +0000741 FormTokenWithChars(Result, CurPtr, tok::unknown);
Reid Spencer5f016e22007-07-11 17:01:13 +0000742 return;
743 } else if (C == '\\') {
744 // Skip the escaped character.
745 // FIXME: UCN's.
746 C = getAndAdvanceChar(CurPtr, Result);
747 }
748
749 if (C && C != '\n' && C != '\r' && CurPtr[0] == '\'') {
750 ++CurPtr;
751 } else {
752 // Fall back on generic code for embedded nulls, newlines, wide chars.
753 do {
754 // Skip escaped characters.
755 if (C == '\\') {
756 // Skip the escaped character.
757 C = getAndAdvanceChar(CurPtr, Result);
758 } else if (C == '\n' || C == '\r' || // Newline.
759 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Chris Lattner33ab3f62009-03-18 21:10:12 +0000760 if (!isLexingRawMode() && !Features.AsmPreprocessor)
Chris Lattner74d15df2008-11-22 02:02:22 +0000761 Diag(BufferPtr, diag::err_unterminated_char);
Chris Lattner9e6293d2008-10-12 04:51:35 +0000762 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Reid Spencer5f016e22007-07-11 17:01:13 +0000763 return;
764 } else if (C == 0) {
765 NulCharacter = CurPtr-1;
766 }
767 C = getAndAdvanceChar(CurPtr, Result);
768 } while (C != '\'');
769 }
770
Chris Lattner74d15df2008-11-22 02:02:22 +0000771 if (NulCharacter && !isLexingRawMode())
772 Diag(NulCharacter, diag::null_in_char);
Reid Spencer5f016e22007-07-11 17:01:13 +0000773
Reid Spencer5f016e22007-07-11 17:01:13 +0000774 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +0000775 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +0000776 FormTokenWithChars(Result, CurPtr, tok::char_constant);
Chris Lattner47246be2009-01-26 19:29:26 +0000777 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +0000778}
779
780/// SkipWhitespace - Efficiently skip over a series of whitespace characters.
781/// Update BufferPtr to point to the next non-whitespace character and return.
Chris Lattnerd88dc482008-10-12 04:05:48 +0000782///
783/// This method forms a token and returns true if KeepWhitespaceMode is enabled.
784///
785bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000786 // Whitespace - Skip it, then return the token after the whitespace.
787 unsigned char Char = *CurPtr; // Skip consequtive spaces efficiently.
788 while (1) {
789 // Skip horizontal whitespace very aggressively.
790 while (isHorizontalWhitespace(Char))
791 Char = *++CurPtr;
792
Daniel Dunbarddd3e8b2008-11-25 00:20:22 +0000793 // Otherwise if we have something other than whitespace, we're done.
Reid Spencer5f016e22007-07-11 17:01:13 +0000794 if (Char != '\n' && Char != '\r')
795 break;
796
797 if (ParsingPreprocessorDirective) {
798 // End of preprocessor directive line, let LexTokenInternal handle this.
799 BufferPtr = CurPtr;
Chris Lattnerd88dc482008-10-12 04:05:48 +0000800 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000801 }
802
803 // ok, but handle newline.
804 // The returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +0000805 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +0000806 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +0000807 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +0000808 Char = *++CurPtr;
809 }
810
811 // If this isn't immediately after a newline, there is leading space.
812 char PrevChar = CurPtr[-1];
813 if (PrevChar != '\n' && PrevChar != '\r')
Chris Lattnerd2177732007-07-20 16:59:19 +0000814 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +0000815
Chris Lattnerd88dc482008-10-12 04:05:48 +0000816 // If the client wants us to return whitespace, return it now.
817 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +0000818 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd88dc482008-10-12 04:05:48 +0000819 return true;
820 }
821
Reid Spencer5f016e22007-07-11 17:01:13 +0000822 BufferPtr = CurPtr;
Chris Lattnerd88dc482008-10-12 04:05:48 +0000823 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000824}
825
826// SkipBCPLComment - We have just read the // characters from input. Skip until
827// we find the newline character thats terminate the comment. Then update
Chris Lattner2d381892008-10-12 04:15:42 +0000828/// BufferPtr and return. If we're in KeepCommentMode, this will form the token
829/// and return true.
Chris Lattnerd2177732007-07-20 16:59:19 +0000830bool Lexer::SkipBCPLComment(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000831 // If BCPL comments aren't explicitly enabled for this language, emit an
832 // extension warning.
Chris Lattner74d15df2008-11-22 02:02:22 +0000833 if (!Features.BCPLComment && !isLexingRawMode()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000834 Diag(BufferPtr, diag::ext_bcpl_comment);
835
836 // Mark them enabled so we only emit one warning for this translation
837 // unit.
838 Features.BCPLComment = true;
839 }
840
841 // Scan over the body of the comment. The common case, when scanning, is that
842 // the comment contains normal ascii characters with nothing interesting in
843 // them. As such, optimize for this case with the inner loop.
844 char C;
845 do {
846 C = *CurPtr;
847 // FIXME: Speedup BCPL comment lexing. Just scan for a \n or \r character.
848 // If we find a \n character, scan backwards, checking to see if it's an
849 // escaped newline, like we do for block comments.
850
851 // Skip over characters in the fast loop.
852 while (C != 0 && // Potentially EOF.
853 C != '\\' && // Potentially escaped newline.
854 C != '?' && // Potentially trigraph.
855 C != '\n' && C != '\r') // Newline or DOS-style newline.
856 C = *++CurPtr;
857
858 // If this is a newline, we're done.
859 if (C == '\n' || C == '\r')
860 break; // Found the newline? Break out!
861
862 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
Chris Lattnerbc3e9842008-12-12 07:34:39 +0000863 // properly decode the character. Read it in raw mode to avoid emitting
864 // diagnostics about things like trigraphs. If we see an escaped newline,
865 // we'll handle it below.
Reid Spencer5f016e22007-07-11 17:01:13 +0000866 const char *OldPtr = CurPtr;
Chris Lattnerbc3e9842008-12-12 07:34:39 +0000867 bool OldRawMode = isLexingRawMode();
868 LexingRawMode = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000869 C = getAndAdvanceChar(CurPtr, Result);
Chris Lattnerbc3e9842008-12-12 07:34:39 +0000870 LexingRawMode = OldRawMode;
Chris Lattneread616c2009-04-05 00:26:41 +0000871
872 // If the char that we finally got was a \n, then we must have had something
873 // like \<newline><newline>. We don't want to have consumed the second
874 // newline, we want CurPtr, to end up pointing to it down below.
875 if (C == '\n' || C == '\r') {
876 --CurPtr;
877 C = 'x'; // doesn't matter what this is.
878 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000879
880 // If we read multiple characters, and one of those characters was a \r or
881 // \n, then we had an escaped newline within the comment. Emit diagnostic
882 // unless the next line is also a // comment.
883 if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') {
884 for (; OldPtr != CurPtr; ++OldPtr)
885 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
886 // Okay, we found a // comment that ends in a newline, if the next
887 // line is also a // comment, but has spaces, don't emit a diagnostic.
888 if (isspace(C)) {
889 const char *ForwardPtr = CurPtr;
890 while (isspace(*ForwardPtr)) // Skip whitespace.
891 ++ForwardPtr;
892 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
893 break;
894 }
895
Chris Lattner74d15df2008-11-22 02:02:22 +0000896 if (!isLexingRawMode())
897 Diag(OldPtr-1, diag::ext_multi_line_bcpl_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +0000898 break;
899 }
900 }
901
902 if (CurPtr == BufferEnd+1) { --CurPtr; break; }
903 } while (C != '\n' && C != '\r');
904
905 // Found but did not consume the newline.
906
907 // If we are returning comments as tokens, return this comment as a token.
Chris Lattnerfa95a012008-10-12 03:22:02 +0000908 if (inKeepCommentMode())
Reid Spencer5f016e22007-07-11 17:01:13 +0000909 return SaveBCPLComment(Result, CurPtr);
910
911 // If we are inside a preprocessor directive and we see the end of line,
912 // return immediately, so that the lexer can return this as an EOM token.
913 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
914 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +0000915 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000916 }
917
918 // Otherwise, eat the \n character. We don't care if this is a \n\r or
Chris Lattner7a4f0042008-10-12 00:23:07 +0000919 // \r\n sequence. This is an efficiency hack (because we know the \n can't
Chris Lattnerd88dc482008-10-12 04:05:48 +0000920 // contribute to another token), it isn't needed for correctness. Note that
921 // this is ok even in KeepWhitespaceMode, because we would have returned the
922 /// comment above in that mode.
Reid Spencer5f016e22007-07-11 17:01:13 +0000923 ++CurPtr;
924
925 // The next returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +0000926 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +0000927 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +0000928 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +0000929 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +0000930 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000931}
932
933/// SaveBCPLComment - If in save-comment mode, package up this BCPL comment in
934/// an appropriate way and return it.
Chris Lattnerd2177732007-07-20 16:59:19 +0000935bool Lexer::SaveBCPLComment(Token &Result, const char *CurPtr) {
Chris Lattner9e6293d2008-10-12 04:51:35 +0000936 // If we're not in a preprocessor directive, just return the // comment
937 // directly.
938 FormTokenWithChars(Result, CurPtr, tok::comment);
Reid Spencer5f016e22007-07-11 17:01:13 +0000939
Chris Lattner9e6293d2008-10-12 04:51:35 +0000940 if (!ParsingPreprocessorDirective)
941 return true;
942
943 // If this BCPL-style comment is in a macro definition, transmogrify it into
944 // a C-style block comment.
945 std::string Spelling = PP->getSpelling(Result);
946 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not bcpl comment?");
947 Spelling[1] = '*'; // Change prefix to "/*".
948 Spelling += "*/"; // add suffix.
949
950 Result.setKind(tok::comment);
Chris Lattner47246be2009-01-26 19:29:26 +0000951 PP->CreateString(&Spelling[0], Spelling.size(), Result,
952 Result.getLocation());
Chris Lattner2d381892008-10-12 04:15:42 +0000953 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000954}
955
956/// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
957/// character (either \n or \r) is part of an escaped newline sequence. Issue a
Chris Lattner47a2b402008-12-12 07:14:34 +0000958/// diagnostic if so. We know that the newline is inside of a block comment.
Reid Spencer5f016e22007-07-11 17:01:13 +0000959static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
960 Lexer *L) {
961 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
962
963 // Back up off the newline.
964 --CurPtr;
965
966 // If this is a two-character newline sequence, skip the other character.
967 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
968 // \n\n or \r\r -> not escaped newline.
969 if (CurPtr[0] == CurPtr[1])
970 return false;
971 // \n\r or \r\n -> skip the newline.
972 --CurPtr;
973 }
974
975 // If we have horizontal whitespace, skip over it. We allow whitespace
976 // between the slash and newline.
977 bool HasSpace = false;
978 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
979 --CurPtr;
980 HasSpace = true;
981 }
982
983 // If we have a slash, we know this is an escaped newline.
984 if (*CurPtr == '\\') {
985 if (CurPtr[-1] != '*') return false;
986 } else {
987 // It isn't a slash, is it the ?? / trigraph?
988 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
989 CurPtr[-3] != '*')
990 return false;
991
992 // This is the trigraph ending the comment. Emit a stern warning!
993 CurPtr -= 2;
994
995 // If no trigraphs are enabled, warn that we ignored this trigraph and
996 // ignore this * character.
997 if (!L->getFeatures().Trigraphs) {
Chris Lattner74d15df2008-11-22 02:02:22 +0000998 if (!L->isLexingRawMode())
999 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001000 return false;
1001 }
Chris Lattner74d15df2008-11-22 02:02:22 +00001002 if (!L->isLexingRawMode())
1003 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001004 }
1005
1006 // Warn about having an escaped newline between the */ characters.
Chris Lattner74d15df2008-11-22 02:02:22 +00001007 if (!L->isLexingRawMode())
1008 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
Reid Spencer5f016e22007-07-11 17:01:13 +00001009
1010 // If there was space between the backslash and newline, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001011 if (HasSpace && !L->isLexingRawMode())
1012 L->Diag(CurPtr, diag::backslash_newline_space);
Reid Spencer5f016e22007-07-11 17:01:13 +00001013
1014 return true;
1015}
1016
1017#ifdef __SSE2__
1018#include <emmintrin.h>
1019#elif __ALTIVEC__
1020#include <altivec.h>
1021#undef bool
1022#endif
1023
1024/// SkipBlockComment - We have just read the /* characters from input. Read
1025/// until we find the */ characters that terminate the comment. Note that we
1026/// don't bother decoding trigraphs or escaped newlines in block comments,
1027/// because they cannot cause the comment to end. The only thing that can
1028/// happen is the comment could end with an escaped newline between the */ end
1029/// of comment.
Chris Lattner2d381892008-10-12 04:15:42 +00001030///
1031/// If KeepCommentMode is enabled, this forms a token from the comment and
1032/// returns true.
Chris Lattnerd2177732007-07-20 16:59:19 +00001033bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001034 // Scan one character past where we should, looking for a '/' character. Once
1035 // we find it, check to see if it was preceeded by a *. This common
1036 // optimization helps people who like to put a lot of * characters in their
1037 // comments.
Chris Lattner8146b682007-07-21 23:43:37 +00001038
1039 // The first character we get with newlines and trigraphs skipped to handle
1040 // the degenerate /*/ case below correctly if the * has an escaped newline
1041 // after it.
1042 unsigned CharSize;
1043 unsigned char C = getCharAndSize(CurPtr, CharSize);
1044 CurPtr += CharSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001045 if (C == 0 && CurPtr == BufferEnd+1) {
Chris Lattner74d15df2008-11-22 02:02:22 +00001046 if (!isLexingRawMode())
Chris Lattner0af57422008-10-12 01:31:51 +00001047 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner31f0eca2008-10-12 04:19:49 +00001048 --CurPtr;
1049
1050 // KeepWhitespaceMode should return this broken comment as a token. Since
1051 // it isn't a well formed comment, just return it as an 'unknown' token.
1052 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001053 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner31f0eca2008-10-12 04:19:49 +00001054 return true;
1055 }
1056
1057 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001058 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001059 }
1060
Chris Lattner8146b682007-07-21 23:43:37 +00001061 // Check to see if the first character after the '/*' is another /. If so,
1062 // then this slash does not end the block comment, it is part of it.
1063 if (C == '/')
1064 C = *CurPtr++;
1065
Reid Spencer5f016e22007-07-11 17:01:13 +00001066 while (1) {
1067 // Skip over all non-interesting characters until we find end of buffer or a
1068 // (probably ending) '/' character.
1069 if (CurPtr + 24 < BufferEnd) {
1070 // While not aligned to a 16-byte boundary.
1071 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
1072 C = *CurPtr++;
1073
1074 if (C == '/') goto FoundSlash;
1075
1076#ifdef __SSE2__
1077 __m128i Slashes = _mm_set_epi8('/', '/', '/', '/', '/', '/', '/', '/',
1078 '/', '/', '/', '/', '/', '/', '/', '/');
1079 while (CurPtr+16 <= BufferEnd &&
1080 _mm_movemask_epi8(_mm_cmpeq_epi8(*(__m128i*)CurPtr, Slashes)) == 0)
1081 CurPtr += 16;
1082#elif __ALTIVEC__
1083 __vector unsigned char Slashes = {
1084 '/', '/', '/', '/', '/', '/', '/', '/',
1085 '/', '/', '/', '/', '/', '/', '/', '/'
1086 };
1087 while (CurPtr+16 <= BufferEnd &&
1088 !vec_any_eq(*(vector unsigned char*)CurPtr, Slashes))
1089 CurPtr += 16;
1090#else
1091 // Scan for '/' quickly. Many block comments are very large.
1092 while (CurPtr[0] != '/' &&
1093 CurPtr[1] != '/' &&
1094 CurPtr[2] != '/' &&
1095 CurPtr[3] != '/' &&
1096 CurPtr+4 < BufferEnd) {
1097 CurPtr += 4;
1098 }
1099#endif
1100
1101 // It has to be one of the bytes scanned, increment to it and read one.
1102 C = *CurPtr++;
1103 }
1104
1105 // Loop to scan the remainder.
1106 while (C != '/' && C != '\0')
1107 C = *CurPtr++;
1108
1109 FoundSlash:
1110 if (C == '/') {
1111 if (CurPtr[-2] == '*') // We found the final */. We're done!
1112 break;
1113
1114 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
1115 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
1116 // We found the final */, though it had an escaped newline between the
1117 // * and /. We're done!
1118 break;
1119 }
1120 }
1121 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
1122 // If this is a /* inside of the comment, emit a warning. Don't do this
1123 // if this is a /*/, which will end the comment. This misses cases with
1124 // embedded escaped newlines, but oh well.
Chris Lattner74d15df2008-11-22 02:02:22 +00001125 if (!isLexingRawMode())
1126 Diag(CurPtr-1, diag::warn_nested_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001127 }
1128 } else if (C == 0 && CurPtr == BufferEnd+1) {
Chris Lattner74d15df2008-11-22 02:02:22 +00001129 if (!isLexingRawMode())
1130 Diag(BufferPtr, diag::err_unterminated_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001131 // Note: the user probably forgot a */. We could continue immediately
1132 // after the /*, but this would involve lexing a lot of what really is the
1133 // comment, which surely would confuse the parser.
Chris Lattner31f0eca2008-10-12 04:19:49 +00001134 --CurPtr;
1135
1136 // KeepWhitespaceMode should return this broken comment as a token. Since
1137 // it isn't a well formed comment, just return it as an 'unknown' token.
1138 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001139 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner31f0eca2008-10-12 04:19:49 +00001140 return true;
1141 }
1142
1143 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001144 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001145 }
1146 C = *CurPtr++;
1147 }
1148
1149 // If we are returning comments as tokens, return this comment as a token.
Chris Lattnerfa95a012008-10-12 03:22:02 +00001150 if (inKeepCommentMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001151 FormTokenWithChars(Result, CurPtr, tok::comment);
Chris Lattner2d381892008-10-12 04:15:42 +00001152 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001153 }
1154
1155 // It is common for the tokens immediately after a /**/ comment to be
1156 // whitespace. Instead of going through the big switch, handle it
Chris Lattnerd88dc482008-10-12 04:05:48 +00001157 // efficiently now. This is safe even in KeepWhitespaceMode because we would
1158 // have already returned above with the comment as a token.
Reid Spencer5f016e22007-07-11 17:01:13 +00001159 if (isHorizontalWhitespace(*CurPtr)) {
Chris Lattnerd2177732007-07-20 16:59:19 +00001160 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001161 SkipWhitespace(Result, CurPtr+1);
Chris Lattner2d381892008-10-12 04:15:42 +00001162 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001163 }
1164
1165 // Otherwise, just return so that the next character will be lexed as a token.
1166 BufferPtr = CurPtr;
Chris Lattnerd2177732007-07-20 16:59:19 +00001167 Result.setFlag(Token::LeadingSpace);
Chris Lattner2d381892008-10-12 04:15:42 +00001168 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001169}
1170
1171//===----------------------------------------------------------------------===//
1172// Primary Lexing Entry Points
1173//===----------------------------------------------------------------------===//
1174
Reid Spencer5f016e22007-07-11 17:01:13 +00001175/// ReadToEndOfLine - Read the rest of the current preprocessor line as an
1176/// uninterpreted string. This switches the lexer out of directive mode.
1177std::string Lexer::ReadToEndOfLine() {
1178 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
1179 "Must be in a preprocessing directive!");
1180 std::string Result;
Chris Lattnerd2177732007-07-20 16:59:19 +00001181 Token Tmp;
Reid Spencer5f016e22007-07-11 17:01:13 +00001182
1183 // CurPtr - Cache BufferPtr in an automatic variable.
1184 const char *CurPtr = BufferPtr;
1185 while (1) {
1186 char Char = getAndAdvanceChar(CurPtr, Tmp);
1187 switch (Char) {
1188 default:
1189 Result += Char;
1190 break;
1191 case 0: // Null.
1192 // Found end of file?
1193 if (CurPtr-1 != BufferEnd) {
1194 // Nope, normal character, continue.
1195 Result += Char;
1196 break;
1197 }
1198 // FALL THROUGH.
1199 case '\r':
1200 case '\n':
1201 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
1202 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
1203 BufferPtr = CurPtr-1;
1204
1205 // Next, lex the character, which should handle the EOM transition.
1206 Lex(Tmp);
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001207 assert(Tmp.is(tok::eom) && "Unexpected token!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001208
1209 // Finally, we're done, return the string we found.
1210 return Result;
1211 }
1212 }
1213}
1214
1215/// LexEndOfFile - CurPtr points to the end of this file. Handle this
1216/// condition, reporting diagnostics and handling other edge cases as required.
1217/// This returns true if Result contains a token, false if PP.Lex should be
1218/// called again.
Chris Lattnerd2177732007-07-20 16:59:19 +00001219bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001220 // If we hit the end of the file while parsing a preprocessor directive,
1221 // end the preprocessor directive first. The next token returned will
1222 // then be the end of file.
1223 if (ParsingPreprocessorDirective) {
1224 // Done parsing the "line".
1225 ParsingPreprocessorDirective = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001226 // Update the location of token as well as BufferPtr.
Chris Lattner9e6293d2008-10-12 04:51:35 +00001227 FormTokenWithChars(Result, CurPtr, tok::eom);
Reid Spencer5f016e22007-07-11 17:01:13 +00001228
1229 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattnerf744d132008-10-12 03:27:19 +00001230 SetCommentRetentionState(PP->getCommentRetentionState());
Reid Spencer5f016e22007-07-11 17:01:13 +00001231 return true; // Have a token.
1232 }
1233
1234 // If we are in raw mode, return this event as an EOF token. Let the caller
1235 // that put us in raw mode handle the event.
Chris Lattner74d15df2008-11-22 02:02:22 +00001236 if (isLexingRawMode()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001237 Result.startToken();
1238 BufferPtr = BufferEnd;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001239 FormTokenWithChars(Result, BufferEnd, tok::eof);
Reid Spencer5f016e22007-07-11 17:01:13 +00001240 return true;
1241 }
1242
1243 // Otherwise, issue diagnostics for unterminated #if and missing newline.
1244
1245 // If we are in a #if directive, emit an error.
1246 while (!ConditionalStack.empty()) {
Chris Lattner30c64762008-11-22 06:22:39 +00001247 PP->Diag(ConditionalStack.back().IfLoc,
1248 diag::err_pp_unterminated_conditional);
Reid Spencer5f016e22007-07-11 17:01:13 +00001249 ConditionalStack.pop_back();
1250 }
1251
Chris Lattnerb25e5d72008-04-12 05:54:25 +00001252 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
1253 // a pedwarn.
1254 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r'))
Mike Stump20d0ee52009-04-02 02:29:42 +00001255 Diag(BufferEnd, diag::ext_no_newline_eof)
1256 << CodeModificationHint::CreateInsertion(getSourceLocation(BufferEnd),
1257 "\n");
Reid Spencer5f016e22007-07-11 17:01:13 +00001258
1259 BufferPtr = CurPtr;
1260
1261 // Finally, let the preprocessor handle this.
Chris Lattner168ae2d2007-10-17 20:41:00 +00001262 return PP->HandleEndOfFile(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001263}
1264
1265/// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
1266/// the specified lexer will return a tok::l_paren token, 0 if it is something
1267/// else and 2 if there are no more tokens in the buffer controlled by the
1268/// lexer.
1269unsigned Lexer::isNextPPTokenLParen() {
1270 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
1271
1272 // Switch to 'skipping' mode. This will ensure that we can lex a token
1273 // without emitting diagnostics, disables macro expansion, and will cause EOF
1274 // to return an EOF token instead of popping the include stack.
1275 LexingRawMode = true;
1276
1277 // Save state that can be changed while lexing so that we can restore it.
1278 const char *TmpBufferPtr = BufferPtr;
Chris Lattnera864cf72009-04-24 07:15:46 +00001279 bool inPPDirectiveMode = ParsingPreprocessorDirective;
Reid Spencer5f016e22007-07-11 17:01:13 +00001280
Chris Lattnerd2177732007-07-20 16:59:19 +00001281 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001282 Tok.startToken();
1283 LexTokenInternal(Tok);
1284
1285 // Restore state that may have changed.
1286 BufferPtr = TmpBufferPtr;
Chris Lattnera864cf72009-04-24 07:15:46 +00001287 ParsingPreprocessorDirective = inPPDirectiveMode;
Reid Spencer5f016e22007-07-11 17:01:13 +00001288
1289 // Restore the lexer back to non-skipping mode.
1290 LexingRawMode = false;
1291
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001292 if (Tok.is(tok::eof))
Reid Spencer5f016e22007-07-11 17:01:13 +00001293 return 2;
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001294 return Tok.is(tok::l_paren);
Reid Spencer5f016e22007-07-11 17:01:13 +00001295}
1296
1297
1298/// LexTokenInternal - This implements a simple C family lexer. It is an
1299/// extremely performance critical piece of code. This assumes that the buffer
1300/// has a null character at the end of the file. Return true if an error
1301/// occurred and compilation should terminate, false if normal. This returns a
1302/// preprocessing token, not a normal token, as such, it is an internal
1303/// interface. It assumes that the Flags of result have been cleared before
1304/// calling this.
Chris Lattnerd2177732007-07-20 16:59:19 +00001305void Lexer::LexTokenInternal(Token &Result) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001306LexNextToken:
1307 // New token, can't need cleaning yet.
Chris Lattnerd2177732007-07-20 16:59:19 +00001308 Result.clearFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00001309 Result.setIdentifierInfo(0);
1310
1311 // CurPtr - Cache BufferPtr in an automatic variable.
1312 const char *CurPtr = BufferPtr;
1313
1314 // Small amounts of horizontal whitespace is very common between tokens.
1315 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
1316 ++CurPtr;
1317 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
1318 ++CurPtr;
Chris Lattnerd88dc482008-10-12 04:05:48 +00001319
1320 // If we are keeping whitespace and other tokens, just return what we just
1321 // skipped. The next lexer invocation will return the token after the
1322 // whitespace.
1323 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001324 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd88dc482008-10-12 04:05:48 +00001325 return;
1326 }
1327
Reid Spencer5f016e22007-07-11 17:01:13 +00001328 BufferPtr = CurPtr;
Chris Lattnerd2177732007-07-20 16:59:19 +00001329 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001330 }
1331
1332 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
1333
1334 // Read a character, advancing over it.
1335 char Char = getAndAdvanceChar(CurPtr, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001336 tok::TokenKind Kind;
1337
Reid Spencer5f016e22007-07-11 17:01:13 +00001338 switch (Char) {
1339 case 0: // Null.
1340 // Found end of file?
1341 if (CurPtr-1 == BufferEnd) {
1342 // Read the PP instance variable into an automatic variable, because
1343 // LexEndOfFile will often delete 'this'.
Chris Lattner168ae2d2007-10-17 20:41:00 +00001344 Preprocessor *PPCache = PP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001345 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
1346 return; // Got a token to return.
Chris Lattner168ae2d2007-10-17 20:41:00 +00001347 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
1348 return PPCache->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001349 }
1350
Chris Lattner74d15df2008-11-22 02:02:22 +00001351 if (!isLexingRawMode())
1352 Diag(CurPtr-1, diag::null_in_file);
Chris Lattnerd2177732007-07-20 16:59:19 +00001353 Result.setFlag(Token::LeadingSpace);
Chris Lattnerd88dc482008-10-12 04:05:48 +00001354 if (SkipWhitespace(Result, CurPtr))
1355 return; // KeepWhitespaceMode
1356
Reid Spencer5f016e22007-07-11 17:01:13 +00001357 goto LexNextToken; // GCC isn't tail call eliminating.
1358 case '\n':
1359 case '\r':
1360 // If we are inside a preprocessor directive and we see the end of line,
1361 // we know we are done with the directive, so return an EOM token.
1362 if (ParsingPreprocessorDirective) {
1363 // Done parsing the "line".
1364 ParsingPreprocessorDirective = false;
1365
1366 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattnerf744d132008-10-12 03:27:19 +00001367 SetCommentRetentionState(PP->getCommentRetentionState());
Reid Spencer5f016e22007-07-11 17:01:13 +00001368
1369 // Since we consumed a newline, we are back at the start of a line.
1370 IsAtStartOfLine = true;
1371
Chris Lattner9e6293d2008-10-12 04:51:35 +00001372 Kind = tok::eom;
Reid Spencer5f016e22007-07-11 17:01:13 +00001373 break;
1374 }
1375 // The returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00001376 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00001377 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00001378 Result.clearFlag(Token::LeadingSpace);
Chris Lattnerd88dc482008-10-12 04:05:48 +00001379
1380 if (SkipWhitespace(Result, CurPtr))
1381 return; // KeepWhitespaceMode
Reid Spencer5f016e22007-07-11 17:01:13 +00001382 goto LexNextToken; // GCC isn't tail call eliminating.
1383 case ' ':
1384 case '\t':
1385 case '\f':
1386 case '\v':
Chris Lattner8133cfc2007-07-22 06:29:05 +00001387 SkipHorizontalWhitespace:
Chris Lattnerd2177732007-07-20 16:59:19 +00001388 Result.setFlag(Token::LeadingSpace);
Chris Lattnerd88dc482008-10-12 04:05:48 +00001389 if (SkipWhitespace(Result, CurPtr))
1390 return; // KeepWhitespaceMode
Chris Lattner8133cfc2007-07-22 06:29:05 +00001391
1392 SkipIgnoredUnits:
1393 CurPtr = BufferPtr;
1394
1395 // If the next token is obviously a // or /* */ comment, skip it efficiently
1396 // too (without going through the big switch stmt).
Chris Lattner8402c732009-01-16 22:39:25 +00001397 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
1398 Features.BCPLComment) {
Chris Lattner8133cfc2007-07-22 06:29:05 +00001399 SkipBCPLComment(Result, CurPtr+2);
1400 goto SkipIgnoredUnits;
Chris Lattnerfa95a012008-10-12 03:22:02 +00001401 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
Chris Lattner8133cfc2007-07-22 06:29:05 +00001402 SkipBlockComment(Result, CurPtr+2);
1403 goto SkipIgnoredUnits;
1404 } else if (isHorizontalWhitespace(*CurPtr)) {
1405 goto SkipHorizontalWhitespace;
1406 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001407 goto LexNextToken; // GCC isn't tail call eliminating.
1408
Chris Lattner3a570772008-01-03 17:58:54 +00001409 // C99 6.4.4.1: Integer Constants.
1410 // C99 6.4.4.2: Floating Constants.
1411 case '0': case '1': case '2': case '3': case '4':
1412 case '5': case '6': case '7': case '8': case '9':
1413 // Notify MIOpt that we read a non-whitespace/non-comment token.
1414 MIOpt.ReadToken();
1415 return LexNumericConstant(Result, CurPtr);
1416
1417 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
Reid Spencer5f016e22007-07-11 17:01:13 +00001418 // Notify MIOpt that we read a non-whitespace/non-comment token.
1419 MIOpt.ReadToken();
1420 Char = getCharAndSize(CurPtr, SizeTmp);
1421
1422 // Wide string literal.
1423 if (Char == '"')
1424 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
1425 true);
1426
1427 // Wide character constant.
1428 if (Char == '\'')
1429 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
1430 // FALL THROUGH, treating L like the start of an identifier.
1431
1432 // C99 6.4.2: Identifiers.
1433 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
1434 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
1435 case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U':
1436 case 'V': case 'W': case 'X': case 'Y': case 'Z':
1437 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
1438 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
1439 case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u':
1440 case 'v': case 'w': case 'x': case 'y': case 'z':
1441 case '_':
1442 // Notify MIOpt that we read a non-whitespace/non-comment token.
1443 MIOpt.ReadToken();
1444 return LexIdentifier(Result, CurPtr);
Chris Lattner3a570772008-01-03 17:58:54 +00001445
1446 case '$': // $ in identifiers.
1447 if (Features.DollarIdents) {
Chris Lattner74d15df2008-11-22 02:02:22 +00001448 if (!isLexingRawMode())
1449 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
Chris Lattner3a570772008-01-03 17:58:54 +00001450 // Notify MIOpt that we read a non-whitespace/non-comment token.
1451 MIOpt.ReadToken();
1452 return LexIdentifier(Result, CurPtr);
1453 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001454
Chris Lattner9e6293d2008-10-12 04:51:35 +00001455 Kind = tok::unknown;
Chris Lattner3a570772008-01-03 17:58:54 +00001456 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001457
1458 // C99 6.4.4: Character Constants.
1459 case '\'':
1460 // Notify MIOpt that we read a non-whitespace/non-comment token.
1461 MIOpt.ReadToken();
1462 return LexCharConstant(Result, CurPtr);
1463
1464 // C99 6.4.5: String Literals.
1465 case '"':
1466 // Notify MIOpt that we read a non-whitespace/non-comment token.
1467 MIOpt.ReadToken();
1468 return LexStringLiteral(Result, CurPtr, false);
1469
1470 // C99 6.4.6: Punctuators.
1471 case '?':
Chris Lattner9e6293d2008-10-12 04:51:35 +00001472 Kind = tok::question;
Reid Spencer5f016e22007-07-11 17:01:13 +00001473 break;
1474 case '[':
Chris Lattner9e6293d2008-10-12 04:51:35 +00001475 Kind = tok::l_square;
Reid Spencer5f016e22007-07-11 17:01:13 +00001476 break;
1477 case ']':
Chris Lattner9e6293d2008-10-12 04:51:35 +00001478 Kind = tok::r_square;
Reid Spencer5f016e22007-07-11 17:01:13 +00001479 break;
1480 case '(':
Chris Lattner9e6293d2008-10-12 04:51:35 +00001481 Kind = tok::l_paren;
Reid Spencer5f016e22007-07-11 17:01:13 +00001482 break;
1483 case ')':
Chris Lattner9e6293d2008-10-12 04:51:35 +00001484 Kind = tok::r_paren;
Reid Spencer5f016e22007-07-11 17:01:13 +00001485 break;
1486 case '{':
Chris Lattner9e6293d2008-10-12 04:51:35 +00001487 Kind = tok::l_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00001488 break;
1489 case '}':
Chris Lattner9e6293d2008-10-12 04:51:35 +00001490 Kind = tok::r_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00001491 break;
1492 case '.':
1493 Char = getCharAndSize(CurPtr, SizeTmp);
1494 if (Char >= '0' && Char <= '9') {
1495 // Notify MIOpt that we read a non-whitespace/non-comment token.
1496 MIOpt.ReadToken();
1497
1498 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
1499 } else if (Features.CPlusPlus && Char == '*') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001500 Kind = tok::periodstar;
Reid Spencer5f016e22007-07-11 17:01:13 +00001501 CurPtr += SizeTmp;
1502 } else if (Char == '.' &&
1503 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001504 Kind = tok::ellipsis;
Reid Spencer5f016e22007-07-11 17:01:13 +00001505 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1506 SizeTmp2, Result);
1507 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001508 Kind = tok::period;
Reid Spencer5f016e22007-07-11 17:01:13 +00001509 }
1510 break;
1511 case '&':
1512 Char = getCharAndSize(CurPtr, SizeTmp);
1513 if (Char == '&') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001514 Kind = tok::ampamp;
Reid Spencer5f016e22007-07-11 17:01:13 +00001515 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1516 } else if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001517 Kind = tok::ampequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00001518 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1519 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001520 Kind = tok::amp;
Reid Spencer5f016e22007-07-11 17:01:13 +00001521 }
1522 break;
1523 case '*':
1524 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001525 Kind = tok::starequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00001526 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1527 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001528 Kind = tok::star;
Reid Spencer5f016e22007-07-11 17:01:13 +00001529 }
1530 break;
1531 case '+':
1532 Char = getCharAndSize(CurPtr, SizeTmp);
1533 if (Char == '+') {
Reid Spencer5f016e22007-07-11 17:01:13 +00001534 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001535 Kind = tok::plusplus;
Reid Spencer5f016e22007-07-11 17:01:13 +00001536 } else if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00001537 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001538 Kind = tok::plusequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00001539 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001540 Kind = tok::plus;
Reid Spencer5f016e22007-07-11 17:01:13 +00001541 }
1542 break;
1543 case '-':
1544 Char = getCharAndSize(CurPtr, SizeTmp);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001545 if (Char == '-') { // --
Reid Spencer5f016e22007-07-11 17:01:13 +00001546 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001547 Kind = tok::minusminus;
Reid Spencer5f016e22007-07-11 17:01:13 +00001548 } else if (Char == '>' && Features.CPlusPlus &&
Chris Lattner9e6293d2008-10-12 04:51:35 +00001549 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
Reid Spencer5f016e22007-07-11 17:01:13 +00001550 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1551 SizeTmp2, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001552 Kind = tok::arrowstar;
1553 } else if (Char == '>') { // ->
Reid Spencer5f016e22007-07-11 17:01:13 +00001554 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001555 Kind = tok::arrow;
1556 } else 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::minusequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00001559 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001560 Kind = tok::minus;
Reid Spencer5f016e22007-07-11 17:01:13 +00001561 }
1562 break;
1563 case '~':
Chris Lattner9e6293d2008-10-12 04:51:35 +00001564 Kind = tok::tilde;
Reid Spencer5f016e22007-07-11 17:01:13 +00001565 break;
1566 case '!':
1567 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001568 Kind = tok::exclaimequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00001569 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1570 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001571 Kind = tok::exclaim;
Reid Spencer5f016e22007-07-11 17:01:13 +00001572 }
1573 break;
1574 case '/':
1575 // 6.4.9: Comments
1576 Char = getCharAndSize(CurPtr, SizeTmp);
1577 if (Char == '/') { // BCPL comment.
Chris Lattner8402c732009-01-16 22:39:25 +00001578 // Even if BCPL comments are disabled (e.g. in C89 mode), we generally
1579 // want to lex this as a comment. There is one problem with this though,
1580 // that in one particular corner case, this can change the behavior of the
1581 // resultant program. For example, In "foo //**/ bar", C89 would lex
1582 // this as "foo / bar" and langauges with BCPL comments would lex it as
1583 // "foo". Check to see if the character after the second slash is a '*'.
1584 // If so, we will lex that as a "/" instead of the start of a comment.
1585 if (Features.BCPLComment ||
1586 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*') {
1587 if (SkipBCPLComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
1588 return; // KeepCommentMode
Chris Lattner2d381892008-10-12 04:15:42 +00001589
Chris Lattner8402c732009-01-16 22:39:25 +00001590 // It is common for the tokens immediately after a // comment to be
1591 // whitespace (indentation for the next line). Instead of going through
1592 // the big switch, handle it efficiently now.
1593 goto SkipIgnoredUnits;
1594 }
1595 }
1596
1597 if (Char == '*') { // /**/ comment.
Reid Spencer5f016e22007-07-11 17:01:13 +00001598 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattner2d381892008-10-12 04:15:42 +00001599 return; // KeepCommentMode
1600 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattner8402c732009-01-16 22:39:25 +00001601 }
1602
1603 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00001604 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001605 Kind = tok::slashequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00001606 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001607 Kind = tok::slash;
Reid Spencer5f016e22007-07-11 17:01:13 +00001608 }
1609 break;
1610 case '%':
1611 Char = getCharAndSize(CurPtr, SizeTmp);
1612 if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001613 Kind = tok::percentequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00001614 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1615 } else if (Features.Digraphs && Char == '>') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001616 Kind = tok::r_brace; // '%>' -> '}'
Reid Spencer5f016e22007-07-11 17:01:13 +00001617 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1618 } else if (Features.Digraphs && Char == ':') {
1619 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1620 Char = getCharAndSize(CurPtr, SizeTmp);
1621 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001622 Kind = tok::hashhash; // '%:%:' -> '##'
Reid Spencer5f016e22007-07-11 17:01:13 +00001623 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1624 SizeTmp2, Result);
1625 } else if (Char == '@' && Features.Microsoft) { // %:@ -> #@ -> Charize
Reid Spencer5f016e22007-07-11 17:01:13 +00001626 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner74d15df2008-11-22 02:02:22 +00001627 if (!isLexingRawMode())
1628 Diag(BufferPtr, diag::charize_microsoft_ext);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001629 Kind = tok::hashat;
Chris Lattnere91e9322009-03-18 20:58:27 +00001630 } else { // '%:' -> '#'
Reid Spencer5f016e22007-07-11 17:01:13 +00001631 // We parsed a # character. If this occurs at the start of the line,
1632 // it's actually the start of a preprocessing directive. Callback to
1633 // the preprocessor to handle it.
1634 // FIXME: -fpreprocessed mode??
1635 if (Result.isAtStartOfLine() && !LexingRawMode) {
Chris Lattnere91e9322009-03-18 20:58:27 +00001636 FormTokenWithChars(Result, CurPtr, tok::hash);
Chris Lattner168ae2d2007-10-17 20:41:00 +00001637 PP->HandleDirective(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001638
1639 // As an optimization, if the preprocessor didn't switch lexers, tail
1640 // recurse.
Chris Lattner168ae2d2007-10-17 20:41:00 +00001641 if (PP->isCurrentLexer(this)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001642 // Start a new token. If this is a #include or something, the PP may
1643 // want us starting at the beginning of the line again. If so, set
1644 // the StartOfLine flag.
1645 if (IsAtStartOfLine) {
Chris Lattnerd2177732007-07-20 16:59:19 +00001646 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00001647 IsAtStartOfLine = false;
1648 }
1649 goto LexNextToken; // GCC isn't tail call eliminating.
1650 }
1651
Chris Lattner168ae2d2007-10-17 20:41:00 +00001652 return PP->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001653 }
Chris Lattnere91e9322009-03-18 20:58:27 +00001654
1655 Kind = tok::hash;
Reid Spencer5f016e22007-07-11 17:01:13 +00001656 }
1657 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001658 Kind = tok::percent;
Reid Spencer5f016e22007-07-11 17:01:13 +00001659 }
1660 break;
1661 case '<':
1662 Char = getCharAndSize(CurPtr, SizeTmp);
1663 if (ParsingFilename) {
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001664 return LexAngledStringLiteral(Result, CurPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +00001665 } else if (Char == '<' &&
1666 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001667 Kind = tok::lesslessequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00001668 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1669 SizeTmp2, Result);
1670 } else if (Char == '<') {
Reid Spencer5f016e22007-07-11 17:01:13 +00001671 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001672 Kind = tok::lessless;
Reid Spencer5f016e22007-07-11 17:01:13 +00001673 } else if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00001674 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001675 Kind = tok::lessequal;
1676 } else if (Features.Digraphs && Char == ':') { // '<:' -> '['
Reid Spencer5f016e22007-07-11 17:01:13 +00001677 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001678 Kind = tok::l_square;
1679 } else if (Features.Digraphs && Char == '%') { // '<%' -> '{'
Reid Spencer5f016e22007-07-11 17:01:13 +00001680 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001681 Kind = tok::l_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00001682 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001683 Kind = tok::less;
Reid Spencer5f016e22007-07-11 17:01:13 +00001684 }
1685 break;
1686 case '>':
1687 Char = getCharAndSize(CurPtr, SizeTmp);
1688 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00001689 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001690 Kind = tok::greaterequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00001691 } else if (Char == '>' &&
1692 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00001693 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1694 SizeTmp2, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001695 Kind = tok::greatergreaterequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00001696 } else if (Char == '>') {
Reid Spencer5f016e22007-07-11 17:01:13 +00001697 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001698 Kind = tok::greatergreater;
Reid Spencer5f016e22007-07-11 17:01:13 +00001699 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001700 Kind = tok::greater;
Reid Spencer5f016e22007-07-11 17:01:13 +00001701 }
1702 break;
1703 case '^':
1704 Char = getCharAndSize(CurPtr, SizeTmp);
1705 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00001706 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001707 Kind = tok::caretequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00001708 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001709 Kind = tok::caret;
Reid Spencer5f016e22007-07-11 17:01:13 +00001710 }
1711 break;
1712 case '|':
1713 Char = getCharAndSize(CurPtr, SizeTmp);
1714 if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001715 Kind = tok::pipeequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00001716 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1717 } else if (Char == '|') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001718 Kind = tok::pipepipe;
Reid Spencer5f016e22007-07-11 17:01:13 +00001719 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1720 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001721 Kind = tok::pipe;
Reid Spencer5f016e22007-07-11 17:01:13 +00001722 }
1723 break;
1724 case ':':
1725 Char = getCharAndSize(CurPtr, SizeTmp);
1726 if (Features.Digraphs && Char == '>') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001727 Kind = tok::r_square; // ':>' -> ']'
Reid Spencer5f016e22007-07-11 17:01:13 +00001728 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1729 } else if (Features.CPlusPlus && Char == ':') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001730 Kind = tok::coloncolon;
Reid Spencer5f016e22007-07-11 17:01:13 +00001731 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1732 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001733 Kind = tok::colon;
Reid Spencer5f016e22007-07-11 17:01:13 +00001734 }
1735 break;
1736 case ';':
Chris Lattner9e6293d2008-10-12 04:51:35 +00001737 Kind = tok::semi;
Reid Spencer5f016e22007-07-11 17:01:13 +00001738 break;
1739 case '=':
1740 Char = getCharAndSize(CurPtr, SizeTmp);
1741 if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001742 Kind = tok::equalequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00001743 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1744 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001745 Kind = tok::equal;
Reid Spencer5f016e22007-07-11 17:01:13 +00001746 }
1747 break;
1748 case ',':
Chris Lattner9e6293d2008-10-12 04:51:35 +00001749 Kind = tok::comma;
Reid Spencer5f016e22007-07-11 17:01:13 +00001750 break;
1751 case '#':
1752 Char = getCharAndSize(CurPtr, SizeTmp);
1753 if (Char == '#') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001754 Kind = tok::hashhash;
Reid Spencer5f016e22007-07-11 17:01:13 +00001755 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1756 } else if (Char == '@' && Features.Microsoft) { // #@ -> Charize
Chris Lattner9e6293d2008-10-12 04:51:35 +00001757 Kind = tok::hashat;
Chris Lattner74d15df2008-11-22 02:02:22 +00001758 if (!isLexingRawMode())
1759 Diag(BufferPtr, diag::charize_microsoft_ext);
Reid Spencer5f016e22007-07-11 17:01:13 +00001760 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1761 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +00001762 // We parsed a # character. If this occurs at the start of the line,
1763 // it's actually the start of a preprocessing directive. Callback to
1764 // the preprocessor to handle it.
1765 // FIXME: -fpreprocessed mode??
1766 if (Result.isAtStartOfLine() && !LexingRawMode) {
Chris Lattnere91e9322009-03-18 20:58:27 +00001767 FormTokenWithChars(Result, CurPtr, tok::hash);
Chris Lattner168ae2d2007-10-17 20:41:00 +00001768 PP->HandleDirective(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001769
1770 // As an optimization, if the preprocessor didn't switch lexers, tail
1771 // recurse.
Chris Lattner168ae2d2007-10-17 20:41:00 +00001772 if (PP->isCurrentLexer(this)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001773 // Start a new token. If this is a #include or something, the PP may
1774 // want us starting at the beginning of the line again. If so, set
1775 // the StartOfLine flag.
1776 if (IsAtStartOfLine) {
Chris Lattnerd2177732007-07-20 16:59:19 +00001777 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00001778 IsAtStartOfLine = false;
1779 }
1780 goto LexNextToken; // GCC isn't tail call eliminating.
1781 }
Chris Lattner168ae2d2007-10-17 20:41:00 +00001782 return PP->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001783 }
Chris Lattnere91e9322009-03-18 20:58:27 +00001784
1785 Kind = tok::hash;
Reid Spencer5f016e22007-07-11 17:01:13 +00001786 }
1787 break;
1788
Chris Lattner3a570772008-01-03 17:58:54 +00001789 case '@':
1790 // Objective C support.
1791 if (CurPtr[-1] == '@' && Features.ObjC1)
Chris Lattner9e6293d2008-10-12 04:51:35 +00001792 Kind = tok::at;
Chris Lattner3a570772008-01-03 17:58:54 +00001793 else
Chris Lattner9e6293d2008-10-12 04:51:35 +00001794 Kind = tok::unknown;
Chris Lattner3a570772008-01-03 17:58:54 +00001795 break;
1796
Reid Spencer5f016e22007-07-11 17:01:13 +00001797 case '\\':
1798 // FIXME: UCN's.
1799 // FALL THROUGH.
1800 default:
Chris Lattner9e6293d2008-10-12 04:51:35 +00001801 Kind = tok::unknown;
Reid Spencer5f016e22007-07-11 17:01:13 +00001802 break;
1803 }
1804
1805 // Notify MIOpt that we read a non-whitespace/non-comment token.
1806 MIOpt.ReadToken();
1807
1808 // Update the location of token as well as BufferPtr.
Chris Lattner9e6293d2008-10-12 04:51:35 +00001809 FormTokenWithChars(Result, CurPtr, Kind);
Reid Spencer5f016e22007-07-11 17:01:13 +00001810}