blob: 490a0b53049d93f94d4bb0be550594f6a66dbe55 [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
402/// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
403/// get its size, and return it. This is tricky in several cases:
404/// 1. If currently at the start of a trigraph, we warn about the trigraph,
405/// then either return the trigraph (skipping 3 chars) or the '?',
406/// depending on whether trigraphs are enabled or not.
407/// 2. If this is an escaped newline (potentially with whitespace between
408/// the backslash and newline), implicitly skip the newline and return
409/// the char after it.
410/// 3. If this is a UCN, return it. FIXME: C++ UCN's?
411///
412/// This handles the slow/uncommon case of the getCharAndSize method. Here we
413/// know that we can accumulate into Size, and that we have already incremented
414/// Ptr by Size bytes.
415///
416/// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
417/// be updated to match.
418///
419char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
Chris Lattnerd2177732007-07-20 16:59:19 +0000420 Token *Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000421 // If we have a slash, look for an escaped newline.
422 if (Ptr[0] == '\\') {
423 ++Size;
424 ++Ptr;
425Slash:
426 // Common case, backslash-char where the char is not whitespace.
427 if (!isWhitespace(Ptr[0])) return '\\';
428
429 // See if we have optional whitespace characters followed by a newline.
430 {
431 unsigned SizeTmp = 0;
432 do {
433 ++SizeTmp;
434 if (Ptr[SizeTmp-1] == '\n' || Ptr[SizeTmp-1] == '\r') {
435 // Remember that this token needs to be cleaned.
Chris Lattnerd2177732007-07-20 16:59:19 +0000436 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +0000437
438 // Warn if there was whitespace between the backslash and newline.
Chris Lattner74d15df2008-11-22 02:02:22 +0000439 if (SizeTmp != 1 && Tok && !isLexingRawMode())
Reid Spencer5f016e22007-07-11 17:01:13 +0000440 Diag(Ptr, diag::backslash_newline_space);
441
442 // If this is a \r\n or \n\r, skip the newlines.
443 if ((Ptr[SizeTmp] == '\r' || Ptr[SizeTmp] == '\n') &&
444 Ptr[SizeTmp-1] != Ptr[SizeTmp])
445 ++SizeTmp;
446
447 // Found backslash<whitespace><newline>. Parse the char after it.
448 Size += SizeTmp;
449 Ptr += SizeTmp;
450 // Use slow version to accumulate a correct size field.
451 return getCharAndSizeSlow(Ptr, Size, Tok);
452 }
453 } while (isWhitespace(Ptr[SizeTmp]));
454 }
455
456 // Otherwise, this is not an escaped newline, just return the slash.
457 return '\\';
458 }
459
460 // If this is a trigraph, process it.
461 if (Ptr[0] == '?' && Ptr[1] == '?') {
462 // If this is actually a legal trigraph (not something like "??x"), emit
463 // a trigraph warning. If so, and if trigraphs are enabled, return it.
464 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : 0)) {
465 // Remember that this token needs to be cleaned.
Chris Lattnerd2177732007-07-20 16:59:19 +0000466 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +0000467
468 Ptr += 3;
469 Size += 3;
470 if (C == '\\') goto Slash;
471 return C;
472 }
473 }
474
475 // If this is neither, return a single character.
476 ++Size;
477 return *Ptr;
478}
479
480
481/// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
482/// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
483/// and that we have already incremented Ptr by Size bytes.
484///
485/// NOTE: When this method is updated, getCharAndSizeSlow (above) should
486/// be updated to match.
487char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
488 const LangOptions &Features) {
489 // If we have a slash, look for an escaped newline.
490 if (Ptr[0] == '\\') {
491 ++Size;
492 ++Ptr;
493Slash:
494 // Common case, backslash-char where the char is not whitespace.
495 if (!isWhitespace(Ptr[0])) return '\\';
496
497 // See if we have optional whitespace characters followed by a newline.
498 {
499 unsigned SizeTmp = 0;
500 do {
501 ++SizeTmp;
502 if (Ptr[SizeTmp-1] == '\n' || Ptr[SizeTmp-1] == '\r') {
503
504 // If this is a \r\n or \n\r, skip the newlines.
505 if ((Ptr[SizeTmp] == '\r' || Ptr[SizeTmp] == '\n') &&
506 Ptr[SizeTmp-1] != Ptr[SizeTmp])
507 ++SizeTmp;
508
509 // Found backslash<whitespace><newline>. Parse the char after it.
510 Size += SizeTmp;
511 Ptr += SizeTmp;
512
513 // Use slow version to accumulate a correct size field.
514 return getCharAndSizeSlowNoWarn(Ptr, Size, Features);
515 }
516 } while (isWhitespace(Ptr[SizeTmp]));
517 }
518
519 // Otherwise, this is not an escaped newline, just return the slash.
520 return '\\';
521 }
522
523 // If this is a trigraph, process it.
524 if (Features.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
525 // If this is actually a legal trigraph (not something like "??x"), return
526 // it.
527 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
528 Ptr += 3;
529 Size += 3;
530 if (C == '\\') goto Slash;
531 return C;
532 }
533 }
534
535 // If this is neither, return a single character.
536 ++Size;
537 return *Ptr;
538}
539
540//===----------------------------------------------------------------------===//
541// Helper methods for lexing.
542//===----------------------------------------------------------------------===//
543
Chris Lattnerd2177732007-07-20 16:59:19 +0000544void Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000545 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
546 unsigned Size;
547 unsigned char C = *CurPtr++;
548 while (isIdentifierBody(C)) {
549 C = *CurPtr++;
550 }
551 --CurPtr; // Back up over the skipped character.
552
553 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
554 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
555 // FIXME: UCNs.
556 if (C != '\\' && C != '?' && (C != '$' || !Features.DollarIdents)) {
557FinishIdentifier:
558 const char *IdStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +0000559 FormTokenWithChars(Result, CurPtr, tok::identifier);
Reid Spencer5f016e22007-07-11 17:01:13 +0000560
561 // If we are in raw mode, return this identifier raw. There is no need to
562 // look up identifier information or attempt to macro expand it.
563 if (LexingRawMode) return;
564
565 // Fill in Result.IdentifierInfo, looking up the identifier in the
566 // identifier table.
Chris Lattnerd1186fa2009-01-21 07:45:14 +0000567 IdentifierInfo *II = PP->LookUpIdentifierInfo(Result, IdStart);
Reid Spencer5f016e22007-07-11 17:01:13 +0000568
Chris Lattner863c4862009-01-23 18:35:48 +0000569 // Change the kind of this identifier to the appropriate token kind, e.g.
570 // turning "for" into a keyword.
571 Result.setKind(II->getTokenID());
572
Reid Spencer5f016e22007-07-11 17:01:13 +0000573 // Finally, now that we know we have an identifier, pass this off to the
574 // preprocessor, which may macro expand it or something.
Chris Lattnerd1186fa2009-01-21 07:45:14 +0000575 if (II->isHandleIdentifierCase())
Chris Lattner6a170eb2009-01-21 07:43:11 +0000576 PP->HandleIdentifier(Result);
577 return;
Reid Spencer5f016e22007-07-11 17:01:13 +0000578 }
579
580 // Otherwise, $,\,? in identifier found. Enter slower path.
581
582 C = getCharAndSize(CurPtr, Size);
583 while (1) {
584 if (C == '$') {
585 // If we hit a $ and they are not supported in identifiers, we are done.
586 if (!Features.DollarIdents) goto FinishIdentifier;
587
588 // Otherwise, emit a diagnostic and continue.
Chris Lattner74d15df2008-11-22 02:02:22 +0000589 if (!isLexingRawMode())
590 Diag(CurPtr, diag::ext_dollar_in_identifier);
Reid Spencer5f016e22007-07-11 17:01:13 +0000591 CurPtr = ConsumeChar(CurPtr, Size, Result);
592 C = getCharAndSize(CurPtr, Size);
593 continue;
594 } else if (!isIdentifierBody(C)) { // FIXME: UCNs.
595 // Found end of identifier.
596 goto FinishIdentifier;
597 }
598
599 // Otherwise, this character is good, consume it.
600 CurPtr = ConsumeChar(CurPtr, Size, Result);
601
602 C = getCharAndSize(CurPtr, Size);
603 while (isIdentifierBody(C)) { // FIXME: UCNs.
604 CurPtr = ConsumeChar(CurPtr, Size, Result);
605 C = getCharAndSize(CurPtr, Size);
606 }
607 }
608}
609
610
Nate Begeman5253c7f2008-04-14 02:26:39 +0000611/// LexNumericConstant - Lex the remainder of a integer or floating point
Reid Spencer5f016e22007-07-11 17:01:13 +0000612/// constant. From[-1] is the first character lexed. Return the end of the
613/// constant.
Chris Lattnerd2177732007-07-20 16:59:19 +0000614void Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000615 unsigned Size;
616 char C = getCharAndSize(CurPtr, Size);
617 char PrevCh = 0;
618 while (isNumberBody(C)) { // FIXME: UCNs?
619 CurPtr = ConsumeChar(CurPtr, Size, Result);
620 PrevCh = C;
621 C = getCharAndSize(CurPtr, Size);
622 }
623
624 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
625 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e'))
626 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
627
628 // If we have a hex FP constant, continue.
Chris Lattner49842122008-11-22 07:39:03 +0000629 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p') &&
630 (Features.HexFloats || !Features.NoExtensions))
Reid Spencer5f016e22007-07-11 17:01:13 +0000631 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
632
Reid Spencer5f016e22007-07-11 17:01:13 +0000633 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +0000634 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +0000635 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
Chris Lattner47246be2009-01-26 19:29:26 +0000636 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +0000637}
638
639/// LexStringLiteral - Lex the remainder of a string literal, after having lexed
640/// either " or L".
Chris Lattnerd88dc482008-10-12 04:05:48 +0000641void Lexer::LexStringLiteral(Token &Result, const char *CurPtr, bool Wide) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000642 const char *NulCharacter = 0; // Does this string contain the \0 character?
643
644 char C = getAndAdvanceChar(CurPtr, Result);
645 while (C != '"') {
646 // Skip escaped characters.
647 if (C == '\\') {
648 // Skip the escaped character.
649 C = getAndAdvanceChar(CurPtr, Result);
650 } else if (C == '\n' || C == '\r' || // Newline.
651 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Chris Lattner33ab3f62009-03-18 21:10:12 +0000652 if (!isLexingRawMode() && !Features.AsmPreprocessor)
Chris Lattner74d15df2008-11-22 02:02:22 +0000653 Diag(BufferPtr, diag::err_unterminated_string);
Chris Lattner9e6293d2008-10-12 04:51:35 +0000654 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Reid Spencer5f016e22007-07-11 17:01:13 +0000655 return;
656 } else if (C == 0) {
657 NulCharacter = CurPtr-1;
658 }
659 C = getAndAdvanceChar(CurPtr, Result);
660 }
661
662 // If a nul character existed in the string, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +0000663 if (NulCharacter && !isLexingRawMode())
664 Diag(NulCharacter, diag::null_in_string);
Reid Spencer5f016e22007-07-11 17:01:13 +0000665
Reid Spencer5f016e22007-07-11 17:01:13 +0000666 // Update the location of the token as well as the BufferPtr instance var.
Chris Lattner47246be2009-01-26 19:29:26 +0000667 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +0000668 FormTokenWithChars(Result, CurPtr,
669 Wide ? tok::wide_string_literal : tok::string_literal);
Chris Lattner47246be2009-01-26 19:29:26 +0000670 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +0000671}
672
673/// LexAngledStringLiteral - Lex the remainder of an angled string literal,
674/// after having lexed the '<' character. This is used for #include filenames.
Chris Lattnerd2177732007-07-20 16:59:19 +0000675void Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000676 const char *NulCharacter = 0; // Does this string contain the \0 character?
Chris Lattner9cb51ce2009-04-17 23:56:52 +0000677 const char *AfterLessPos = CurPtr;
Reid Spencer5f016e22007-07-11 17:01:13 +0000678 char C = getAndAdvanceChar(CurPtr, Result);
679 while (C != '>') {
680 // Skip escaped characters.
681 if (C == '\\') {
682 // Skip the escaped character.
683 C = getAndAdvanceChar(CurPtr, Result);
684 } else if (C == '\n' || C == '\r' || // Newline.
685 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Chris Lattner9cb51ce2009-04-17 23:56:52 +0000686 // If the filename is unterminated, then it must just be a lone <
687 // character. Return this as such.
688 FormTokenWithChars(Result, AfterLessPos, tok::less);
Reid Spencer5f016e22007-07-11 17:01:13 +0000689 return;
690 } else if (C == 0) {
691 NulCharacter = CurPtr-1;
692 }
693 C = getAndAdvanceChar(CurPtr, Result);
694 }
695
696 // If a nul character existed in the string, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +0000697 if (NulCharacter && !isLexingRawMode())
698 Diag(NulCharacter, diag::null_in_string);
Reid Spencer5f016e22007-07-11 17:01:13 +0000699
Reid Spencer5f016e22007-07-11 17:01:13 +0000700 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +0000701 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +0000702 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
Chris Lattner47246be2009-01-26 19:29:26 +0000703 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +0000704}
705
706
707/// LexCharConstant - Lex the remainder of a character constant, after having
708/// lexed either ' or L'.
Chris Lattnerd2177732007-07-20 16:59:19 +0000709void Lexer::LexCharConstant(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000710 const char *NulCharacter = 0; // Does this character contain the \0 character?
711
712 // Handle the common case of 'x' and '\y' efficiently.
713 char C = getAndAdvanceChar(CurPtr, Result);
714 if (C == '\'') {
Chris Lattner33ab3f62009-03-18 21:10:12 +0000715 if (!isLexingRawMode() && !Features.AsmPreprocessor)
Chris Lattner74d15df2008-11-22 02:02:22 +0000716 Diag(BufferPtr, diag::err_empty_character);
Chris Lattner9e6293d2008-10-12 04:51:35 +0000717 FormTokenWithChars(Result, CurPtr, tok::unknown);
Reid Spencer5f016e22007-07-11 17:01:13 +0000718 return;
719 } else if (C == '\\') {
720 // Skip the escaped character.
721 // FIXME: UCN's.
722 C = getAndAdvanceChar(CurPtr, Result);
723 }
724
725 if (C && C != '\n' && C != '\r' && CurPtr[0] == '\'') {
726 ++CurPtr;
727 } else {
728 // Fall back on generic code for embedded nulls, newlines, wide chars.
729 do {
730 // Skip escaped characters.
731 if (C == '\\') {
732 // Skip the escaped character.
733 C = getAndAdvanceChar(CurPtr, Result);
734 } else if (C == '\n' || C == '\r' || // Newline.
735 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Chris Lattner33ab3f62009-03-18 21:10:12 +0000736 if (!isLexingRawMode() && !Features.AsmPreprocessor)
Chris Lattner74d15df2008-11-22 02:02:22 +0000737 Diag(BufferPtr, diag::err_unterminated_char);
Chris Lattner9e6293d2008-10-12 04:51:35 +0000738 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Reid Spencer5f016e22007-07-11 17:01:13 +0000739 return;
740 } else if (C == 0) {
741 NulCharacter = CurPtr-1;
742 }
743 C = getAndAdvanceChar(CurPtr, Result);
744 } while (C != '\'');
745 }
746
Chris Lattner74d15df2008-11-22 02:02:22 +0000747 if (NulCharacter && !isLexingRawMode())
748 Diag(NulCharacter, diag::null_in_char);
Reid Spencer5f016e22007-07-11 17:01:13 +0000749
Reid Spencer5f016e22007-07-11 17:01:13 +0000750 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +0000751 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +0000752 FormTokenWithChars(Result, CurPtr, tok::char_constant);
Chris Lattner47246be2009-01-26 19:29:26 +0000753 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +0000754}
755
756/// SkipWhitespace - Efficiently skip over a series of whitespace characters.
757/// Update BufferPtr to point to the next non-whitespace character and return.
Chris Lattnerd88dc482008-10-12 04:05:48 +0000758///
759/// This method forms a token and returns true if KeepWhitespaceMode is enabled.
760///
761bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000762 // Whitespace - Skip it, then return the token after the whitespace.
763 unsigned char Char = *CurPtr; // Skip consequtive spaces efficiently.
764 while (1) {
765 // Skip horizontal whitespace very aggressively.
766 while (isHorizontalWhitespace(Char))
767 Char = *++CurPtr;
768
Daniel Dunbarddd3e8b2008-11-25 00:20:22 +0000769 // Otherwise if we have something other than whitespace, we're done.
Reid Spencer5f016e22007-07-11 17:01:13 +0000770 if (Char != '\n' && Char != '\r')
771 break;
772
773 if (ParsingPreprocessorDirective) {
774 // End of preprocessor directive line, let LexTokenInternal handle this.
775 BufferPtr = CurPtr;
Chris Lattnerd88dc482008-10-12 04:05:48 +0000776 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000777 }
778
779 // ok, but handle newline.
780 // The returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +0000781 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +0000782 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +0000783 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +0000784 Char = *++CurPtr;
785 }
786
787 // If this isn't immediately after a newline, there is leading space.
788 char PrevChar = CurPtr[-1];
789 if (PrevChar != '\n' && PrevChar != '\r')
Chris Lattnerd2177732007-07-20 16:59:19 +0000790 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +0000791
Chris Lattnerd88dc482008-10-12 04:05:48 +0000792 // If the client wants us to return whitespace, return it now.
793 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +0000794 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd88dc482008-10-12 04:05:48 +0000795 return true;
796 }
797
Reid Spencer5f016e22007-07-11 17:01:13 +0000798 BufferPtr = CurPtr;
Chris Lattnerd88dc482008-10-12 04:05:48 +0000799 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000800}
801
802// SkipBCPLComment - We have just read the // characters from input. Skip until
803// we find the newline character thats terminate the comment. Then update
Chris Lattner2d381892008-10-12 04:15:42 +0000804/// BufferPtr and return. If we're in KeepCommentMode, this will form the token
805/// and return true.
Chris Lattnerd2177732007-07-20 16:59:19 +0000806bool Lexer::SkipBCPLComment(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000807 // If BCPL comments aren't explicitly enabled for this language, emit an
808 // extension warning.
Chris Lattner74d15df2008-11-22 02:02:22 +0000809 if (!Features.BCPLComment && !isLexingRawMode()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000810 Diag(BufferPtr, diag::ext_bcpl_comment);
811
812 // Mark them enabled so we only emit one warning for this translation
813 // unit.
814 Features.BCPLComment = true;
815 }
816
817 // Scan over the body of the comment. The common case, when scanning, is that
818 // the comment contains normal ascii characters with nothing interesting in
819 // them. As such, optimize for this case with the inner loop.
820 char C;
821 do {
822 C = *CurPtr;
823 // FIXME: Speedup BCPL comment lexing. Just scan for a \n or \r character.
824 // If we find a \n character, scan backwards, checking to see if it's an
825 // escaped newline, like we do for block comments.
826
827 // Skip over characters in the fast loop.
828 while (C != 0 && // Potentially EOF.
829 C != '\\' && // Potentially escaped newline.
830 C != '?' && // Potentially trigraph.
831 C != '\n' && C != '\r') // Newline or DOS-style newline.
832 C = *++CurPtr;
833
834 // If this is a newline, we're done.
835 if (C == '\n' || C == '\r')
836 break; // Found the newline? Break out!
837
838 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
Chris Lattnerbc3e9842008-12-12 07:34:39 +0000839 // properly decode the character. Read it in raw mode to avoid emitting
840 // diagnostics about things like trigraphs. If we see an escaped newline,
841 // we'll handle it below.
Reid Spencer5f016e22007-07-11 17:01:13 +0000842 const char *OldPtr = CurPtr;
Chris Lattnerbc3e9842008-12-12 07:34:39 +0000843 bool OldRawMode = isLexingRawMode();
844 LexingRawMode = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000845 C = getAndAdvanceChar(CurPtr, Result);
Chris Lattnerbc3e9842008-12-12 07:34:39 +0000846 LexingRawMode = OldRawMode;
Chris Lattneread616c2009-04-05 00:26:41 +0000847
848 // If the char that we finally got was a \n, then we must have had something
849 // like \<newline><newline>. We don't want to have consumed the second
850 // newline, we want CurPtr, to end up pointing to it down below.
851 if (C == '\n' || C == '\r') {
852 --CurPtr;
853 C = 'x'; // doesn't matter what this is.
854 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000855
856 // If we read multiple characters, and one of those characters was a \r or
857 // \n, then we had an escaped newline within the comment. Emit diagnostic
858 // unless the next line is also a // comment.
859 if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') {
860 for (; OldPtr != CurPtr; ++OldPtr)
861 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
862 // Okay, we found a // comment that ends in a newline, if the next
863 // line is also a // comment, but has spaces, don't emit a diagnostic.
864 if (isspace(C)) {
865 const char *ForwardPtr = CurPtr;
866 while (isspace(*ForwardPtr)) // Skip whitespace.
867 ++ForwardPtr;
868 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
869 break;
870 }
871
Chris Lattner74d15df2008-11-22 02:02:22 +0000872 if (!isLexingRawMode())
873 Diag(OldPtr-1, diag::ext_multi_line_bcpl_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +0000874 break;
875 }
876 }
877
878 if (CurPtr == BufferEnd+1) { --CurPtr; break; }
879 } while (C != '\n' && C != '\r');
880
881 // Found but did not consume the newline.
882
883 // If we are returning comments as tokens, return this comment as a token.
Chris Lattnerfa95a012008-10-12 03:22:02 +0000884 if (inKeepCommentMode())
Reid Spencer5f016e22007-07-11 17:01:13 +0000885 return SaveBCPLComment(Result, CurPtr);
886
887 // If we are inside a preprocessor directive and we see the end of line,
888 // return immediately, so that the lexer can return this as an EOM token.
889 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
890 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +0000891 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000892 }
893
894 // Otherwise, eat the \n character. We don't care if this is a \n\r or
Chris Lattner7a4f0042008-10-12 00:23:07 +0000895 // \r\n sequence. This is an efficiency hack (because we know the \n can't
Chris Lattnerd88dc482008-10-12 04:05:48 +0000896 // contribute to another token), it isn't needed for correctness. Note that
897 // this is ok even in KeepWhitespaceMode, because we would have returned the
898 /// comment above in that mode.
Reid Spencer5f016e22007-07-11 17:01:13 +0000899 ++CurPtr;
900
901 // The next returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +0000902 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +0000903 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +0000904 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +0000905 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +0000906 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000907}
908
909/// SaveBCPLComment - If in save-comment mode, package up this BCPL comment in
910/// an appropriate way and return it.
Chris Lattnerd2177732007-07-20 16:59:19 +0000911bool Lexer::SaveBCPLComment(Token &Result, const char *CurPtr) {
Chris Lattner9e6293d2008-10-12 04:51:35 +0000912 // If we're not in a preprocessor directive, just return the // comment
913 // directly.
914 FormTokenWithChars(Result, CurPtr, tok::comment);
Reid Spencer5f016e22007-07-11 17:01:13 +0000915
Chris Lattner9e6293d2008-10-12 04:51:35 +0000916 if (!ParsingPreprocessorDirective)
917 return true;
918
919 // If this BCPL-style comment is in a macro definition, transmogrify it into
920 // a C-style block comment.
921 std::string Spelling = PP->getSpelling(Result);
922 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not bcpl comment?");
923 Spelling[1] = '*'; // Change prefix to "/*".
924 Spelling += "*/"; // add suffix.
925
926 Result.setKind(tok::comment);
Chris Lattner47246be2009-01-26 19:29:26 +0000927 PP->CreateString(&Spelling[0], Spelling.size(), Result,
928 Result.getLocation());
Chris Lattner2d381892008-10-12 04:15:42 +0000929 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000930}
931
932/// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
933/// character (either \n or \r) is part of an escaped newline sequence. Issue a
Chris Lattner47a2b402008-12-12 07:14:34 +0000934/// diagnostic if so. We know that the newline is inside of a block comment.
Reid Spencer5f016e22007-07-11 17:01:13 +0000935static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
936 Lexer *L) {
937 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
938
939 // Back up off the newline.
940 --CurPtr;
941
942 // If this is a two-character newline sequence, skip the other character.
943 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
944 // \n\n or \r\r -> not escaped newline.
945 if (CurPtr[0] == CurPtr[1])
946 return false;
947 // \n\r or \r\n -> skip the newline.
948 --CurPtr;
949 }
950
951 // If we have horizontal whitespace, skip over it. We allow whitespace
952 // between the slash and newline.
953 bool HasSpace = false;
954 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
955 --CurPtr;
956 HasSpace = true;
957 }
958
959 // If we have a slash, we know this is an escaped newline.
960 if (*CurPtr == '\\') {
961 if (CurPtr[-1] != '*') return false;
962 } else {
963 // It isn't a slash, is it the ?? / trigraph?
964 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
965 CurPtr[-3] != '*')
966 return false;
967
968 // This is the trigraph ending the comment. Emit a stern warning!
969 CurPtr -= 2;
970
971 // If no trigraphs are enabled, warn that we ignored this trigraph and
972 // ignore this * character.
973 if (!L->getFeatures().Trigraphs) {
Chris Lattner74d15df2008-11-22 02:02:22 +0000974 if (!L->isLexingRawMode())
975 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +0000976 return false;
977 }
Chris Lattner74d15df2008-11-22 02:02:22 +0000978 if (!L->isLexingRawMode())
979 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +0000980 }
981
982 // Warn about having an escaped newline between the */ characters.
Chris Lattner74d15df2008-11-22 02:02:22 +0000983 if (!L->isLexingRawMode())
984 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
Reid Spencer5f016e22007-07-11 17:01:13 +0000985
986 // If there was space between the backslash and newline, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +0000987 if (HasSpace && !L->isLexingRawMode())
988 L->Diag(CurPtr, diag::backslash_newline_space);
Reid Spencer5f016e22007-07-11 17:01:13 +0000989
990 return true;
991}
992
993#ifdef __SSE2__
994#include <emmintrin.h>
995#elif __ALTIVEC__
996#include <altivec.h>
997#undef bool
998#endif
999
1000/// SkipBlockComment - We have just read the /* characters from input. Read
1001/// until we find the */ characters that terminate the comment. Note that we
1002/// don't bother decoding trigraphs or escaped newlines in block comments,
1003/// because they cannot cause the comment to end. The only thing that can
1004/// happen is the comment could end with an escaped newline between the */ end
1005/// of comment.
Chris Lattner2d381892008-10-12 04:15:42 +00001006///
1007/// If KeepCommentMode is enabled, this forms a token from the comment and
1008/// returns true.
Chris Lattnerd2177732007-07-20 16:59:19 +00001009bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001010 // Scan one character past where we should, looking for a '/' character. Once
1011 // we find it, check to see if it was preceeded by a *. This common
1012 // optimization helps people who like to put a lot of * characters in their
1013 // comments.
Chris Lattner8146b682007-07-21 23:43:37 +00001014
1015 // The first character we get with newlines and trigraphs skipped to handle
1016 // the degenerate /*/ case below correctly if the * has an escaped newline
1017 // after it.
1018 unsigned CharSize;
1019 unsigned char C = getCharAndSize(CurPtr, CharSize);
1020 CurPtr += CharSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001021 if (C == 0 && CurPtr == BufferEnd+1) {
Chris Lattner74d15df2008-11-22 02:02:22 +00001022 if (!isLexingRawMode())
Chris Lattner0af57422008-10-12 01:31:51 +00001023 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner31f0eca2008-10-12 04:19:49 +00001024 --CurPtr;
1025
1026 // KeepWhitespaceMode should return this broken comment as a token. Since
1027 // it isn't a well formed comment, just return it as an 'unknown' token.
1028 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001029 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner31f0eca2008-10-12 04:19:49 +00001030 return true;
1031 }
1032
1033 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001034 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001035 }
1036
Chris Lattner8146b682007-07-21 23:43:37 +00001037 // Check to see if the first character after the '/*' is another /. If so,
1038 // then this slash does not end the block comment, it is part of it.
1039 if (C == '/')
1040 C = *CurPtr++;
1041
Reid Spencer5f016e22007-07-11 17:01:13 +00001042 while (1) {
1043 // Skip over all non-interesting characters until we find end of buffer or a
1044 // (probably ending) '/' character.
1045 if (CurPtr + 24 < BufferEnd) {
1046 // While not aligned to a 16-byte boundary.
1047 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
1048 C = *CurPtr++;
1049
1050 if (C == '/') goto FoundSlash;
1051
1052#ifdef __SSE2__
1053 __m128i Slashes = _mm_set_epi8('/', '/', '/', '/', '/', '/', '/', '/',
1054 '/', '/', '/', '/', '/', '/', '/', '/');
1055 while (CurPtr+16 <= BufferEnd &&
1056 _mm_movemask_epi8(_mm_cmpeq_epi8(*(__m128i*)CurPtr, Slashes)) == 0)
1057 CurPtr += 16;
1058#elif __ALTIVEC__
1059 __vector unsigned char Slashes = {
1060 '/', '/', '/', '/', '/', '/', '/', '/',
1061 '/', '/', '/', '/', '/', '/', '/', '/'
1062 };
1063 while (CurPtr+16 <= BufferEnd &&
1064 !vec_any_eq(*(vector unsigned char*)CurPtr, Slashes))
1065 CurPtr += 16;
1066#else
1067 // Scan for '/' quickly. Many block comments are very large.
1068 while (CurPtr[0] != '/' &&
1069 CurPtr[1] != '/' &&
1070 CurPtr[2] != '/' &&
1071 CurPtr[3] != '/' &&
1072 CurPtr+4 < BufferEnd) {
1073 CurPtr += 4;
1074 }
1075#endif
1076
1077 // It has to be one of the bytes scanned, increment to it and read one.
1078 C = *CurPtr++;
1079 }
1080
1081 // Loop to scan the remainder.
1082 while (C != '/' && C != '\0')
1083 C = *CurPtr++;
1084
1085 FoundSlash:
1086 if (C == '/') {
1087 if (CurPtr[-2] == '*') // We found the final */. We're done!
1088 break;
1089
1090 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
1091 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
1092 // We found the final */, though it had an escaped newline between the
1093 // * and /. We're done!
1094 break;
1095 }
1096 }
1097 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
1098 // If this is a /* inside of the comment, emit a warning. Don't do this
1099 // if this is a /*/, which will end the comment. This misses cases with
1100 // embedded escaped newlines, but oh well.
Chris Lattner74d15df2008-11-22 02:02:22 +00001101 if (!isLexingRawMode())
1102 Diag(CurPtr-1, diag::warn_nested_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001103 }
1104 } else if (C == 0 && CurPtr == BufferEnd+1) {
Chris Lattner74d15df2008-11-22 02:02:22 +00001105 if (!isLexingRawMode())
1106 Diag(BufferPtr, diag::err_unterminated_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001107 // Note: the user probably forgot a */. We could continue immediately
1108 // after the /*, but this would involve lexing a lot of what really is the
1109 // comment, which surely would confuse the parser.
Chris Lattner31f0eca2008-10-12 04:19:49 +00001110 --CurPtr;
1111
1112 // KeepWhitespaceMode should return this broken comment as a token. Since
1113 // it isn't a well formed comment, just return it as an 'unknown' token.
1114 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001115 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner31f0eca2008-10-12 04:19:49 +00001116 return true;
1117 }
1118
1119 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001120 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001121 }
1122 C = *CurPtr++;
1123 }
1124
1125 // If we are returning comments as tokens, return this comment as a token.
Chris Lattnerfa95a012008-10-12 03:22:02 +00001126 if (inKeepCommentMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001127 FormTokenWithChars(Result, CurPtr, tok::comment);
Chris Lattner2d381892008-10-12 04:15:42 +00001128 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001129 }
1130
1131 // It is common for the tokens immediately after a /**/ comment to be
1132 // whitespace. Instead of going through the big switch, handle it
Chris Lattnerd88dc482008-10-12 04:05:48 +00001133 // efficiently now. This is safe even in KeepWhitespaceMode because we would
1134 // have already returned above with the comment as a token.
Reid Spencer5f016e22007-07-11 17:01:13 +00001135 if (isHorizontalWhitespace(*CurPtr)) {
Chris Lattnerd2177732007-07-20 16:59:19 +00001136 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001137 SkipWhitespace(Result, CurPtr+1);
Chris Lattner2d381892008-10-12 04:15:42 +00001138 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001139 }
1140
1141 // Otherwise, just return so that the next character will be lexed as a token.
1142 BufferPtr = CurPtr;
Chris Lattnerd2177732007-07-20 16:59:19 +00001143 Result.setFlag(Token::LeadingSpace);
Chris Lattner2d381892008-10-12 04:15:42 +00001144 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001145}
1146
1147//===----------------------------------------------------------------------===//
1148// Primary Lexing Entry Points
1149//===----------------------------------------------------------------------===//
1150
Reid Spencer5f016e22007-07-11 17:01:13 +00001151/// ReadToEndOfLine - Read the rest of the current preprocessor line as an
1152/// uninterpreted string. This switches the lexer out of directive mode.
1153std::string Lexer::ReadToEndOfLine() {
1154 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
1155 "Must be in a preprocessing directive!");
1156 std::string Result;
Chris Lattnerd2177732007-07-20 16:59:19 +00001157 Token Tmp;
Reid Spencer5f016e22007-07-11 17:01:13 +00001158
1159 // CurPtr - Cache BufferPtr in an automatic variable.
1160 const char *CurPtr = BufferPtr;
1161 while (1) {
1162 char Char = getAndAdvanceChar(CurPtr, Tmp);
1163 switch (Char) {
1164 default:
1165 Result += Char;
1166 break;
1167 case 0: // Null.
1168 // Found end of file?
1169 if (CurPtr-1 != BufferEnd) {
1170 // Nope, normal character, continue.
1171 Result += Char;
1172 break;
1173 }
1174 // FALL THROUGH.
1175 case '\r':
1176 case '\n':
1177 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
1178 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
1179 BufferPtr = CurPtr-1;
1180
1181 // Next, lex the character, which should handle the EOM transition.
1182 Lex(Tmp);
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001183 assert(Tmp.is(tok::eom) && "Unexpected token!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001184
1185 // Finally, we're done, return the string we found.
1186 return Result;
1187 }
1188 }
1189}
1190
1191/// LexEndOfFile - CurPtr points to the end of this file. Handle this
1192/// condition, reporting diagnostics and handling other edge cases as required.
1193/// This returns true if Result contains a token, false if PP.Lex should be
1194/// called again.
Chris Lattnerd2177732007-07-20 16:59:19 +00001195bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001196 // If we hit the end of the file while parsing a preprocessor directive,
1197 // end the preprocessor directive first. The next token returned will
1198 // then be the end of file.
1199 if (ParsingPreprocessorDirective) {
1200 // Done parsing the "line".
1201 ParsingPreprocessorDirective = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001202 // Update the location of token as well as BufferPtr.
Chris Lattner9e6293d2008-10-12 04:51:35 +00001203 FormTokenWithChars(Result, CurPtr, tok::eom);
Reid Spencer5f016e22007-07-11 17:01:13 +00001204
1205 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattnerf744d132008-10-12 03:27:19 +00001206 SetCommentRetentionState(PP->getCommentRetentionState());
Reid Spencer5f016e22007-07-11 17:01:13 +00001207 return true; // Have a token.
1208 }
1209
1210 // If we are in raw mode, return this event as an EOF token. Let the caller
1211 // that put us in raw mode handle the event.
Chris Lattner74d15df2008-11-22 02:02:22 +00001212 if (isLexingRawMode()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001213 Result.startToken();
1214 BufferPtr = BufferEnd;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001215 FormTokenWithChars(Result, BufferEnd, tok::eof);
Reid Spencer5f016e22007-07-11 17:01:13 +00001216 return true;
1217 }
1218
1219 // Otherwise, issue diagnostics for unterminated #if and missing newline.
1220
1221 // If we are in a #if directive, emit an error.
1222 while (!ConditionalStack.empty()) {
Chris Lattner30c64762008-11-22 06:22:39 +00001223 PP->Diag(ConditionalStack.back().IfLoc,
1224 diag::err_pp_unterminated_conditional);
Reid Spencer5f016e22007-07-11 17:01:13 +00001225 ConditionalStack.pop_back();
1226 }
1227
Chris Lattnerb25e5d72008-04-12 05:54:25 +00001228 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
1229 // a pedwarn.
1230 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r'))
Mike Stump20d0ee52009-04-02 02:29:42 +00001231 Diag(BufferEnd, diag::ext_no_newline_eof)
1232 << CodeModificationHint::CreateInsertion(getSourceLocation(BufferEnd),
1233 "\n");
Reid Spencer5f016e22007-07-11 17:01:13 +00001234
1235 BufferPtr = CurPtr;
1236
1237 // Finally, let the preprocessor handle this.
Chris Lattner168ae2d2007-10-17 20:41:00 +00001238 return PP->HandleEndOfFile(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001239}
1240
1241/// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
1242/// the specified lexer will return a tok::l_paren token, 0 if it is something
1243/// else and 2 if there are no more tokens in the buffer controlled by the
1244/// lexer.
1245unsigned Lexer::isNextPPTokenLParen() {
1246 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
1247
1248 // Switch to 'skipping' mode. This will ensure that we can lex a token
1249 // without emitting diagnostics, disables macro expansion, and will cause EOF
1250 // to return an EOF token instead of popping the include stack.
1251 LexingRawMode = true;
1252
1253 // Save state that can be changed while lexing so that we can restore it.
1254 const char *TmpBufferPtr = BufferPtr;
1255
Chris Lattnerd2177732007-07-20 16:59:19 +00001256 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001257 Tok.startToken();
1258 LexTokenInternal(Tok);
1259
1260 // Restore state that may have changed.
1261 BufferPtr = TmpBufferPtr;
1262
1263 // Restore the lexer back to non-skipping mode.
1264 LexingRawMode = false;
1265
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001266 if (Tok.is(tok::eof))
Reid Spencer5f016e22007-07-11 17:01:13 +00001267 return 2;
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001268 return Tok.is(tok::l_paren);
Reid Spencer5f016e22007-07-11 17:01:13 +00001269}
1270
1271
1272/// LexTokenInternal - This implements a simple C family lexer. It is an
1273/// extremely performance critical piece of code. This assumes that the buffer
1274/// has a null character at the end of the file. Return true if an error
1275/// occurred and compilation should terminate, false if normal. This returns a
1276/// preprocessing token, not a normal token, as such, it is an internal
1277/// interface. It assumes that the Flags of result have been cleared before
1278/// calling this.
Chris Lattnerd2177732007-07-20 16:59:19 +00001279void Lexer::LexTokenInternal(Token &Result) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001280LexNextToken:
1281 // New token, can't need cleaning yet.
Chris Lattnerd2177732007-07-20 16:59:19 +00001282 Result.clearFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00001283 Result.setIdentifierInfo(0);
1284
1285 // CurPtr - Cache BufferPtr in an automatic variable.
1286 const char *CurPtr = BufferPtr;
1287
1288 // Small amounts of horizontal whitespace is very common between tokens.
1289 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
1290 ++CurPtr;
1291 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
1292 ++CurPtr;
Chris Lattnerd88dc482008-10-12 04:05:48 +00001293
1294 // If we are keeping whitespace and other tokens, just return what we just
1295 // skipped. The next lexer invocation will return the token after the
1296 // whitespace.
1297 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001298 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd88dc482008-10-12 04:05:48 +00001299 return;
1300 }
1301
Reid Spencer5f016e22007-07-11 17:01:13 +00001302 BufferPtr = CurPtr;
Chris Lattnerd2177732007-07-20 16:59:19 +00001303 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001304 }
1305
1306 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
1307
1308 // Read a character, advancing over it.
1309 char Char = getAndAdvanceChar(CurPtr, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001310 tok::TokenKind Kind;
1311
Reid Spencer5f016e22007-07-11 17:01:13 +00001312 switch (Char) {
1313 case 0: // Null.
1314 // Found end of file?
1315 if (CurPtr-1 == BufferEnd) {
1316 // Read the PP instance variable into an automatic variable, because
1317 // LexEndOfFile will often delete 'this'.
Chris Lattner168ae2d2007-10-17 20:41:00 +00001318 Preprocessor *PPCache = PP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001319 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
1320 return; // Got a token to return.
Chris Lattner168ae2d2007-10-17 20:41:00 +00001321 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
1322 return PPCache->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001323 }
1324
Chris Lattner74d15df2008-11-22 02:02:22 +00001325 if (!isLexingRawMode())
1326 Diag(CurPtr-1, diag::null_in_file);
Chris Lattnerd2177732007-07-20 16:59:19 +00001327 Result.setFlag(Token::LeadingSpace);
Chris Lattnerd88dc482008-10-12 04:05:48 +00001328 if (SkipWhitespace(Result, CurPtr))
1329 return; // KeepWhitespaceMode
1330
Reid Spencer5f016e22007-07-11 17:01:13 +00001331 goto LexNextToken; // GCC isn't tail call eliminating.
1332 case '\n':
1333 case '\r':
1334 // If we are inside a preprocessor directive and we see the end of line,
1335 // we know we are done with the directive, so return an EOM token.
1336 if (ParsingPreprocessorDirective) {
1337 // Done parsing the "line".
1338 ParsingPreprocessorDirective = false;
1339
1340 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattnerf744d132008-10-12 03:27:19 +00001341 SetCommentRetentionState(PP->getCommentRetentionState());
Reid Spencer5f016e22007-07-11 17:01:13 +00001342
1343 // Since we consumed a newline, we are back at the start of a line.
1344 IsAtStartOfLine = true;
1345
Chris Lattner9e6293d2008-10-12 04:51:35 +00001346 Kind = tok::eom;
Reid Spencer5f016e22007-07-11 17:01:13 +00001347 break;
1348 }
1349 // The returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00001350 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00001351 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00001352 Result.clearFlag(Token::LeadingSpace);
Chris Lattnerd88dc482008-10-12 04:05:48 +00001353
1354 if (SkipWhitespace(Result, CurPtr))
1355 return; // KeepWhitespaceMode
Reid Spencer5f016e22007-07-11 17:01:13 +00001356 goto LexNextToken; // GCC isn't tail call eliminating.
1357 case ' ':
1358 case '\t':
1359 case '\f':
1360 case '\v':
Chris Lattner8133cfc2007-07-22 06:29:05 +00001361 SkipHorizontalWhitespace:
Chris Lattnerd2177732007-07-20 16:59:19 +00001362 Result.setFlag(Token::LeadingSpace);
Chris Lattnerd88dc482008-10-12 04:05:48 +00001363 if (SkipWhitespace(Result, CurPtr))
1364 return; // KeepWhitespaceMode
Chris Lattner8133cfc2007-07-22 06:29:05 +00001365
1366 SkipIgnoredUnits:
1367 CurPtr = BufferPtr;
1368
1369 // If the next token is obviously a // or /* */ comment, skip it efficiently
1370 // too (without going through the big switch stmt).
Chris Lattner8402c732009-01-16 22:39:25 +00001371 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
1372 Features.BCPLComment) {
Chris Lattner8133cfc2007-07-22 06:29:05 +00001373 SkipBCPLComment(Result, CurPtr+2);
1374 goto SkipIgnoredUnits;
Chris Lattnerfa95a012008-10-12 03:22:02 +00001375 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
Chris Lattner8133cfc2007-07-22 06:29:05 +00001376 SkipBlockComment(Result, CurPtr+2);
1377 goto SkipIgnoredUnits;
1378 } else if (isHorizontalWhitespace(*CurPtr)) {
1379 goto SkipHorizontalWhitespace;
1380 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001381 goto LexNextToken; // GCC isn't tail call eliminating.
1382
Chris Lattner3a570772008-01-03 17:58:54 +00001383 // C99 6.4.4.1: Integer Constants.
1384 // C99 6.4.4.2: Floating Constants.
1385 case '0': case '1': case '2': case '3': case '4':
1386 case '5': case '6': case '7': case '8': case '9':
1387 // Notify MIOpt that we read a non-whitespace/non-comment token.
1388 MIOpt.ReadToken();
1389 return LexNumericConstant(Result, CurPtr);
1390
1391 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
Reid Spencer5f016e22007-07-11 17:01:13 +00001392 // Notify MIOpt that we read a non-whitespace/non-comment token.
1393 MIOpt.ReadToken();
1394 Char = getCharAndSize(CurPtr, SizeTmp);
1395
1396 // Wide string literal.
1397 if (Char == '"')
1398 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
1399 true);
1400
1401 // Wide character constant.
1402 if (Char == '\'')
1403 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
1404 // FALL THROUGH, treating L like the start of an identifier.
1405
1406 // C99 6.4.2: Identifiers.
1407 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
1408 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
1409 case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U':
1410 case 'V': case 'W': case 'X': case 'Y': case 'Z':
1411 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
1412 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
1413 case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u':
1414 case 'v': case 'w': case 'x': case 'y': case 'z':
1415 case '_':
1416 // Notify MIOpt that we read a non-whitespace/non-comment token.
1417 MIOpt.ReadToken();
1418 return LexIdentifier(Result, CurPtr);
Chris Lattner3a570772008-01-03 17:58:54 +00001419
1420 case '$': // $ in identifiers.
1421 if (Features.DollarIdents) {
Chris Lattner74d15df2008-11-22 02:02:22 +00001422 if (!isLexingRawMode())
1423 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
Chris Lattner3a570772008-01-03 17:58:54 +00001424 // Notify MIOpt that we read a non-whitespace/non-comment token.
1425 MIOpt.ReadToken();
1426 return LexIdentifier(Result, CurPtr);
1427 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001428
Chris Lattner9e6293d2008-10-12 04:51:35 +00001429 Kind = tok::unknown;
Chris Lattner3a570772008-01-03 17:58:54 +00001430 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001431
1432 // C99 6.4.4: Character Constants.
1433 case '\'':
1434 // Notify MIOpt that we read a non-whitespace/non-comment token.
1435 MIOpt.ReadToken();
1436 return LexCharConstant(Result, CurPtr);
1437
1438 // C99 6.4.5: String Literals.
1439 case '"':
1440 // Notify MIOpt that we read a non-whitespace/non-comment token.
1441 MIOpt.ReadToken();
1442 return LexStringLiteral(Result, CurPtr, false);
1443
1444 // C99 6.4.6: Punctuators.
1445 case '?':
Chris Lattner9e6293d2008-10-12 04:51:35 +00001446 Kind = tok::question;
Reid Spencer5f016e22007-07-11 17:01:13 +00001447 break;
1448 case '[':
Chris Lattner9e6293d2008-10-12 04:51:35 +00001449 Kind = tok::l_square;
Reid Spencer5f016e22007-07-11 17:01:13 +00001450 break;
1451 case ']':
Chris Lattner9e6293d2008-10-12 04:51:35 +00001452 Kind = tok::r_square;
Reid Spencer5f016e22007-07-11 17:01:13 +00001453 break;
1454 case '(':
Chris Lattner9e6293d2008-10-12 04:51:35 +00001455 Kind = tok::l_paren;
Reid Spencer5f016e22007-07-11 17:01:13 +00001456 break;
1457 case ')':
Chris Lattner9e6293d2008-10-12 04:51:35 +00001458 Kind = tok::r_paren;
Reid Spencer5f016e22007-07-11 17:01:13 +00001459 break;
1460 case '{':
Chris Lattner9e6293d2008-10-12 04:51:35 +00001461 Kind = tok::l_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00001462 break;
1463 case '}':
Chris Lattner9e6293d2008-10-12 04:51:35 +00001464 Kind = tok::r_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00001465 break;
1466 case '.':
1467 Char = getCharAndSize(CurPtr, SizeTmp);
1468 if (Char >= '0' && Char <= '9') {
1469 // Notify MIOpt that we read a non-whitespace/non-comment token.
1470 MIOpt.ReadToken();
1471
1472 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
1473 } else if (Features.CPlusPlus && Char == '*') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001474 Kind = tok::periodstar;
Reid Spencer5f016e22007-07-11 17:01:13 +00001475 CurPtr += SizeTmp;
1476 } else if (Char == '.' &&
1477 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001478 Kind = tok::ellipsis;
Reid Spencer5f016e22007-07-11 17:01:13 +00001479 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1480 SizeTmp2, Result);
1481 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001482 Kind = tok::period;
Reid Spencer5f016e22007-07-11 17:01:13 +00001483 }
1484 break;
1485 case '&':
1486 Char = getCharAndSize(CurPtr, SizeTmp);
1487 if (Char == '&') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001488 Kind = tok::ampamp;
Reid Spencer5f016e22007-07-11 17:01:13 +00001489 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1490 } else if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001491 Kind = tok::ampequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00001492 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1493 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001494 Kind = tok::amp;
Reid Spencer5f016e22007-07-11 17:01:13 +00001495 }
1496 break;
1497 case '*':
1498 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001499 Kind = tok::starequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00001500 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1501 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001502 Kind = tok::star;
Reid Spencer5f016e22007-07-11 17:01:13 +00001503 }
1504 break;
1505 case '+':
1506 Char = getCharAndSize(CurPtr, SizeTmp);
1507 if (Char == '+') {
Reid Spencer5f016e22007-07-11 17:01:13 +00001508 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001509 Kind = tok::plusplus;
Reid Spencer5f016e22007-07-11 17:01:13 +00001510 } else if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00001511 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001512 Kind = tok::plusequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00001513 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001514 Kind = tok::plus;
Reid Spencer5f016e22007-07-11 17:01:13 +00001515 }
1516 break;
1517 case '-':
1518 Char = getCharAndSize(CurPtr, SizeTmp);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001519 if (Char == '-') { // --
Reid Spencer5f016e22007-07-11 17:01:13 +00001520 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001521 Kind = tok::minusminus;
Reid Spencer5f016e22007-07-11 17:01:13 +00001522 } else if (Char == '>' && Features.CPlusPlus &&
Chris Lattner9e6293d2008-10-12 04:51:35 +00001523 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
Reid Spencer5f016e22007-07-11 17:01:13 +00001524 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1525 SizeTmp2, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001526 Kind = tok::arrowstar;
1527 } else if (Char == '>') { // ->
Reid Spencer5f016e22007-07-11 17:01:13 +00001528 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001529 Kind = tok::arrow;
1530 } else if (Char == '=') { // -=
Reid Spencer5f016e22007-07-11 17:01:13 +00001531 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001532 Kind = tok::minusequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00001533 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001534 Kind = tok::minus;
Reid Spencer5f016e22007-07-11 17:01:13 +00001535 }
1536 break;
1537 case '~':
Chris Lattner9e6293d2008-10-12 04:51:35 +00001538 Kind = tok::tilde;
Reid Spencer5f016e22007-07-11 17:01:13 +00001539 break;
1540 case '!':
1541 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001542 Kind = tok::exclaimequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00001543 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1544 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001545 Kind = tok::exclaim;
Reid Spencer5f016e22007-07-11 17:01:13 +00001546 }
1547 break;
1548 case '/':
1549 // 6.4.9: Comments
1550 Char = getCharAndSize(CurPtr, SizeTmp);
1551 if (Char == '/') { // BCPL comment.
Chris Lattner8402c732009-01-16 22:39:25 +00001552 // Even if BCPL comments are disabled (e.g. in C89 mode), we generally
1553 // want to lex this as a comment. There is one problem with this though,
1554 // that in one particular corner case, this can change the behavior of the
1555 // resultant program. For example, In "foo //**/ bar", C89 would lex
1556 // this as "foo / bar" and langauges with BCPL comments would lex it as
1557 // "foo". Check to see if the character after the second slash is a '*'.
1558 // If so, we will lex that as a "/" instead of the start of a comment.
1559 if (Features.BCPLComment ||
1560 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*') {
1561 if (SkipBCPLComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
1562 return; // KeepCommentMode
Chris Lattner2d381892008-10-12 04:15:42 +00001563
Chris Lattner8402c732009-01-16 22:39:25 +00001564 // It is common for the tokens immediately after a // comment to be
1565 // whitespace (indentation for the next line). Instead of going through
1566 // the big switch, handle it efficiently now.
1567 goto SkipIgnoredUnits;
1568 }
1569 }
1570
1571 if (Char == '*') { // /**/ comment.
Reid Spencer5f016e22007-07-11 17:01:13 +00001572 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattner2d381892008-10-12 04:15:42 +00001573 return; // KeepCommentMode
1574 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattner8402c732009-01-16 22:39:25 +00001575 }
1576
1577 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00001578 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001579 Kind = tok::slashequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00001580 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001581 Kind = tok::slash;
Reid Spencer5f016e22007-07-11 17:01:13 +00001582 }
1583 break;
1584 case '%':
1585 Char = getCharAndSize(CurPtr, SizeTmp);
1586 if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001587 Kind = tok::percentequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00001588 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1589 } else if (Features.Digraphs && Char == '>') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001590 Kind = tok::r_brace; // '%>' -> '}'
Reid Spencer5f016e22007-07-11 17:01:13 +00001591 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1592 } else if (Features.Digraphs && Char == ':') {
1593 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1594 Char = getCharAndSize(CurPtr, SizeTmp);
1595 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001596 Kind = tok::hashhash; // '%:%:' -> '##'
Reid Spencer5f016e22007-07-11 17:01:13 +00001597 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1598 SizeTmp2, Result);
1599 } else if (Char == '@' && Features.Microsoft) { // %:@ -> #@ -> Charize
Reid Spencer5f016e22007-07-11 17:01:13 +00001600 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner74d15df2008-11-22 02:02:22 +00001601 if (!isLexingRawMode())
1602 Diag(BufferPtr, diag::charize_microsoft_ext);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001603 Kind = tok::hashat;
Chris Lattnere91e9322009-03-18 20:58:27 +00001604 } else { // '%:' -> '#'
Reid Spencer5f016e22007-07-11 17:01:13 +00001605 // We parsed a # character. If this occurs at the start of the line,
1606 // it's actually the start of a preprocessing directive. Callback to
1607 // the preprocessor to handle it.
1608 // FIXME: -fpreprocessed mode??
1609 if (Result.isAtStartOfLine() && !LexingRawMode) {
Chris Lattnere91e9322009-03-18 20:58:27 +00001610 FormTokenWithChars(Result, CurPtr, tok::hash);
Chris Lattner168ae2d2007-10-17 20:41:00 +00001611 PP->HandleDirective(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001612
1613 // As an optimization, if the preprocessor didn't switch lexers, tail
1614 // recurse.
Chris Lattner168ae2d2007-10-17 20:41:00 +00001615 if (PP->isCurrentLexer(this)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001616 // Start a new token. If this is a #include or something, the PP may
1617 // want us starting at the beginning of the line again. If so, set
1618 // the StartOfLine flag.
1619 if (IsAtStartOfLine) {
Chris Lattnerd2177732007-07-20 16:59:19 +00001620 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00001621 IsAtStartOfLine = false;
1622 }
1623 goto LexNextToken; // GCC isn't tail call eliminating.
1624 }
1625
Chris Lattner168ae2d2007-10-17 20:41:00 +00001626 return PP->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001627 }
Chris Lattnere91e9322009-03-18 20:58:27 +00001628
1629 Kind = tok::hash;
Reid Spencer5f016e22007-07-11 17:01:13 +00001630 }
1631 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001632 Kind = tok::percent;
Reid Spencer5f016e22007-07-11 17:01:13 +00001633 }
1634 break;
1635 case '<':
1636 Char = getCharAndSize(CurPtr, SizeTmp);
1637 if (ParsingFilename) {
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001638 return LexAngledStringLiteral(Result, CurPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +00001639 } else if (Char == '<' &&
1640 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001641 Kind = tok::lesslessequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00001642 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1643 SizeTmp2, Result);
1644 } else if (Char == '<') {
Reid Spencer5f016e22007-07-11 17:01:13 +00001645 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001646 Kind = tok::lessless;
Reid Spencer5f016e22007-07-11 17:01:13 +00001647 } else if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00001648 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001649 Kind = tok::lessequal;
1650 } else if (Features.Digraphs && Char == ':') { // '<:' -> '['
Reid Spencer5f016e22007-07-11 17:01:13 +00001651 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001652 Kind = tok::l_square;
1653 } else if (Features.Digraphs && Char == '%') { // '<%' -> '{'
Reid Spencer5f016e22007-07-11 17:01:13 +00001654 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001655 Kind = tok::l_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00001656 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001657 Kind = tok::less;
Reid Spencer5f016e22007-07-11 17:01:13 +00001658 }
1659 break;
1660 case '>':
1661 Char = getCharAndSize(CurPtr, SizeTmp);
1662 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00001663 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001664 Kind = tok::greaterequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00001665 } else if (Char == '>' &&
1666 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00001667 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1668 SizeTmp2, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001669 Kind = tok::greatergreaterequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00001670 } 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::greatergreater;
Reid Spencer5f016e22007-07-11 17:01:13 +00001673 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001674 Kind = tok::greater;
Reid Spencer5f016e22007-07-11 17:01:13 +00001675 }
1676 break;
1677 case '^':
1678 Char = getCharAndSize(CurPtr, SizeTmp);
1679 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00001680 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001681 Kind = tok::caretequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00001682 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001683 Kind = tok::caret;
Reid Spencer5f016e22007-07-11 17:01:13 +00001684 }
1685 break;
1686 case '|':
1687 Char = getCharAndSize(CurPtr, SizeTmp);
1688 if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001689 Kind = tok::pipeequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00001690 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1691 } else if (Char == '|') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001692 Kind = tok::pipepipe;
Reid Spencer5f016e22007-07-11 17:01:13 +00001693 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1694 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001695 Kind = tok::pipe;
Reid Spencer5f016e22007-07-11 17:01:13 +00001696 }
1697 break;
1698 case ':':
1699 Char = getCharAndSize(CurPtr, SizeTmp);
1700 if (Features.Digraphs && Char == '>') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001701 Kind = tok::r_square; // ':>' -> ']'
Reid Spencer5f016e22007-07-11 17:01:13 +00001702 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1703 } else if (Features.CPlusPlus && Char == ':') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001704 Kind = tok::coloncolon;
Reid Spencer5f016e22007-07-11 17:01:13 +00001705 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1706 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001707 Kind = tok::colon;
Reid Spencer5f016e22007-07-11 17:01:13 +00001708 }
1709 break;
1710 case ';':
Chris Lattner9e6293d2008-10-12 04:51:35 +00001711 Kind = tok::semi;
Reid Spencer5f016e22007-07-11 17:01:13 +00001712 break;
1713 case '=':
1714 Char = getCharAndSize(CurPtr, SizeTmp);
1715 if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001716 Kind = tok::equalequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00001717 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1718 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001719 Kind = tok::equal;
Reid Spencer5f016e22007-07-11 17:01:13 +00001720 }
1721 break;
1722 case ',':
Chris Lattner9e6293d2008-10-12 04:51:35 +00001723 Kind = tok::comma;
Reid Spencer5f016e22007-07-11 17:01:13 +00001724 break;
1725 case '#':
1726 Char = getCharAndSize(CurPtr, SizeTmp);
1727 if (Char == '#') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001728 Kind = tok::hashhash;
Reid Spencer5f016e22007-07-11 17:01:13 +00001729 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1730 } else if (Char == '@' && Features.Microsoft) { // #@ -> Charize
Chris Lattner9e6293d2008-10-12 04:51:35 +00001731 Kind = tok::hashat;
Chris Lattner74d15df2008-11-22 02:02:22 +00001732 if (!isLexingRawMode())
1733 Diag(BufferPtr, diag::charize_microsoft_ext);
Reid Spencer5f016e22007-07-11 17:01:13 +00001734 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1735 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +00001736 // We parsed a # character. If this occurs at the start of the line,
1737 // it's actually the start of a preprocessing directive. Callback to
1738 // the preprocessor to handle it.
1739 // FIXME: -fpreprocessed mode??
1740 if (Result.isAtStartOfLine() && !LexingRawMode) {
Chris Lattnere91e9322009-03-18 20:58:27 +00001741 FormTokenWithChars(Result, CurPtr, tok::hash);
Chris Lattner168ae2d2007-10-17 20:41:00 +00001742 PP->HandleDirective(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001743
1744 // As an optimization, if the preprocessor didn't switch lexers, tail
1745 // recurse.
Chris Lattner168ae2d2007-10-17 20:41:00 +00001746 if (PP->isCurrentLexer(this)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001747 // Start a new token. If this is a #include or something, the PP may
1748 // want us starting at the beginning of the line again. If so, set
1749 // the StartOfLine flag.
1750 if (IsAtStartOfLine) {
Chris Lattnerd2177732007-07-20 16:59:19 +00001751 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00001752 IsAtStartOfLine = false;
1753 }
1754 goto LexNextToken; // GCC isn't tail call eliminating.
1755 }
Chris Lattner168ae2d2007-10-17 20:41:00 +00001756 return PP->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001757 }
Chris Lattnere91e9322009-03-18 20:58:27 +00001758
1759 Kind = tok::hash;
Reid Spencer5f016e22007-07-11 17:01:13 +00001760 }
1761 break;
1762
Chris Lattner3a570772008-01-03 17:58:54 +00001763 case '@':
1764 // Objective C support.
1765 if (CurPtr[-1] == '@' && Features.ObjC1)
Chris Lattner9e6293d2008-10-12 04:51:35 +00001766 Kind = tok::at;
Chris Lattner3a570772008-01-03 17:58:54 +00001767 else
Chris Lattner9e6293d2008-10-12 04:51:35 +00001768 Kind = tok::unknown;
Chris Lattner3a570772008-01-03 17:58:54 +00001769 break;
1770
Reid Spencer5f016e22007-07-11 17:01:13 +00001771 case '\\':
1772 // FIXME: UCN's.
1773 // FALL THROUGH.
1774 default:
Chris Lattner9e6293d2008-10-12 04:51:35 +00001775 Kind = tok::unknown;
Reid Spencer5f016e22007-07-11 17:01:13 +00001776 break;
1777 }
1778
1779 // Notify MIOpt that we read a non-whitespace/non-comment token.
1780 MIOpt.ReadToken();
1781
1782 // Update the location of token as well as BufferPtr.
Chris Lattner9e6293d2008-10-12 04:51:35 +00001783 FormTokenWithChars(Result, CurPtr, Kind);
Reid Spencer5f016e22007-07-11 17:01:13 +00001784}