blob: 6dea5b7ddee7f149c89fca51675e3f071d954fef [file] [log] [blame]
Chris Lattner22eb9722006-06-18 05:43:12 +00001//===--- Lexer.cpp - C Language Family Lexer ------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner22eb9722006-06-18 05:43:12 +00007//
8//===----------------------------------------------------------------------===//
9//
Chris Lattner146762e2007-07-20 16:59:19 +000010// This file implements the Lexer and Token interfaces.
Chris Lattner22eb9722006-06-18 05:43:12 +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:
Chris Lattner22eb9722006-06-18 05:43:12 +000022// 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 Lattner60f36222009-01-29 05:15:15 +000029#include "clang/Lex/LexDiagnostic.h"
Chris Lattnerdc5c0552007-07-20 16:37:10 +000030#include "clang/Basic/SourceManager.h"
Chris Lattner619c1742007-07-22 18:38:25 +000031#include "llvm/Support/Compiler.h"
Chris Lattner739e7392007-04-29 07:12:06 +000032#include "llvm/Support/MemoryBuffer.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000033#include <cctype>
Chris Lattner22eb9722006-06-18 05:43:12 +000034using namespace clang;
35
36static void InitCharacterInfo();
37
Chris Lattner4894f482007-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 Gregor90abb6d2008-12-01 21:46:47 +000044 if (IdentifierInfo *II = getIdentifierInfo())
45 return II->getObjCKeywordID() == objcKey;
46 return false;
Chris Lattner4894f482007-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 Lattner67671ed2007-12-13 01:59:49 +000055
Chris Lattner4894f482007-10-07 08:47:24 +000056//===----------------------------------------------------------------------===//
57// Lexer Class Implementation
58//===----------------------------------------------------------------------===//
59
Chris Lattnerf76b9202009-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 Lattner5965a282009-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 Lattnerc8090892009-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 Lattner5965a282009-01-17 07:56:59 +0000101
Chris Lattnerc8090892009-01-17 08:03:42 +0000102 const llvm::MemoryBuffer *InputFile = PP.getSourceManager().getBuffer(FID);
Chris Lattner5965a282009-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 Lattner4894f482007-10-07 08:47:24 +0000110
Chris Lattner02b436a2007-10-17 20:41:00 +0000111/// Lexer constructor - Create a new raw lexer object. This object is only
Chris Lattner50c90502008-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 Lattner02b436a2007-10-17 20:41:00 +0000114Lexer::Lexer(SourceLocation fileloc, const LangOptions &features,
Chris Lattnerfcf64522009-01-17 07:42:27 +0000115 const char *BufStart, const char *BufPtr, const char *BufEnd)
Chris Lattner1abd2092009-01-17 03:48:08 +0000116 : FileLoc(fileloc), Features(features) {
Chris Lattnerf76b9202009-01-17 06:55:17 +0000117
Chris Lattnerf76b9202009-01-17 06:55:17 +0000118 InitLexer(BufStart, BufPtr, BufEnd);
Chris Lattner02b436a2007-10-17 20:41:00 +0000119
120 // We *are* in raw mode.
121 LexingRawMode = true;
Chris Lattner02b436a2007-10-17 20:41:00 +0000122}
123
Chris Lattner08354fe2009-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 Lattner757169b2009-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 Lattner29a2a192009-01-19 06:46:35 +0000153Lexer *Lexer::Create_PragmaLexer(SourceLocation SpellingLoc,
Chris Lattner9dc9c202009-02-15 20:52:18 +0000154 SourceLocation InstantiationLocStart,
155 SourceLocation InstantiationLocEnd,
Chris Lattner29a2a192009-01-19 06:46:35 +0000156 unsigned TokLen, Preprocessor &PP) {
Chris Lattner757169b2009-01-17 08:27:52 +0000157 SourceManager &SM = PP.getSourceManager();
Chris Lattner757169b2009-01-17 08:27:52 +0000158
159 // Create the lexer as if we were going to lex the file normally.
Chris Lattnercbc35ecb2009-01-19 07:46:45 +0000160 FileID SpellingFID = SM.getFileID(SpellingLoc);
Chris Lattner29a2a192009-01-19 06:46:35 +0000161 Lexer *L = new Lexer(SpellingFID, PP);
Chris Lattner757169b2009-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 Lattnerfa217bd2009-03-08 08:08:45 +0000170 assert(L->BufferEnd[0] == 0 && "Buffer is not nul terminated!");
Chris Lattner757169b2009-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 Lattner4fa23622009-01-26 00:43:02 +0000174 L->FileLoc = SM.createInstantiationLoc(SM.getLocForStartOfFile(SpellingFID),
Chris Lattner9dc9c202009-02-15 20:52:18 +0000175 InstantiationLocStart,
176 InstantiationLocEnd, TokLen);
Chris Lattner757169b2009-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 Lattner02b436a2007-10-17 20:41:00 +0000187
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000188/// Stringify - Convert the specified string into a C string, with surrounding
189/// ""'s, and with escaped \ and " characters.
Chris Lattnerecc39e92006-07-15 05:23:31 +0000190std::string Lexer::Stringify(const std::string &Str, bool Charify) {
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000191 std::string Result = Str;
Chris Lattnerecc39e92006-07-15 05:23:31 +0000192 char Quote = Charify ? '\'' : '"';
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000193 for (unsigned i = 0, e = Result.size(); i != e; ++i) {
Chris Lattnerecc39e92006-07-15 05:23:31 +0000194 if (Result[i] == '\\' || Result[i] == Quote) {
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000195 Result.insert(Result.begin()+i, '\\');
196 ++i; ++e;
197 }
198 }
Chris Lattnerecc39e92006-07-15 05:23:31 +0000199 return Result;
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000200}
201
Chris Lattner4c4a2452007-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
Chris Lattner22eb9722006-06-18 05:43:12 +0000213
Chris Lattner8e129c22007-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 Lattner184e65d2009-04-14 23:22:57 +0000219 const SourceManager &SM,
220 const LangOptions &LangOpts) {
Chris Lattner8e129c22007-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 Lattner4fa23622009-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 Lattnerd3817212009-01-26 22:24:27 +0000229 Loc = SM.getInstantiationLoc(Loc);
230 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
Chris Lattner5509d532009-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 Lattner8e129c22007-10-17 21:18:47 +0000234 // Create a lexer starting at the beginning of this token.
Chris Lattnerfcf64522009-01-17 07:42:27 +0000235 Lexer TheLexer(Loc, LangOpts, Buffer.first, StrData, Buffer.second);
Chris Lattner8e129c22007-10-17 21:18:47 +0000236 Token TheTok;
Chris Lattner50c90502008-10-12 01:15:46 +0000237 TheLexer.LexFromRawLexer(TheTok);
Chris Lattner8e129c22007-10-17 21:18:47 +0000238 return TheTok.getLength();
239}
240
Chris Lattner22eb9722006-06-18 05:43:12 +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;
Chris Lattnerdd0b7cb2006-10-17 02:53:51 +0000268 CharInfo[(int)'.'] = CHAR_PERIOD;
Chris Lattner22eb9722006-06-18 05:43:12 +0000269 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 Kaiserc8107e52007-10-18 12:47:01 +0000278 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER)) ? true : false;
Chris Lattner22eb9722006-06-18 05:43:12 +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 Kaiserc8107e52007-10-18 12:47:01 +0000284 return (CharInfo[c] & CHAR_HORZ_WS) ? true : false;
Chris Lattner22eb9722006-06-18 05:43:12 +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 Kaiserc8107e52007-10-18 12:47:01 +0000291 return (CharInfo[c] & (CHAR_HORZ_WS|CHAR_VERT_WS)) ? true : false;
Chris Lattner22eb9722006-06-18 05:43:12 +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 Kaiserc8107e52007-10-18 12:47:01 +0000297 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER|CHAR_PERIOD)) ?
298 true : false;
Chris Lattner22eb9722006-06-18 05:43:12 +0000299}
300
Chris Lattnerd01e2912006-06-18 16:22:51 +0000301
Chris Lattner22eb9722006-06-18 05:43:12 +0000302//===----------------------------------------------------------------------===//
303// Diagnostics forwarding code.
304//===----------------------------------------------------------------------===//
305
Chris Lattner619c1742007-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 Lattner4fa23622009-01-26 00:43:02 +0000312 unsigned CharNo,
313 unsigned TokLen) DISABLE_INLINE;
Chris Lattner619c1742007-07-22 18:38:25 +0000314static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
315 SourceLocation FileLoc,
Chris Lattner4fa23622009-01-26 00:43:02 +0000316 unsigned CharNo, unsigned TokLen) {
Chris Lattner9dc9c202009-02-15 20:52:18 +0000317 assert(FileLoc.isMacroID() && "Must be an instantiation");
318
Chris Lattner619c1742007-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 Lattner53e384f2009-01-16 07:00:02 +0000321 // spelling location.
Chris Lattner9dc9c202009-02-15 20:52:18 +0000322 SourceManager &SM = PP.getSourceManager();
Chris Lattner619c1742007-07-22 18:38:25 +0000323
Chris Lattner8a425862009-01-16 07:36:28 +0000324 // Create a new SLoc which is expanded from Instantiation(FileLoc) but whose
Chris Lattner53e384f2009-01-16 07:00:02 +0000325 // characters come from spelling(FileLoc)+Offset.
Chris Lattner9dc9c202009-02-15 20:52:18 +0000326 SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc);
Chris Lattner29a2a192009-01-19 06:46:35 +0000327 SpellingLoc = SpellingLoc.getFileLocWithOffset(CharNo);
Chris Lattner9dc9c202009-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 Lattner619c1742007-07-22 18:38:25 +0000335}
336
Chris Lattner22eb9722006-06-18 05:43:12 +0000337/// getSourceLocation - Return a source location identifier for the specified
338/// offset in the current file.
Chris Lattner4fa23622009-01-26 00:43:02 +0000339SourceLocation Lexer::getSourceLocation(const char *Loc,
340 unsigned TokLen) const {
Chris Lattner5d1c0272007-07-22 18:44:36 +0000341 assert(Loc >= BufferStart && Loc <= BufferEnd &&
Chris Lattner4cca5ba2006-07-02 20:05:54 +0000342 "Location out of range for this buffer!");
Chris Lattnerdc5c0552007-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 Lattner5d1c0272007-07-22 18:44:36 +0000346 unsigned CharNo = Loc-BufferStart;
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000347 if (FileLoc.isFileID())
Chris Lattner29a2a192009-01-19 06:46:35 +0000348 return FileLoc.getFileLocWithOffset(CharNo);
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000349
Chris Lattnerd32480d2009-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 Lattner02b436a2007-10-17 20:41:00 +0000352 assert(PP && "This doesn't work on raw lexers");
Chris Lattner4fa23622009-01-26 00:43:02 +0000353 return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen);
Chris Lattner22eb9722006-06-18 05:43:12 +0000354}
355
Chris Lattner22eb9722006-06-18 05:43:12 +0000356/// Diag - Forwarding function for diagnostics. This translate a source
357/// position in the current buffer into a SourceLocation object for rendering.
Chris Lattner427c9c12008-11-22 00:59:29 +0000358DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
Chris Lattner907dfe92008-11-18 07:59:24 +0000359 return PP->Diag(getSourceLocation(Loc), DiagID);
Chris Lattner22eb9722006-06-18 05:43:12 +0000360}
361
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 Lattner907dfe92008-11-18 07:59:24 +0000389 if (!Res || !L) return Res;
390
391 if (!L->getFeatures().Trigraphs) {
Chris Lattner6d27a162008-11-22 02:02:22 +0000392 if (!L->isLexingRawMode())
393 L->Diag(CP-2, diag::trigraph_ignored);
Chris Lattner907dfe92008-11-18 07:59:24 +0000394 return 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000395 }
Chris Lattner907dfe92008-11-18 07:59:24 +0000396
Chris Lattner6d27a162008-11-22 02:02:22 +0000397 if (!L->isLexingRawMode())
398 L->Diag(CP-2, diag::trigraph_converted) << std::string()+Res;
Chris Lattner22eb9722006-06-18 05:43:12 +0000399 return Res;
400}
401
Chris Lattnerfbce7aa2009-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 Lattner38b2cde2009-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 Lattnerfbce7aa2009-04-18 22:05:41 +0000448
Chris Lattner22eb9722006-06-18 05:43:12 +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.
Chris Lattner505c5472006-07-03 00:55:48 +0000457/// 3. If this is a UCN, return it. FIXME: C++ UCN's?
Chris Lattner22eb9722006-06-18 05:43:12 +0000458///
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///
Chris Lattnerd01e2912006-06-18 16:22:51 +0000463/// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
464/// be updated to match.
Chris Lattner22eb9722006-06-18 05:43:12 +0000465///
466char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
Chris Lattner146762e2007-07-20 16:59:19 +0000467 Token *Tok) {
Chris Lattner22eb9722006-06-18 05:43:12 +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
Chris Lattnerc1835952009-06-23 05:15:06 +0000476 // See if we have optional whitespace characters between the slash and
477 // newline.
Chris Lattnerfbce7aa2009-04-18 22:05:41 +0000478 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
479 // Remember that this token needs to be cleaned.
480 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Chris Lattner22eb9722006-06-18 05:43:12 +0000481
Chris Lattnerfbce7aa2009-04-18 22:05:41 +0000482 // Warn if there was whitespace between the backslash and newline.
Chris Lattnerc1835952009-06-23 05:15:06 +0000483 if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode())
Chris Lattnerfbce7aa2009-04-18 22:05:41 +0000484 Diag(Ptr, diag::backslash_newline_space);
Chris Lattnerdfbfc442009-04-18 21:57:20 +0000485
Chris Lattnerfbce7aa2009-04-18 22:05:41 +0000486 // Found backslash<whitespace><newline>. Parse the char after it.
487 Size += EscapedNewLineSize;
488 Ptr += EscapedNewLineSize;
489 // Use slow version to accumulate a correct size field.
490 return getCharAndSizeSlow(Ptr, Size, Tok);
491 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000492
493 // Otherwise, this is not an escaped newline, just return the slash.
494 return '\\';
495 }
496
497 // If this is a trigraph, process it.
498 if (Ptr[0] == '?' && Ptr[1] == '?') {
499 // If this is actually a legal trigraph (not something like "??x"), emit
500 // a trigraph warning. If so, and if trigraphs are enabled, return it.
501 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : 0)) {
502 // Remember that this token needs to be cleaned.
Chris Lattner146762e2007-07-20 16:59:19 +0000503 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Chris Lattner22eb9722006-06-18 05:43:12 +0000504
505 Ptr += 3;
506 Size += 3;
507 if (C == '\\') goto Slash;
508 return C;
509 }
510 }
511
512 // If this is neither, return a single character.
513 ++Size;
514 return *Ptr;
515}
516
Chris Lattnerd01e2912006-06-18 16:22:51 +0000517
Chris Lattner22eb9722006-06-18 05:43:12 +0000518/// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
519/// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
520/// and that we have already incremented Ptr by Size bytes.
521///
Chris Lattnerd01e2912006-06-18 16:22:51 +0000522/// NOTE: When this method is updated, getCharAndSizeSlow (above) should
523/// be updated to match.
524char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
Chris Lattner22eb9722006-06-18 05:43:12 +0000525 const LangOptions &Features) {
526 // If we have a slash, look for an escaped newline.
527 if (Ptr[0] == '\\') {
528 ++Size;
529 ++Ptr;
530Slash:
531 // Common case, backslash-char where the char is not whitespace.
532 if (!isWhitespace(Ptr[0])) return '\\';
533
534 // See if we have optional whitespace characters followed by a newline.
Chris Lattnerfbce7aa2009-04-18 22:05:41 +0000535 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
536 // Found backslash<whitespace><newline>. Parse the char after it.
537 Size += EscapedNewLineSize;
538 Ptr += EscapedNewLineSize;
539
540 // Use slow version to accumulate a correct size field.
541 return getCharAndSizeSlowNoWarn(Ptr, Size, Features);
542 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000543
544 // Otherwise, this is not an escaped newline, just return the slash.
545 return '\\';
546 }
547
548 // If this is a trigraph, process it.
549 if (Features.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
550 // If this is actually a legal trigraph (not something like "??x"), return
551 // it.
552 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
553 Ptr += 3;
554 Size += 3;
555 if (C == '\\') goto Slash;
556 return C;
557 }
558 }
559
560 // If this is neither, return a single character.
561 ++Size;
562 return *Ptr;
563}
564
Chris Lattner22eb9722006-06-18 05:43:12 +0000565//===----------------------------------------------------------------------===//
566// Helper methods for lexing.
567//===----------------------------------------------------------------------===//
568
Chris Lattner146762e2007-07-20 16:59:19 +0000569void Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000570 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
571 unsigned Size;
572 unsigned char C = *CurPtr++;
573 while (isIdentifierBody(C)) {
574 C = *CurPtr++;
575 }
576 --CurPtr; // Back up over the skipped character.
577
578 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
579 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
Chris Lattner505c5472006-07-03 00:55:48 +0000580 // FIXME: UCNs.
Chris Lattner22eb9722006-06-18 05:43:12 +0000581 if (C != '\\' && C != '?' && (C != '$' || !Features.DollarIdents)) {
582FinishIdentifier:
Chris Lattnercefc7682006-07-08 08:28:12 +0000583 const char *IdStart = BufferPtr;
Chris Lattnerb11c3232008-10-12 04:51:35 +0000584 FormTokenWithChars(Result, CurPtr, tok::identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +0000585
Chris Lattner0f1f5052006-07-20 04:16:23 +0000586 // If we are in raw mode, return this identifier raw. There is no need to
587 // look up identifier information or attempt to macro expand it.
588 if (LexingRawMode) return;
589
Chris Lattnercefc7682006-07-08 08:28:12 +0000590 // Fill in Result.IdentifierInfo, looking up the identifier in the
591 // identifier table.
Chris Lattner8256b972009-01-21 07:45:14 +0000592 IdentifierInfo *II = PP->LookUpIdentifierInfo(Result, IdStart);
Chris Lattner22eb9722006-06-18 05:43:12 +0000593
Chris Lattner1f6c7fe2009-01-23 18:35:48 +0000594 // Change the kind of this identifier to the appropriate token kind, e.g.
595 // turning "for" into a keyword.
596 Result.setKind(II->getTokenID());
597
Chris Lattnerc5a00062006-06-18 16:41:01 +0000598 // Finally, now that we know we have an identifier, pass this off to the
599 // preprocessor, which may macro expand it or something.
Chris Lattner8256b972009-01-21 07:45:14 +0000600 if (II->isHandleIdentifierCase())
Chris Lattnerad89ec02009-01-21 07:43:11 +0000601 PP->HandleIdentifier(Result);
602 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000603 }
604
605 // Otherwise, $,\,? in identifier found. Enter slower path.
606
607 C = getCharAndSize(CurPtr, Size);
608 while (1) {
609 if (C == '$') {
610 // If we hit a $ and they are not supported in identifiers, we are done.
611 if (!Features.DollarIdents) goto FinishIdentifier;
612
613 // Otherwise, emit a diagnostic and continue.
Chris Lattner6d27a162008-11-22 02:02:22 +0000614 if (!isLexingRawMode())
615 Diag(CurPtr, diag::ext_dollar_in_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +0000616 CurPtr = ConsumeChar(CurPtr, Size, Result);
617 C = getCharAndSize(CurPtr, Size);
618 continue;
Chris Lattner505c5472006-07-03 00:55:48 +0000619 } else if (!isIdentifierBody(C)) { // FIXME: UCNs.
Chris Lattner22eb9722006-06-18 05:43:12 +0000620 // Found end of identifier.
621 goto FinishIdentifier;
622 }
623
624 // Otherwise, this character is good, consume it.
625 CurPtr = ConsumeChar(CurPtr, Size, Result);
626
627 C = getCharAndSize(CurPtr, Size);
Chris Lattner505c5472006-07-03 00:55:48 +0000628 while (isIdentifierBody(C)) { // FIXME: UCNs.
Chris Lattner22eb9722006-06-18 05:43:12 +0000629 CurPtr = ConsumeChar(CurPtr, Size, Result);
630 C = getCharAndSize(CurPtr, Size);
631 }
632 }
633}
634
635
Nate Begeman5eee9332008-04-14 02:26:39 +0000636/// LexNumericConstant - Lex the remainder of a integer or floating point
Chris Lattner22eb9722006-06-18 05:43:12 +0000637/// constant. From[-1] is the first character lexed. Return the end of the
638/// constant.
Chris Lattner146762e2007-07-20 16:59:19 +0000639void Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000640 unsigned Size;
641 char C = getCharAndSize(CurPtr, Size);
642 char PrevCh = 0;
Chris Lattner505c5472006-07-03 00:55:48 +0000643 while (isNumberBody(C)) { // FIXME: UCNs?
Chris Lattner22eb9722006-06-18 05:43:12 +0000644 CurPtr = ConsumeChar(CurPtr, Size, Result);
645 PrevCh = C;
646 C = getCharAndSize(CurPtr, Size);
647 }
648
649 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
650 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e'))
651 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
652
653 // If we have a hex FP constant, continue.
Eli Friedman5d72d412009-04-28 00:51:18 +0000654 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p'))
Chris Lattner22eb9722006-06-18 05:43:12 +0000655 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
656
Chris Lattnerd01e2912006-06-18 16:22:51 +0000657 // Update the location of token as well as BufferPtr.
Chris Lattner5a7971e2009-01-26 19:29:26 +0000658 const char *TokStart = BufferPtr;
Chris Lattnerb11c3232008-10-12 04:51:35 +0000659 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
Chris Lattner5a7971e2009-01-26 19:29:26 +0000660 Result.setLiteralData(TokStart);
Chris Lattner22eb9722006-06-18 05:43:12 +0000661}
662
663/// LexStringLiteral - Lex the remainder of a string literal, after having lexed
664/// either " or L".
Chris Lattner4d963442008-10-12 04:05:48 +0000665void Lexer::LexStringLiteral(Token &Result, const char *CurPtr, bool Wide) {
Chris Lattner22eb9722006-06-18 05:43:12 +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 Lattnerd14705b2009-03-18 21:10:12 +0000676 if (!isLexingRawMode() && !Features.AsmPreprocessor)
Chris Lattner6d27a162008-11-22 02:02:22 +0000677 Diag(BufferPtr, diag::err_unterminated_string);
Chris Lattnerb11c3232008-10-12 04:51:35 +0000678 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Chris Lattner5a78a022006-07-20 06:02:19 +0000679 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000680 } else if (C == 0) {
681 NulCharacter = CurPtr-1;
682 }
683 C = getAndAdvanceChar(CurPtr, Result);
684 }
685
Chris Lattner5a78a022006-07-20 06:02:19 +0000686 // If a nul character existed in the string, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +0000687 if (NulCharacter && !isLexingRawMode())
688 Diag(NulCharacter, diag::null_in_string);
Chris Lattner22eb9722006-06-18 05:43:12 +0000689
Chris Lattnerd01e2912006-06-18 16:22:51 +0000690 // Update the location of the token as well as the BufferPtr instance var.
Chris Lattner5a7971e2009-01-26 19:29:26 +0000691 const char *TokStart = BufferPtr;
Chris Lattnerb11c3232008-10-12 04:51:35 +0000692 FormTokenWithChars(Result, CurPtr,
693 Wide ? tok::wide_string_literal : tok::string_literal);
Chris Lattner5a7971e2009-01-26 19:29:26 +0000694 Result.setLiteralData(TokStart);
Chris Lattner22eb9722006-06-18 05:43:12 +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 Lattner146762e2007-07-20 16:59:19 +0000699void Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000700 const char *NulCharacter = 0; // Does this string contain the \0 character?
Chris Lattnerb40289b2009-04-17 23:56:52 +0000701 const char *AfterLessPos = CurPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +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 Lattnerb40289b2009-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);
Chris Lattner5a78a022006-07-20 06:02:19 +0000713 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000714 } else if (C == 0) {
715 NulCharacter = CurPtr-1;
716 }
717 C = getAndAdvanceChar(CurPtr, Result);
718 }
719
Chris Lattner5a78a022006-07-20 06:02:19 +0000720 // If a nul character existed in the string, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +0000721 if (NulCharacter && !isLexingRawMode())
722 Diag(NulCharacter, diag::null_in_string);
Chris Lattner22eb9722006-06-18 05:43:12 +0000723
Chris Lattnerd01e2912006-06-18 16:22:51 +0000724 // Update the location of token as well as BufferPtr.
Chris Lattner5a7971e2009-01-26 19:29:26 +0000725 const char *TokStart = BufferPtr;
Chris Lattnerb11c3232008-10-12 04:51:35 +0000726 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
Chris Lattner5a7971e2009-01-26 19:29:26 +0000727 Result.setLiteralData(TokStart);
Chris Lattner22eb9722006-06-18 05:43:12 +0000728}
729
730
731/// LexCharConstant - Lex the remainder of a character constant, after having
732/// lexed either ' or L'.
Chris Lattner146762e2007-07-20 16:59:19 +0000733void Lexer::LexCharConstant(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +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 Lattnerd14705b2009-03-18 21:10:12 +0000739 if (!isLexingRawMode() && !Features.AsmPreprocessor)
Chris Lattner6d27a162008-11-22 02:02:22 +0000740 Diag(BufferPtr, diag::err_empty_character);
Chris Lattnerb11c3232008-10-12 04:51:35 +0000741 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner5a78a022006-07-20 06:02:19 +0000742 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000743 } 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 Lattnerd14705b2009-03-18 21:10:12 +0000760 if (!isLexingRawMode() && !Features.AsmPreprocessor)
Chris Lattner6d27a162008-11-22 02:02:22 +0000761 Diag(BufferPtr, diag::err_unterminated_char);
Chris Lattnerb11c3232008-10-12 04:51:35 +0000762 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Chris Lattner5a78a022006-07-20 06:02:19 +0000763 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000764 } else if (C == 0) {
765 NulCharacter = CurPtr-1;
766 }
767 C = getAndAdvanceChar(CurPtr, Result);
768 } while (C != '\'');
769 }
770
Chris Lattner6d27a162008-11-22 02:02:22 +0000771 if (NulCharacter && !isLexingRawMode())
772 Diag(NulCharacter, diag::null_in_char);
Chris Lattner22eb9722006-06-18 05:43:12 +0000773
Chris Lattnerd01e2912006-06-18 16:22:51 +0000774 // Update the location of token as well as BufferPtr.
Chris Lattner5a7971e2009-01-26 19:29:26 +0000775 const char *TokStart = BufferPtr;
Chris Lattnerb11c3232008-10-12 04:51:35 +0000776 FormTokenWithChars(Result, CurPtr, tok::char_constant);
Chris Lattner5a7971e2009-01-26 19:29:26 +0000777 Result.setLiteralData(TokStart);
Chris Lattner22eb9722006-06-18 05:43:12 +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 Lattner4d963442008-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) {
Chris Lattner22eb9722006-06-18 05:43:12 +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 Dunbar5c4cc092008-11-25 00:20:22 +0000793 // Otherwise if we have something other than whitespace, we're done.
Chris Lattner22eb9722006-06-18 05:43:12 +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 Lattner4d963442008-10-12 04:05:48 +0000800 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +0000801 }
802
803 // ok, but handle newline.
804 // The returned token is at the start of the line.
Chris Lattner146762e2007-07-20 16:59:19 +0000805 Result.setFlag(Token::StartOfLine);
Chris Lattner22eb9722006-06-18 05:43:12 +0000806 // No leading whitespace seen so far.
Chris Lattner146762e2007-07-20 16:59:19 +0000807 Result.clearFlag(Token::LeadingSpace);
Chris Lattner22eb9722006-06-18 05:43:12 +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 Lattner146762e2007-07-20 16:59:19 +0000814 Result.setFlag(Token::LeadingSpace);
Chris Lattner22eb9722006-06-18 05:43:12 +0000815
Chris Lattner4d963442008-10-12 04:05:48 +0000816 // If the client wants us to return whitespace, return it now.
817 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +0000818 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner4d963442008-10-12 04:05:48 +0000819 return true;
820 }
821
Chris Lattner22eb9722006-06-18 05:43:12 +0000822 BufferPtr = CurPtr;
Chris Lattner4d963442008-10-12 04:05:48 +0000823 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +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 Lattnere01e7582008-10-12 04:15:42 +0000828/// BufferPtr and return. If we're in KeepCommentMode, this will form the token
829/// and return true.
Chris Lattner146762e2007-07-20 16:59:19 +0000830bool Lexer::SkipBCPLComment(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000831 // If BCPL comments aren't explicitly enabled for this language, emit an
832 // extension warning.
Chris Lattner6d27a162008-11-22 02:02:22 +0000833 if (!Features.BCPLComment && !isLexingRawMode()) {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000834 Diag(BufferPtr, diag::ext_bcpl_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +0000835
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;
Chris Lattner505c5472006-07-03 00:55:48 +0000847 // 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.
Chris Lattner22eb9722006-06-18 05:43:12 +0000850
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 Lattnere141a9e2008-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.
Chris Lattner22eb9722006-06-18 05:43:12 +0000866 const char *OldPtr = CurPtr;
Chris Lattnere141a9e2008-12-12 07:34:39 +0000867 bool OldRawMode = isLexingRawMode();
868 LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +0000869 C = getAndAdvanceChar(CurPtr, Result);
Chris Lattnere141a9e2008-12-12 07:34:39 +0000870 LexingRawMode = OldRawMode;
Chris Lattnerecdaf402009-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 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000879
880 // If we read multiple characters, and one of those characters was a \r or
Chris Lattnerff591e22007-06-09 06:07:22 +0000881 // \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] != '/') {
Chris Lattner22eb9722006-06-18 05:43:12 +0000884 for (; OldPtr != CurPtr; ++OldPtr)
885 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
Chris Lattnerff591e22007-06-09 06:07:22 +0000886 // 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 Lattner6d27a162008-11-22 02:02:22 +0000896 if (!isLexingRawMode())
897 Diag(OldPtr-1, diag::ext_multi_line_bcpl_comment);
Chris Lattnercb283342006-06-18 06:48:37 +0000898 break;
Chris Lattner22eb9722006-06-18 05:43:12 +0000899 }
900 }
901
Chris Lattner457fc152006-07-29 06:30:25 +0000902 if (CurPtr == BufferEnd+1) { --CurPtr; break; }
Chris Lattner22eb9722006-06-18 05:43:12 +0000903 } while (C != '\n' && C != '\r');
904
Chris Lattner457fc152006-07-29 06:30:25 +0000905 // Found but did not consume the newline.
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000906 if (PP)
907 PP->HandleComment(SourceRange(getSourceLocation(BufferPtr),
908 getSourceLocation(CurPtr)));
909
Chris Lattner457fc152006-07-29 06:30:25 +0000910 // If we are returning comments as tokens, return this comment as a token.
Chris Lattner8637abd2008-10-12 03:22:02 +0000911 if (inKeepCommentMode())
Chris Lattner457fc152006-07-29 06:30:25 +0000912 return SaveBCPLComment(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +0000913
914 // If we are inside a preprocessor directive and we see the end of line,
915 // return immediately, so that the lexer can return this as an EOM token.
Chris Lattner457fc152006-07-29 06:30:25 +0000916 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000917 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +0000918 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +0000919 }
920
921 // Otherwise, eat the \n character. We don't care if this is a \n\r or
Chris Lattner87e97ea2008-10-12 00:23:07 +0000922 // \r\n sequence. This is an efficiency hack (because we know the \n can't
Chris Lattner4d963442008-10-12 04:05:48 +0000923 // contribute to another token), it isn't needed for correctness. Note that
924 // this is ok even in KeepWhitespaceMode, because we would have returned the
925 /// comment above in that mode.
Chris Lattner22eb9722006-06-18 05:43:12 +0000926 ++CurPtr;
927
928 // The next returned token is at the start of the line.
Chris Lattner146762e2007-07-20 16:59:19 +0000929 Result.setFlag(Token::StartOfLine);
Chris Lattner22eb9722006-06-18 05:43:12 +0000930 // No leading whitespace seen so far.
Chris Lattner146762e2007-07-20 16:59:19 +0000931 Result.clearFlag(Token::LeadingSpace);
Chris Lattner22eb9722006-06-18 05:43:12 +0000932 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +0000933 return false;
Chris Lattner457fc152006-07-29 06:30:25 +0000934}
Chris Lattner22eb9722006-06-18 05:43:12 +0000935
Chris Lattner457fc152006-07-29 06:30:25 +0000936/// SaveBCPLComment - If in save-comment mode, package up this BCPL comment in
937/// an appropriate way and return it.
Chris Lattner146762e2007-07-20 16:59:19 +0000938bool Lexer::SaveBCPLComment(Token &Result, const char *CurPtr) {
Chris Lattnerb11c3232008-10-12 04:51:35 +0000939 // If we're not in a preprocessor directive, just return the // comment
940 // directly.
941 FormTokenWithChars(Result, CurPtr, tok::comment);
Chris Lattner457fc152006-07-29 06:30:25 +0000942
Chris Lattnerb11c3232008-10-12 04:51:35 +0000943 if (!ParsingPreprocessorDirective)
944 return true;
945
946 // If this BCPL-style comment is in a macro definition, transmogrify it into
947 // a C-style block comment.
948 std::string Spelling = PP->getSpelling(Result);
949 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not bcpl comment?");
950 Spelling[1] = '*'; // Change prefix to "/*".
951 Spelling += "*/"; // add suffix.
952
953 Result.setKind(tok::comment);
Chris Lattner5a7971e2009-01-26 19:29:26 +0000954 PP->CreateString(&Spelling[0], Spelling.size(), Result,
955 Result.getLocation());
Chris Lattnere01e7582008-10-12 04:15:42 +0000956 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +0000957}
958
Chris Lattnercb283342006-06-18 06:48:37 +0000959/// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
960/// character (either \n or \r) is part of an escaped newline sequence. Issue a
Chris Lattner89770572008-12-12 07:14:34 +0000961/// diagnostic if so. We know that the newline is inside of a block comment.
Chris Lattner1f583052006-06-18 06:53:56 +0000962static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
963 Lexer *L) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000964 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
Chris Lattner22eb9722006-06-18 05:43:12 +0000965
966 // Back up off the newline.
967 --CurPtr;
968
969 // If this is a two-character newline sequence, skip the other character.
970 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
971 // \n\n or \r\r -> not escaped newline.
972 if (CurPtr[0] == CurPtr[1])
973 return false;
974 // \n\r or \r\n -> skip the newline.
975 --CurPtr;
976 }
977
978 // If we have horizontal whitespace, skip over it. We allow whitespace
979 // between the slash and newline.
980 bool HasSpace = false;
981 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
982 --CurPtr;
983 HasSpace = true;
984 }
985
986 // If we have a slash, we know this is an escaped newline.
987 if (*CurPtr == '\\') {
Chris Lattnercb283342006-06-18 06:48:37 +0000988 if (CurPtr[-1] != '*') return false;
Chris Lattner22eb9722006-06-18 05:43:12 +0000989 } else {
990 // It isn't a slash, is it the ?? / trigraph?
Chris Lattnercb283342006-06-18 06:48:37 +0000991 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
992 CurPtr[-3] != '*')
Chris Lattner22eb9722006-06-18 05:43:12 +0000993 return false;
Chris Lattnercb283342006-06-18 06:48:37 +0000994
995 // This is the trigraph ending the comment. Emit a stern warning!
Chris Lattner22eb9722006-06-18 05:43:12 +0000996 CurPtr -= 2;
997
998 // If no trigraphs are enabled, warn that we ignored this trigraph and
999 // ignore this * character.
Chris Lattner1f583052006-06-18 06:53:56 +00001000 if (!L->getFeatures().Trigraphs) {
Chris Lattner6d27a162008-11-22 02:02:22 +00001001 if (!L->isLexingRawMode())
1002 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
Chris Lattnercb283342006-06-18 06:48:37 +00001003 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001004 }
Chris Lattner6d27a162008-11-22 02:02:22 +00001005 if (!L->isLexingRawMode())
1006 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +00001007 }
1008
1009 // Warn about having an escaped newline between the */ characters.
Chris Lattner6d27a162008-11-22 02:02:22 +00001010 if (!L->isLexingRawMode())
1011 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
Chris Lattner22eb9722006-06-18 05:43:12 +00001012
1013 // If there was space between the backslash and newline, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00001014 if (HasSpace && !L->isLexingRawMode())
1015 L->Diag(CurPtr, diag::backslash_newline_space);
Chris Lattner22eb9722006-06-18 05:43:12 +00001016
Chris Lattnercb283342006-06-18 06:48:37 +00001017 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001018}
1019
Chris Lattneraded4a92006-10-27 04:42:31 +00001020#ifdef __SSE2__
1021#include <emmintrin.h>
Chris Lattner9f6604f2006-10-30 20:01:22 +00001022#elif __ALTIVEC__
1023#include <altivec.h>
1024#undef bool
Chris Lattneraded4a92006-10-27 04:42:31 +00001025#endif
1026
Chris Lattner22eb9722006-06-18 05:43:12 +00001027/// SkipBlockComment - We have just read the /* characters from input. Read
1028/// until we find the */ characters that terminate the comment. Note that we
1029/// don't bother decoding trigraphs or escaped newlines in block comments,
1030/// because they cannot cause the comment to end. The only thing that can
1031/// happen is the comment could end with an escaped newline between the */ end
1032/// of comment.
Chris Lattnere01e7582008-10-12 04:15:42 +00001033///
1034/// If KeepCommentMode is enabled, this forms a token from the comment and
1035/// returns true.
Chris Lattner146762e2007-07-20 16:59:19 +00001036bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001037 // Scan one character past where we should, looking for a '/' character. Once
1038 // we find it, check to see if it was preceeded by a *. This common
1039 // optimization helps people who like to put a lot of * characters in their
1040 // comments.
Chris Lattnerc850ad62007-07-21 23:43:37 +00001041
1042 // The first character we get with newlines and trigraphs skipped to handle
1043 // the degenerate /*/ case below correctly if the * has an escaped newline
1044 // after it.
1045 unsigned CharSize;
1046 unsigned char C = getCharAndSize(CurPtr, CharSize);
1047 CurPtr += CharSize;
Chris Lattner22eb9722006-06-18 05:43:12 +00001048 if (C == 0 && CurPtr == BufferEnd+1) {
Chris Lattner6d27a162008-11-22 02:02:22 +00001049 if (!isLexingRawMode())
Chris Lattner7c2e9802008-10-12 01:31:51 +00001050 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner99e7d232008-10-12 04:19:49 +00001051 --CurPtr;
1052
1053 // KeepWhitespaceMode should return this broken comment as a token. Since
1054 // it isn't a well formed comment, just return it as an 'unknown' token.
1055 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00001056 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner99e7d232008-10-12 04:19:49 +00001057 return true;
1058 }
1059
1060 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00001061 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001062 }
1063
Chris Lattnerc850ad62007-07-21 23:43:37 +00001064 // Check to see if the first character after the '/*' is another /. If so,
1065 // then this slash does not end the block comment, it is part of it.
1066 if (C == '/')
1067 C = *CurPtr++;
1068
Chris Lattner22eb9722006-06-18 05:43:12 +00001069 while (1) {
Chris Lattner6cc3e362006-10-27 04:12:35 +00001070 // Skip over all non-interesting characters until we find end of buffer or a
1071 // (probably ending) '/' character.
Chris Lattner6cc3e362006-10-27 04:12:35 +00001072 if (CurPtr + 24 < BufferEnd) {
1073 // While not aligned to a 16-byte boundary.
1074 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
1075 C = *CurPtr++;
1076
1077 if (C == '/') goto FoundSlash;
Chris Lattneraded4a92006-10-27 04:42:31 +00001078
1079#ifdef __SSE2__
1080 __m128i Slashes = _mm_set_epi8('/', '/', '/', '/', '/', '/', '/', '/',
1081 '/', '/', '/', '/', '/', '/', '/', '/');
1082 while (CurPtr+16 <= BufferEnd &&
1083 _mm_movemask_epi8(_mm_cmpeq_epi8(*(__m128i*)CurPtr, Slashes)) == 0)
1084 CurPtr += 16;
Chris Lattner9f6604f2006-10-30 20:01:22 +00001085#elif __ALTIVEC__
1086 __vector unsigned char Slashes = {
1087 '/', '/', '/', '/', '/', '/', '/', '/',
1088 '/', '/', '/', '/', '/', '/', '/', '/'
1089 };
1090 while (CurPtr+16 <= BufferEnd &&
1091 !vec_any_eq(*(vector unsigned char*)CurPtr, Slashes))
1092 CurPtr += 16;
1093#else
Chris Lattneraded4a92006-10-27 04:42:31 +00001094 // Scan for '/' quickly. Many block comments are very large.
Chris Lattner6cc3e362006-10-27 04:12:35 +00001095 while (CurPtr[0] != '/' &&
1096 CurPtr[1] != '/' &&
1097 CurPtr[2] != '/' &&
1098 CurPtr[3] != '/' &&
1099 CurPtr+4 < BufferEnd) {
1100 CurPtr += 4;
1101 }
Chris Lattneraded4a92006-10-27 04:42:31 +00001102#endif
1103
1104 // It has to be one of the bytes scanned, increment to it and read one.
Chris Lattner6cc3e362006-10-27 04:12:35 +00001105 C = *CurPtr++;
1106 }
1107
Chris Lattneraded4a92006-10-27 04:42:31 +00001108 // Loop to scan the remainder.
Chris Lattner22eb9722006-06-18 05:43:12 +00001109 while (C != '/' && C != '\0')
1110 C = *CurPtr++;
1111
Chris Lattner6cc3e362006-10-27 04:12:35 +00001112 FoundSlash:
Chris Lattner22eb9722006-06-18 05:43:12 +00001113 if (C == '/') {
Chris Lattner22eb9722006-06-18 05:43:12 +00001114 if (CurPtr[-2] == '*') // We found the final */. We're done!
1115 break;
1116
1117 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
Chris Lattner1f583052006-06-18 06:53:56 +00001118 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001119 // We found the final */, though it had an escaped newline between the
1120 // * and /. We're done!
1121 break;
1122 }
1123 }
1124 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
1125 // If this is a /* inside of the comment, emit a warning. Don't do this
1126 // if this is a /*/, which will end the comment. This misses cases with
1127 // embedded escaped newlines, but oh well.
Chris Lattner6d27a162008-11-22 02:02:22 +00001128 if (!isLexingRawMode())
1129 Diag(CurPtr-1, diag::warn_nested_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +00001130 }
1131 } else if (C == 0 && CurPtr == BufferEnd+1) {
Chris Lattner6d27a162008-11-22 02:02:22 +00001132 if (!isLexingRawMode())
1133 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +00001134 // Note: the user probably forgot a */. We could continue immediately
1135 // after the /*, but this would involve lexing a lot of what really is the
1136 // comment, which surely would confuse the parser.
Chris Lattner99e7d232008-10-12 04:19:49 +00001137 --CurPtr;
1138
1139 // KeepWhitespaceMode should return this broken comment as a token. Since
1140 // it isn't a well formed comment, just return it as an 'unknown' token.
1141 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00001142 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner99e7d232008-10-12 04:19:49 +00001143 return true;
1144 }
1145
1146 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00001147 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001148 }
1149 C = *CurPtr++;
1150 }
Chris Lattner457fc152006-07-29 06:30:25 +00001151
Douglas Gregorc6d5edd2009-07-02 17:08:52 +00001152 if (PP)
1153 PP->HandleComment(SourceRange(getSourceLocation(BufferPtr),
1154 getSourceLocation(CurPtr)));
1155
Chris Lattner457fc152006-07-29 06:30:25 +00001156 // If we are returning comments as tokens, return this comment as a token.
Chris Lattner8637abd2008-10-12 03:22:02 +00001157 if (inKeepCommentMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00001158 FormTokenWithChars(Result, CurPtr, tok::comment);
Chris Lattnere01e7582008-10-12 04:15:42 +00001159 return true;
Chris Lattner457fc152006-07-29 06:30:25 +00001160 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001161
1162 // It is common for the tokens immediately after a /**/ comment to be
1163 // whitespace. Instead of going through the big switch, handle it
Chris Lattner4d963442008-10-12 04:05:48 +00001164 // efficiently now. This is safe even in KeepWhitespaceMode because we would
1165 // have already returned above with the comment as a token.
Chris Lattner22eb9722006-06-18 05:43:12 +00001166 if (isHorizontalWhitespace(*CurPtr)) {
Chris Lattner146762e2007-07-20 16:59:19 +00001167 Result.setFlag(Token::LeadingSpace);
Chris Lattner457fc152006-07-29 06:30:25 +00001168 SkipWhitespace(Result, CurPtr+1);
Chris Lattnere01e7582008-10-12 04:15:42 +00001169 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001170 }
1171
1172 // Otherwise, just return so that the next character will be lexed as a token.
1173 BufferPtr = CurPtr;
Chris Lattner146762e2007-07-20 16:59:19 +00001174 Result.setFlag(Token::LeadingSpace);
Chris Lattnere01e7582008-10-12 04:15:42 +00001175 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001176}
1177
1178//===----------------------------------------------------------------------===//
1179// Primary Lexing Entry Points
1180//===----------------------------------------------------------------------===//
1181
Chris Lattner22eb9722006-06-18 05:43:12 +00001182/// ReadToEndOfLine - Read the rest of the current preprocessor line as an
1183/// uninterpreted string. This switches the lexer out of directive mode.
1184std::string Lexer::ReadToEndOfLine() {
1185 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
1186 "Must be in a preprocessing directive!");
1187 std::string Result;
Chris Lattner146762e2007-07-20 16:59:19 +00001188 Token Tmp;
Chris Lattner22eb9722006-06-18 05:43:12 +00001189
1190 // CurPtr - Cache BufferPtr in an automatic variable.
1191 const char *CurPtr = BufferPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00001192 while (1) {
1193 char Char = getAndAdvanceChar(CurPtr, Tmp);
1194 switch (Char) {
1195 default:
1196 Result += Char;
1197 break;
1198 case 0: // Null.
1199 // Found end of file?
1200 if (CurPtr-1 != BufferEnd) {
1201 // Nope, normal character, continue.
1202 Result += Char;
1203 break;
1204 }
1205 // FALL THROUGH.
1206 case '\r':
1207 case '\n':
1208 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
1209 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
1210 BufferPtr = CurPtr-1;
1211
1212 // Next, lex the character, which should handle the EOM transition.
Chris Lattnercb283342006-06-18 06:48:37 +00001213 Lex(Tmp);
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001214 assert(Tmp.is(tok::eom) && "Unexpected token!");
Chris Lattner22eb9722006-06-18 05:43:12 +00001215
1216 // Finally, we're done, return the string we found.
1217 return Result;
1218 }
1219 }
1220}
1221
1222/// LexEndOfFile - CurPtr points to the end of this file. Handle this
1223/// condition, reporting diagnostics and handling other edge cases as required.
Chris Lattner2183a6e2006-07-18 06:36:12 +00001224/// This returns true if Result contains a token, false if PP.Lex should be
1225/// called again.
Chris Lattner146762e2007-07-20 16:59:19 +00001226bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001227 // If we hit the end of the file while parsing a preprocessor directive,
1228 // end the preprocessor directive first. The next token returned will
1229 // then be the end of file.
1230 if (ParsingPreprocessorDirective) {
1231 // Done parsing the "line".
1232 ParsingPreprocessorDirective = false;
Chris Lattnerd01e2912006-06-18 16:22:51 +00001233 // Update the location of token as well as BufferPtr.
Chris Lattnerb11c3232008-10-12 04:51:35 +00001234 FormTokenWithChars(Result, CurPtr, tok::eom);
Chris Lattner457fc152006-07-29 06:30:25 +00001235
1236 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattner097a8b82008-10-12 03:27:19 +00001237 SetCommentRetentionState(PP->getCommentRetentionState());
Chris Lattner2183a6e2006-07-18 06:36:12 +00001238 return true; // Have a token.
Chris Lattner22eb9722006-06-18 05:43:12 +00001239 }
1240
Chris Lattner30a2fa12006-07-19 06:31:49 +00001241 // If we are in raw mode, return this event as an EOF token. Let the caller
1242 // that put us in raw mode handle the event.
Chris Lattner6d27a162008-11-22 02:02:22 +00001243 if (isLexingRawMode()) {
Chris Lattner8c204872006-10-14 05:19:21 +00001244 Result.startToken();
Chris Lattner30a2fa12006-07-19 06:31:49 +00001245 BufferPtr = BufferEnd;
Chris Lattnerb11c3232008-10-12 04:51:35 +00001246 FormTokenWithChars(Result, BufferEnd, tok::eof);
Chris Lattner30a2fa12006-07-19 06:31:49 +00001247 return true;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00001248 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001249
Chris Lattner30a2fa12006-07-19 06:31:49 +00001250 // Otherwise, issue diagnostics for unterminated #if and missing newline.
1251
1252 // If we are in a #if directive, emit an error.
1253 while (!ConditionalStack.empty()) {
Chris Lattner014156e2008-11-22 06:22:39 +00001254 PP->Diag(ConditionalStack.back().IfLoc,
1255 diag::err_pp_unterminated_conditional);
Chris Lattner30a2fa12006-07-19 06:31:49 +00001256 ConditionalStack.pop_back();
1257 }
1258
Chris Lattner8f96d042008-04-12 05:54:25 +00001259 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
1260 // a pedwarn.
1261 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r'))
Mike Stump0be88752009-04-02 02:29:42 +00001262 Diag(BufferEnd, diag::ext_no_newline_eof)
1263 << CodeModificationHint::CreateInsertion(getSourceLocation(BufferEnd),
1264 "\n");
Chris Lattner30a2fa12006-07-19 06:31:49 +00001265
Chris Lattner22eb9722006-06-18 05:43:12 +00001266 BufferPtr = CurPtr;
Chris Lattner30a2fa12006-07-19 06:31:49 +00001267
1268 // Finally, let the preprocessor handle this.
Chris Lattner02b436a2007-10-17 20:41:00 +00001269 return PP->HandleEndOfFile(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001270}
1271
Chris Lattner678c8802006-07-11 05:46:12 +00001272/// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
1273/// the specified lexer will return a tok::l_paren token, 0 if it is something
1274/// else and 2 if there are no more tokens in the buffer controlled by the
1275/// lexer.
1276unsigned Lexer::isNextPPTokenLParen() {
1277 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
1278
1279 // Switch to 'skipping' mode. This will ensure that we can lex a token
1280 // without emitting diagnostics, disables macro expansion, and will cause EOF
1281 // to return an EOF token instead of popping the include stack.
1282 LexingRawMode = true;
1283
1284 // Save state that can be changed while lexing so that we can restore it.
1285 const char *TmpBufferPtr = BufferPtr;
Chris Lattner40493eb2009-04-24 07:15:46 +00001286 bool inPPDirectiveMode = ParsingPreprocessorDirective;
Chris Lattner678c8802006-07-11 05:46:12 +00001287
Chris Lattner146762e2007-07-20 16:59:19 +00001288 Token Tok;
Chris Lattner8c204872006-10-14 05:19:21 +00001289 Tok.startToken();
Chris Lattner678c8802006-07-11 05:46:12 +00001290 LexTokenInternal(Tok);
1291
1292 // Restore state that may have changed.
1293 BufferPtr = TmpBufferPtr;
Chris Lattner40493eb2009-04-24 07:15:46 +00001294 ParsingPreprocessorDirective = inPPDirectiveMode;
Chris Lattner678c8802006-07-11 05:46:12 +00001295
1296 // Restore the lexer back to non-skipping mode.
1297 LexingRawMode = false;
1298
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001299 if (Tok.is(tok::eof))
Chris Lattner678c8802006-07-11 05:46:12 +00001300 return 2;
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001301 return Tok.is(tok::l_paren);
Chris Lattner678c8802006-07-11 05:46:12 +00001302}
1303
Chris Lattner22eb9722006-06-18 05:43:12 +00001304
1305/// LexTokenInternal - This implements a simple C family lexer. It is an
1306/// extremely performance critical piece of code. This assumes that the buffer
Chris Lattner5c349382009-07-07 05:05:42 +00001307/// has a null character at the end of the file. This returns a preprocessing
1308/// token, not a normal token, as such, it is an internal interface. It assumes
1309/// that the Flags of result have been cleared before calling this.
Chris Lattner146762e2007-07-20 16:59:19 +00001310void Lexer::LexTokenInternal(Token &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001311LexNextToken:
1312 // New token, can't need cleaning yet.
Chris Lattner146762e2007-07-20 16:59:19 +00001313 Result.clearFlag(Token::NeedsCleaning);
Chris Lattner8c204872006-10-14 05:19:21 +00001314 Result.setIdentifierInfo(0);
Chris Lattner22eb9722006-06-18 05:43:12 +00001315
1316 // CurPtr - Cache BufferPtr in an automatic variable.
1317 const char *CurPtr = BufferPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00001318
Chris Lattnereb54b592006-07-10 06:34:27 +00001319 // Small amounts of horizontal whitespace is very common between tokens.
1320 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
1321 ++CurPtr;
1322 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
1323 ++CurPtr;
Chris Lattner4d963442008-10-12 04:05:48 +00001324
1325 // If we are keeping whitespace and other tokens, just return what we just
1326 // skipped. The next lexer invocation will return the token after the
1327 // whitespace.
1328 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00001329 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner4d963442008-10-12 04:05:48 +00001330 return;
1331 }
1332
Chris Lattnereb54b592006-07-10 06:34:27 +00001333 BufferPtr = CurPtr;
Chris Lattner146762e2007-07-20 16:59:19 +00001334 Result.setFlag(Token::LeadingSpace);
Chris Lattnereb54b592006-07-10 06:34:27 +00001335 }
1336
Chris Lattner22eb9722006-06-18 05:43:12 +00001337 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
1338
1339 // Read a character, advancing over it.
1340 char Char = getAndAdvanceChar(CurPtr, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00001341 tok::TokenKind Kind;
1342
Chris Lattner22eb9722006-06-18 05:43:12 +00001343 switch (Char) {
1344 case 0: // Null.
1345 // Found end of file?
Chris Lattner2183a6e2006-07-18 06:36:12 +00001346 if (CurPtr-1 == BufferEnd) {
1347 // Read the PP instance variable into an automatic variable, because
1348 // LexEndOfFile will often delete 'this'.
Chris Lattner02b436a2007-10-17 20:41:00 +00001349 Preprocessor *PPCache = PP;
Chris Lattner2183a6e2006-07-18 06:36:12 +00001350 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
1351 return; // Got a token to return.
Chris Lattner02b436a2007-10-17 20:41:00 +00001352 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
1353 return PPCache->Lex(Result);
Chris Lattner2183a6e2006-07-18 06:36:12 +00001354 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001355
Chris Lattner6d27a162008-11-22 02:02:22 +00001356 if (!isLexingRawMode())
1357 Diag(CurPtr-1, diag::null_in_file);
Chris Lattner146762e2007-07-20 16:59:19 +00001358 Result.setFlag(Token::LeadingSpace);
Chris Lattner4d963442008-10-12 04:05:48 +00001359 if (SkipWhitespace(Result, CurPtr))
1360 return; // KeepWhitespaceMode
1361
Chris Lattner22eb9722006-06-18 05:43:12 +00001362 goto LexNextToken; // GCC isn't tail call eliminating.
1363 case '\n':
1364 case '\r':
1365 // If we are inside a preprocessor directive and we see the end of line,
1366 // we know we are done with the directive, so return an EOM token.
1367 if (ParsingPreprocessorDirective) {
1368 // Done parsing the "line".
1369 ParsingPreprocessorDirective = false;
1370
Chris Lattner457fc152006-07-29 06:30:25 +00001371 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattner097a8b82008-10-12 03:27:19 +00001372 SetCommentRetentionState(PP->getCommentRetentionState());
Chris Lattner457fc152006-07-29 06:30:25 +00001373
Chris Lattner22eb9722006-06-18 05:43:12 +00001374 // Since we consumed a newline, we are back at the start of a line.
1375 IsAtStartOfLine = true;
1376
Chris Lattnerb11c3232008-10-12 04:51:35 +00001377 Kind = tok::eom;
Chris Lattner22eb9722006-06-18 05:43:12 +00001378 break;
1379 }
1380 // The returned token is at the start of the line.
Chris Lattner146762e2007-07-20 16:59:19 +00001381 Result.setFlag(Token::StartOfLine);
Chris Lattner22eb9722006-06-18 05:43:12 +00001382 // No leading whitespace seen so far.
Chris Lattner146762e2007-07-20 16:59:19 +00001383 Result.clearFlag(Token::LeadingSpace);
Chris Lattner4d963442008-10-12 04:05:48 +00001384
1385 if (SkipWhitespace(Result, CurPtr))
1386 return; // KeepWhitespaceMode
Chris Lattner22eb9722006-06-18 05:43:12 +00001387 goto LexNextToken; // GCC isn't tail call eliminating.
1388 case ' ':
1389 case '\t':
1390 case '\f':
1391 case '\v':
Chris Lattnerb9b85972007-07-22 06:29:05 +00001392 SkipHorizontalWhitespace:
Chris Lattner146762e2007-07-20 16:59:19 +00001393 Result.setFlag(Token::LeadingSpace);
Chris Lattner4d963442008-10-12 04:05:48 +00001394 if (SkipWhitespace(Result, CurPtr))
1395 return; // KeepWhitespaceMode
Chris Lattnerb9b85972007-07-22 06:29:05 +00001396
1397 SkipIgnoredUnits:
1398 CurPtr = BufferPtr;
1399
1400 // If the next token is obviously a // or /* */ comment, skip it efficiently
1401 // too (without going through the big switch stmt).
Chris Lattner58827712009-01-16 22:39:25 +00001402 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
1403 Features.BCPLComment) {
Chris Lattnerb9b85972007-07-22 06:29:05 +00001404 SkipBCPLComment(Result, CurPtr+2);
1405 goto SkipIgnoredUnits;
Chris Lattner8637abd2008-10-12 03:22:02 +00001406 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
Chris Lattnerb9b85972007-07-22 06:29:05 +00001407 SkipBlockComment(Result, CurPtr+2);
1408 goto SkipIgnoredUnits;
1409 } else if (isHorizontalWhitespace(*CurPtr)) {
1410 goto SkipHorizontalWhitespace;
1411 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001412 goto LexNextToken; // GCC isn't tail call eliminating.
1413
Chris Lattner2b15cf72008-01-03 17:58:54 +00001414 // C99 6.4.4.1: Integer Constants.
1415 // C99 6.4.4.2: Floating Constants.
1416 case '0': case '1': case '2': case '3': case '4':
1417 case '5': case '6': case '7': case '8': case '9':
1418 // Notify MIOpt that we read a non-whitespace/non-comment token.
1419 MIOpt.ReadToken();
1420 return LexNumericConstant(Result, CurPtr);
1421
1422 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
Chris Lattner371ac8a2006-07-04 07:11:10 +00001423 // Notify MIOpt that we read a non-whitespace/non-comment token.
1424 MIOpt.ReadToken();
Chris Lattner22eb9722006-06-18 05:43:12 +00001425 Char = getCharAndSize(CurPtr, SizeTmp);
1426
1427 // Wide string literal.
1428 if (Char == '"')
Chris Lattnerd3e98952006-10-06 05:22:26 +00001429 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
1430 true);
Chris Lattner22eb9722006-06-18 05:43:12 +00001431
1432 // Wide character constant.
1433 if (Char == '\'')
1434 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
1435 // FALL THROUGH, treating L like the start of an identifier.
1436
1437 // C99 6.4.2: Identifiers.
1438 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
1439 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
1440 case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U':
1441 case 'V': case 'W': case 'X': case 'Y': case 'Z':
1442 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
1443 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
1444 case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u':
1445 case 'v': case 'w': case 'x': case 'y': case 'z':
1446 case '_':
Chris Lattner371ac8a2006-07-04 07:11:10 +00001447 // Notify MIOpt that we read a non-whitespace/non-comment token.
1448 MIOpt.ReadToken();
Chris Lattner22eb9722006-06-18 05:43:12 +00001449 return LexIdentifier(Result, CurPtr);
Chris Lattner2b15cf72008-01-03 17:58:54 +00001450
1451 case '$': // $ in identifiers.
1452 if (Features.DollarIdents) {
Chris Lattner6d27a162008-11-22 02:02:22 +00001453 if (!isLexingRawMode())
1454 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
Chris Lattner2b15cf72008-01-03 17:58:54 +00001455 // Notify MIOpt that we read a non-whitespace/non-comment token.
1456 MIOpt.ReadToken();
1457 return LexIdentifier(Result, CurPtr);
1458 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001459
Chris Lattnerb11c3232008-10-12 04:51:35 +00001460 Kind = tok::unknown;
Chris Lattner2b15cf72008-01-03 17:58:54 +00001461 break;
Chris Lattner22eb9722006-06-18 05:43:12 +00001462
1463 // C99 6.4.4: Character Constants.
1464 case '\'':
Chris Lattner371ac8a2006-07-04 07:11:10 +00001465 // Notify MIOpt that we read a non-whitespace/non-comment token.
1466 MIOpt.ReadToken();
Chris Lattner22eb9722006-06-18 05:43:12 +00001467 return LexCharConstant(Result, CurPtr);
1468
1469 // C99 6.4.5: String Literals.
1470 case '"':
Chris Lattner371ac8a2006-07-04 07:11:10 +00001471 // Notify MIOpt that we read a non-whitespace/non-comment token.
1472 MIOpt.ReadToken();
Chris Lattnerd3e98952006-10-06 05:22:26 +00001473 return LexStringLiteral(Result, CurPtr, false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001474
1475 // C99 6.4.6: Punctuators.
1476 case '?':
Chris Lattnerb11c3232008-10-12 04:51:35 +00001477 Kind = tok::question;
Chris Lattner22eb9722006-06-18 05:43:12 +00001478 break;
1479 case '[':
Chris Lattnerb11c3232008-10-12 04:51:35 +00001480 Kind = tok::l_square;
Chris Lattner22eb9722006-06-18 05:43:12 +00001481 break;
1482 case ']':
Chris Lattnerb11c3232008-10-12 04:51:35 +00001483 Kind = tok::r_square;
Chris Lattner22eb9722006-06-18 05:43:12 +00001484 break;
1485 case '(':
Chris Lattnerb11c3232008-10-12 04:51:35 +00001486 Kind = tok::l_paren;
Chris Lattner22eb9722006-06-18 05:43:12 +00001487 break;
1488 case ')':
Chris Lattnerb11c3232008-10-12 04:51:35 +00001489 Kind = tok::r_paren;
Chris Lattner22eb9722006-06-18 05:43:12 +00001490 break;
1491 case '{':
Chris Lattnerb11c3232008-10-12 04:51:35 +00001492 Kind = tok::l_brace;
Chris Lattner22eb9722006-06-18 05:43:12 +00001493 break;
1494 case '}':
Chris Lattnerb11c3232008-10-12 04:51:35 +00001495 Kind = tok::r_brace;
Chris Lattner22eb9722006-06-18 05:43:12 +00001496 break;
1497 case '.':
1498 Char = getCharAndSize(CurPtr, SizeTmp);
1499 if (Char >= '0' && Char <= '9') {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001500 // Notify MIOpt that we read a non-whitespace/non-comment token.
1501 MIOpt.ReadToken();
1502
Chris Lattner22eb9722006-06-18 05:43:12 +00001503 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
1504 } else if (Features.CPlusPlus && Char == '*') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00001505 Kind = tok::periodstar;
Chris Lattner22eb9722006-06-18 05:43:12 +00001506 CurPtr += SizeTmp;
1507 } else if (Char == '.' &&
1508 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00001509 Kind = tok::ellipsis;
Chris Lattner22eb9722006-06-18 05:43:12 +00001510 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1511 SizeTmp2, Result);
1512 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00001513 Kind = tok::period;
Chris Lattner22eb9722006-06-18 05:43:12 +00001514 }
1515 break;
1516 case '&':
1517 Char = getCharAndSize(CurPtr, SizeTmp);
1518 if (Char == '&') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00001519 Kind = tok::ampamp;
Chris Lattner22eb9722006-06-18 05:43:12 +00001520 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1521 } else if (Char == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00001522 Kind = tok::ampequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00001523 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1524 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00001525 Kind = tok::amp;
Chris Lattner22eb9722006-06-18 05:43:12 +00001526 }
1527 break;
1528 case '*':
1529 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00001530 Kind = tok::starequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00001531 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1532 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00001533 Kind = tok::star;
Chris Lattner22eb9722006-06-18 05:43:12 +00001534 }
1535 break;
1536 case '+':
1537 Char = getCharAndSize(CurPtr, SizeTmp);
1538 if (Char == '+') {
Chris Lattner22eb9722006-06-18 05:43:12 +00001539 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00001540 Kind = tok::plusplus;
Chris Lattner22eb9722006-06-18 05:43:12 +00001541 } else if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00001542 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00001543 Kind = tok::plusequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00001544 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00001545 Kind = tok::plus;
Chris Lattner22eb9722006-06-18 05:43:12 +00001546 }
1547 break;
1548 case '-':
1549 Char = getCharAndSize(CurPtr, SizeTmp);
Chris Lattnerb11c3232008-10-12 04:51:35 +00001550 if (Char == '-') { // --
Chris Lattner22eb9722006-06-18 05:43:12 +00001551 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00001552 Kind = tok::minusminus;
Chris Lattner22eb9722006-06-18 05:43:12 +00001553 } else if (Char == '>' && Features.CPlusPlus &&
Chris Lattnerb11c3232008-10-12 04:51:35 +00001554 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
Chris Lattner22eb9722006-06-18 05:43:12 +00001555 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1556 SizeTmp2, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00001557 Kind = tok::arrowstar;
1558 } else if (Char == '>') { // ->
Chris Lattner22eb9722006-06-18 05:43:12 +00001559 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00001560 Kind = tok::arrow;
1561 } else if (Char == '=') { // -=
Chris Lattner22eb9722006-06-18 05:43:12 +00001562 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00001563 Kind = tok::minusequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00001564 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00001565 Kind = tok::minus;
Chris Lattner22eb9722006-06-18 05:43:12 +00001566 }
1567 break;
1568 case '~':
Chris Lattnerb11c3232008-10-12 04:51:35 +00001569 Kind = tok::tilde;
Chris Lattner22eb9722006-06-18 05:43:12 +00001570 break;
1571 case '!':
1572 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00001573 Kind = tok::exclaimequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00001574 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1575 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00001576 Kind = tok::exclaim;
Chris Lattner22eb9722006-06-18 05:43:12 +00001577 }
1578 break;
1579 case '/':
1580 // 6.4.9: Comments
1581 Char = getCharAndSize(CurPtr, SizeTmp);
1582 if (Char == '/') { // BCPL comment.
Chris Lattner58827712009-01-16 22:39:25 +00001583 // Even if BCPL comments are disabled (e.g. in C89 mode), we generally
1584 // want to lex this as a comment. There is one problem with this though,
1585 // that in one particular corner case, this can change the behavior of the
1586 // resultant program. For example, In "foo //**/ bar", C89 would lex
1587 // this as "foo / bar" and langauges with BCPL comments would lex it as
1588 // "foo". Check to see if the character after the second slash is a '*'.
1589 // If so, we will lex that as a "/" instead of the start of a comment.
1590 if (Features.BCPLComment ||
1591 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*') {
1592 if (SkipBCPLComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
1593 return; // KeepCommentMode
Chris Lattnere01e7582008-10-12 04:15:42 +00001594
Chris Lattner58827712009-01-16 22:39:25 +00001595 // It is common for the tokens immediately after a // comment to be
1596 // whitespace (indentation for the next line). Instead of going through
1597 // the big switch, handle it efficiently now.
1598 goto SkipIgnoredUnits;
1599 }
1600 }
1601
1602 if (Char == '*') { // /**/ comment.
Chris Lattner457fc152006-07-29 06:30:25 +00001603 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattnere01e7582008-10-12 04:15:42 +00001604 return; // KeepCommentMode
1605 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattner58827712009-01-16 22:39:25 +00001606 }
1607
1608 if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00001609 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00001610 Kind = tok::slashequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00001611 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00001612 Kind = tok::slash;
Chris Lattner22eb9722006-06-18 05:43:12 +00001613 }
1614 break;
1615 case '%':
1616 Char = getCharAndSize(CurPtr, SizeTmp);
1617 if (Char == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00001618 Kind = tok::percentequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00001619 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1620 } else if (Features.Digraphs && Char == '>') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00001621 Kind = tok::r_brace; // '%>' -> '}'
Chris Lattner22eb9722006-06-18 05:43:12 +00001622 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1623 } else if (Features.Digraphs && Char == ':') {
1624 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner2b271db2006-07-15 05:41:09 +00001625 Char = getCharAndSize(CurPtr, SizeTmp);
1626 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00001627 Kind = tok::hashhash; // '%:%:' -> '##'
Chris Lattner22eb9722006-06-18 05:43:12 +00001628 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1629 SizeTmp2, Result);
Chris Lattner2b271db2006-07-15 05:41:09 +00001630 } else if (Char == '@' && Features.Microsoft) { // %:@ -> #@ -> Charize
Chris Lattner2b271db2006-07-15 05:41:09 +00001631 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner6d27a162008-11-22 02:02:22 +00001632 if (!isLexingRawMode())
1633 Diag(BufferPtr, diag::charize_microsoft_ext);
Chris Lattnerb11c3232008-10-12 04:51:35 +00001634 Kind = tok::hashat;
Chris Lattner2534324a2009-03-18 20:58:27 +00001635 } else { // '%:' -> '#'
Chris Lattner22eb9722006-06-18 05:43:12 +00001636 // We parsed a # character. If this occurs at the start of the line,
1637 // it's actually the start of a preprocessing directive. Callback to
1638 // the preprocessor to handle it.
1639 // FIXME: -fpreprocessed mode??
Chris Lattnerff96dd02009-05-13 06:10:29 +00001640 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer) {
Chris Lattner2534324a2009-03-18 20:58:27 +00001641 FormTokenWithChars(Result, CurPtr, tok::hash);
Chris Lattner02b436a2007-10-17 20:41:00 +00001642 PP->HandleDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001643
1644 // As an optimization, if the preprocessor didn't switch lexers, tail
1645 // recurse.
Chris Lattner02b436a2007-10-17 20:41:00 +00001646 if (PP->isCurrentLexer(this)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001647 // Start a new token. If this is a #include or something, the PP may
1648 // want us starting at the beginning of the line again. If so, set
1649 // the StartOfLine flag.
1650 if (IsAtStartOfLine) {
Chris Lattner146762e2007-07-20 16:59:19 +00001651 Result.setFlag(Token::StartOfLine);
Chris Lattner22eb9722006-06-18 05:43:12 +00001652 IsAtStartOfLine = false;
1653 }
1654 goto LexNextToken; // GCC isn't tail call eliminating.
1655 }
1656
Chris Lattner02b436a2007-10-17 20:41:00 +00001657 return PP->Lex(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001658 }
Chris Lattner2534324a2009-03-18 20:58:27 +00001659
1660 Kind = tok::hash;
Chris Lattner22eb9722006-06-18 05:43:12 +00001661 }
1662 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00001663 Kind = tok::percent;
Chris Lattner22eb9722006-06-18 05:43:12 +00001664 }
1665 break;
1666 case '<':
1667 Char = getCharAndSize(CurPtr, SizeTmp);
1668 if (ParsingFilename) {
Chris Lattnerb40289b2009-04-17 23:56:52 +00001669 return LexAngledStringLiteral(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +00001670 } else if (Char == '<' &&
1671 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00001672 Kind = tok::lesslessequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00001673 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1674 SizeTmp2, Result);
1675 } else if (Char == '<') {
Chris Lattner22eb9722006-06-18 05:43:12 +00001676 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00001677 Kind = tok::lessless;
Chris Lattner22eb9722006-06-18 05:43:12 +00001678 } else if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00001679 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00001680 Kind = tok::lessequal;
1681 } else if (Features.Digraphs && Char == ':') { // '<:' -> '['
Chris Lattner22eb9722006-06-18 05:43:12 +00001682 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00001683 Kind = tok::l_square;
1684 } else if (Features.Digraphs && Char == '%') { // '<%' -> '{'
Chris Lattner22eb9722006-06-18 05:43:12 +00001685 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00001686 Kind = tok::l_brace;
Chris Lattner22eb9722006-06-18 05:43:12 +00001687 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00001688 Kind = tok::less;
Chris Lattner22eb9722006-06-18 05:43:12 +00001689 }
1690 break;
1691 case '>':
1692 Char = getCharAndSize(CurPtr, SizeTmp);
1693 if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00001694 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00001695 Kind = tok::greaterequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00001696 } else if (Char == '>' &&
1697 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00001698 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1699 SizeTmp2, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00001700 Kind = tok::greatergreaterequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00001701 } else if (Char == '>') {
Chris Lattner22eb9722006-06-18 05:43:12 +00001702 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00001703 Kind = tok::greatergreater;
Chris Lattner22eb9722006-06-18 05:43:12 +00001704 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00001705 Kind = tok::greater;
Chris Lattner22eb9722006-06-18 05:43:12 +00001706 }
1707 break;
1708 case '^':
1709 Char = getCharAndSize(CurPtr, SizeTmp);
1710 if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00001711 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00001712 Kind = tok::caretequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00001713 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00001714 Kind = tok::caret;
Chris Lattner22eb9722006-06-18 05:43:12 +00001715 }
1716 break;
1717 case '|':
1718 Char = getCharAndSize(CurPtr, SizeTmp);
1719 if (Char == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00001720 Kind = tok::pipeequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00001721 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1722 } else if (Char == '|') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00001723 Kind = tok::pipepipe;
Chris Lattner22eb9722006-06-18 05:43:12 +00001724 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1725 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00001726 Kind = tok::pipe;
Chris Lattner22eb9722006-06-18 05:43:12 +00001727 }
1728 break;
1729 case ':':
1730 Char = getCharAndSize(CurPtr, SizeTmp);
1731 if (Features.Digraphs && Char == '>') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00001732 Kind = tok::r_square; // ':>' -> ']'
Chris Lattner22eb9722006-06-18 05:43:12 +00001733 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1734 } else if (Features.CPlusPlus && Char == ':') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00001735 Kind = tok::coloncolon;
Chris Lattner22eb9722006-06-18 05:43:12 +00001736 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1737 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00001738 Kind = tok::colon;
Chris Lattner22eb9722006-06-18 05:43:12 +00001739 }
1740 break;
1741 case ';':
Chris Lattnerb11c3232008-10-12 04:51:35 +00001742 Kind = tok::semi;
Chris Lattner22eb9722006-06-18 05:43:12 +00001743 break;
1744 case '=':
1745 Char = getCharAndSize(CurPtr, SizeTmp);
1746 if (Char == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00001747 Kind = tok::equalequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00001748 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1749 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00001750 Kind = tok::equal;
Chris Lattner22eb9722006-06-18 05:43:12 +00001751 }
1752 break;
1753 case ',':
Chris Lattnerb11c3232008-10-12 04:51:35 +00001754 Kind = tok::comma;
Chris Lattner22eb9722006-06-18 05:43:12 +00001755 break;
1756 case '#':
1757 Char = getCharAndSize(CurPtr, SizeTmp);
1758 if (Char == '#') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00001759 Kind = tok::hashhash;
Chris Lattner22eb9722006-06-18 05:43:12 +00001760 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner2b271db2006-07-15 05:41:09 +00001761 } else if (Char == '@' && Features.Microsoft) { // #@ -> Charize
Chris Lattnerb11c3232008-10-12 04:51:35 +00001762 Kind = tok::hashat;
Chris Lattner6d27a162008-11-22 02:02:22 +00001763 if (!isLexingRawMode())
1764 Diag(BufferPtr, diag::charize_microsoft_ext);
Chris Lattner2b271db2006-07-15 05:41:09 +00001765 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001766 } else {
Chris Lattner22eb9722006-06-18 05:43:12 +00001767 // We parsed a # character. If this occurs at the start of the line,
1768 // it's actually the start of a preprocessing directive. Callback to
1769 // the preprocessor to handle it.
Chris Lattner505c5472006-07-03 00:55:48 +00001770 // FIXME: -fpreprocessed mode??
Chris Lattnerff96dd02009-05-13 06:10:29 +00001771 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer) {
Chris Lattner2534324a2009-03-18 20:58:27 +00001772 FormTokenWithChars(Result, CurPtr, tok::hash);
Chris Lattner02b436a2007-10-17 20:41:00 +00001773 PP->HandleDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001774
1775 // As an optimization, if the preprocessor didn't switch lexers, tail
1776 // recurse.
Chris Lattner02b436a2007-10-17 20:41:00 +00001777 if (PP->isCurrentLexer(this)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001778 // Start a new token. If this is a #include or something, the PP may
1779 // want us starting at the beginning of the line again. If so, set
1780 // the StartOfLine flag.
1781 if (IsAtStartOfLine) {
Chris Lattner146762e2007-07-20 16:59:19 +00001782 Result.setFlag(Token::StartOfLine);
Chris Lattner22eb9722006-06-18 05:43:12 +00001783 IsAtStartOfLine = false;
1784 }
1785 goto LexNextToken; // GCC isn't tail call eliminating.
1786 }
Chris Lattner02b436a2007-10-17 20:41:00 +00001787 return PP->Lex(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001788 }
Chris Lattner2534324a2009-03-18 20:58:27 +00001789
1790 Kind = tok::hash;
Chris Lattner22eb9722006-06-18 05:43:12 +00001791 }
1792 break;
1793
Chris Lattner2b15cf72008-01-03 17:58:54 +00001794 case '@':
1795 // Objective C support.
1796 if (CurPtr[-1] == '@' && Features.ObjC1)
Chris Lattnerb11c3232008-10-12 04:51:35 +00001797 Kind = tok::at;
Chris Lattner2b15cf72008-01-03 17:58:54 +00001798 else
Chris Lattnerb11c3232008-10-12 04:51:35 +00001799 Kind = tok::unknown;
Chris Lattner2b15cf72008-01-03 17:58:54 +00001800 break;
1801
Chris Lattner22eb9722006-06-18 05:43:12 +00001802 case '\\':
Chris Lattner505c5472006-07-03 00:55:48 +00001803 // FIXME: UCN's.
Chris Lattner22eb9722006-06-18 05:43:12 +00001804 // FALL THROUGH.
1805 default:
Chris Lattnerb11c3232008-10-12 04:51:35 +00001806 Kind = tok::unknown;
Chris Lattner041bef82006-07-11 05:52:53 +00001807 break;
Chris Lattner22eb9722006-06-18 05:43:12 +00001808 }
1809
Chris Lattner371ac8a2006-07-04 07:11:10 +00001810 // Notify MIOpt that we read a non-whitespace/non-comment token.
1811 MIOpt.ReadToken();
1812
Chris Lattnerd01e2912006-06-18 16:22:51 +00001813 // Update the location of token as well as BufferPtr.
Chris Lattnerb11c3232008-10-12 04:51:35 +00001814 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner22eb9722006-06-18 05:43:12 +00001815}