blob: 974b6900b76db8d9a57564b642e1ce1b18dd296e [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- Lexer.cpp - C Language Family Lexer ------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
Chris Lattnerd2177732007-07-20 16:59:19 +000010// This file implements the Lexer and Token interfaces.
Reid Spencer5f016e22007-07-11 17:01:13 +000011//
12//===----------------------------------------------------------------------===//
13//
14// TODO: GCC Diagnostics emitted by the lexer:
15// PEDWARN: (form feed|vertical tab) in preprocessing directive
16//
17// Universal characters, unicode, char mapping:
18// WARNING: `%.*s' is not in NFKC
19// WARNING: `%.*s' is not in NFC
20//
21// Other:
22// TODO: Options to support:
23// -fexec-charset,-fwide-exec-charset
24//
25//===----------------------------------------------------------------------===//
26
27#include "clang/Lex/Lexer.h"
28#include "clang/Lex/Preprocessor.h"
Chris Lattner500d3292009-01-29 05:15:15 +000029#include "clang/Lex/LexDiagnostic.h"
Chris Lattner9dc1f532007-07-20 16:37:10 +000030#include "clang/Basic/SourceManager.h"
Chris Lattner409a0362007-07-22 18:38:25 +000031#include "llvm/Support/Compiler.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000032#include "llvm/Support/MemoryBuffer.h"
33#include <cctype>
34using namespace clang;
35
36static void InitCharacterInfo();
37
Chris Lattnerdbf388b2007-10-07 08:47:24 +000038//===----------------------------------------------------------------------===//
39// Token Class Implementation
40//===----------------------------------------------------------------------===//
41
42/// isObjCAtKeyword - Return true if we have an ObjC keyword identifier.
43bool Token::isObjCAtKeyword(tok::ObjCKeywordKind objcKey) const {
Douglas Gregorbec1c9d2008-12-01 21:46:47 +000044 if (IdentifierInfo *II = getIdentifierInfo())
45 return II->getObjCKeywordID() == objcKey;
46 return false;
Chris Lattnerdbf388b2007-10-07 08:47:24 +000047}
48
49/// getObjCKeywordID - Return the ObjC keyword kind.
50tok::ObjCKeywordKind Token::getObjCKeywordID() const {
51 IdentifierInfo *specId = getIdentifierInfo();
52 return specId ? specId->getObjCKeywordID() : tok::objc_not_keyword;
53}
54
Chris Lattner53702cd2007-12-13 01:59:49 +000055
Chris Lattnerdbf388b2007-10-07 08:47:24 +000056//===----------------------------------------------------------------------===//
57// Lexer Class Implementation
58//===----------------------------------------------------------------------===//
59
Chris Lattner22d91ca2009-01-17 06:55:17 +000060void Lexer::InitLexer(const char *BufStart, const char *BufPtr,
61 const char *BufEnd) {
62 InitCharacterInfo();
63
64 BufferStart = BufStart;
65 BufferPtr = BufPtr;
66 BufferEnd = BufEnd;
67
68 assert(BufEnd[0] == 0 &&
69 "We assume that the input buffer has a null character at the end"
70 " to simplify lexing!");
71
72 Is_PragmaLexer = false;
73
74 // Start of the file is a start of line.
75 IsAtStartOfLine = true;
76
77 // We are not after parsing a #.
78 ParsingPreprocessorDirective = false;
79
80 // We are not after parsing #include.
81 ParsingFilename = false;
82
83 // We are not in raw mode. Raw mode disables diagnostics and interpretation
84 // of tokens (e.g. identifiers, thus disabling macro expansion). It is used
85 // to quickly lex the tokens of the buffer, e.g. when handling a "#if 0" block
86 // or otherwise skipping over tokens.
87 LexingRawMode = false;
88
89 // Default to not keeping comments.
90 ExtendedTokenMode = 0;
91}
92
Chris Lattner0770dab2009-01-17 07:56:59 +000093/// Lexer constructor - Create a new lexer object for the specified buffer
94/// with the specified preprocessor managing the lexing process. This lexer
95/// assumes that the associated file buffer and Preprocessor objects will
96/// outlive it, so it doesn't take ownership of either of them.
Chris Lattner88d3ac12009-01-17 08:03:42 +000097Lexer::Lexer(FileID FID, Preprocessor &PP)
98 : PreprocessorLexer(&PP, FID),
99 FileLoc(PP.getSourceManager().getLocForStartOfFile(FID)),
100 Features(PP.getLangOptions()) {
Chris Lattner0770dab2009-01-17 07:56:59 +0000101
Chris Lattner88d3ac12009-01-17 08:03:42 +0000102 const llvm::MemoryBuffer *InputFile = PP.getSourceManager().getBuffer(FID);
Chris Lattner0770dab2009-01-17 07:56:59 +0000103
104 InitLexer(InputFile->getBufferStart(), InputFile->getBufferStart(),
105 InputFile->getBufferEnd());
106
107 // Default to keeping comments if the preprocessor wants them.
108 SetCommentRetentionState(PP.getCommentRetentionState());
109}
Chris Lattnerdbf388b2007-10-07 08:47:24 +0000110
Chris Lattner168ae2d2007-10-17 20:41:00 +0000111/// Lexer constructor - Create a new raw lexer object. This object is only
Chris Lattner590f0cc2008-10-12 01:15:46 +0000112/// suitable for calls to 'LexRawToken'. This lexer assumes that the text
113/// range will outlive it, so it doesn't take ownership of it.
Chris Lattner168ae2d2007-10-17 20:41:00 +0000114Lexer::Lexer(SourceLocation fileloc, const LangOptions &features,
Chris Lattnerde96c0f2009-01-17 07:42:27 +0000115 const char *BufStart, const char *BufPtr, const char *BufEnd)
Chris Lattnerc6fe32a2009-01-17 03:48:08 +0000116 : FileLoc(fileloc), Features(features) {
Chris Lattner22d91ca2009-01-17 06:55:17 +0000117
Chris Lattner22d91ca2009-01-17 06:55:17 +0000118 InitLexer(BufStart, BufPtr, BufEnd);
Chris Lattner168ae2d2007-10-17 20:41:00 +0000119
120 // We *are* in raw mode.
121 LexingRawMode = true;
Chris Lattner168ae2d2007-10-17 20:41:00 +0000122}
123
Chris Lattner025c3a62009-01-17 07:35:14 +0000124/// Lexer constructor - Create a new raw lexer object. This object is only
125/// suitable for calls to 'LexRawToken'. This lexer assumes that the text
126/// range will outlive it, so it doesn't take ownership of it.
127Lexer::Lexer(FileID FID, const SourceManager &SM, const LangOptions &features)
128 : FileLoc(SM.getLocForStartOfFile(FID)), Features(features) {
129 const llvm::MemoryBuffer *FromFile = SM.getBuffer(FID);
130
131 InitLexer(FromFile->getBufferStart(), FromFile->getBufferStart(),
132 FromFile->getBufferEnd());
133
134 // We *are* in raw mode.
135 LexingRawMode = true;
136}
137
Chris Lattner42e00d12009-01-17 08:27:52 +0000138/// Create_PragmaLexer: Lexer constructor - Create a new lexer object for
139/// _Pragma expansion. This has a variety of magic semantics that this method
140/// sets up. It returns a new'd Lexer that must be delete'd when done.
141///
142/// On entrance to this routine, TokStartLoc is a macro location which has a
143/// spelling loc that indicates the bytes to be lexed for the token and an
144/// instantiation location that indicates where all lexed tokens should be
145/// "expanded from".
146///
147/// FIXME: It would really be nice to make _Pragma just be a wrapper around a
148/// normal lexer that remaps tokens as they fly by. This would require making
149/// Preprocessor::Lex virtual. Given that, we could just dump in a magic lexer
150/// interface that could handle this stuff. This would pull GetMappedTokenLoc
151/// out of the critical path of the lexer!
152///
Chris Lattnerbcc2a672009-01-19 06:46:35 +0000153Lexer *Lexer::Create_PragmaLexer(SourceLocation SpellingLoc,
Chris Lattnere7fb4842009-02-15 20:52:18 +0000154 SourceLocation InstantiationLocStart,
155 SourceLocation InstantiationLocEnd,
Chris Lattnerbcc2a672009-01-19 06:46:35 +0000156 unsigned TokLen, Preprocessor &PP) {
Chris Lattner42e00d12009-01-17 08:27:52 +0000157 SourceManager &SM = PP.getSourceManager();
Chris Lattner42e00d12009-01-17 08:27:52 +0000158
159 // Create the lexer as if we were going to lex the file normally.
Chris Lattnera11d6172009-01-19 07:46:45 +0000160 FileID SpellingFID = SM.getFileID(SpellingLoc);
Chris Lattnerbcc2a672009-01-19 06:46:35 +0000161 Lexer *L = new Lexer(SpellingFID, PP);
Chris Lattner42e00d12009-01-17 08:27:52 +0000162
163 // Now that the lexer is created, change the start/end locations so that we
164 // just lex the subsection of the file that we want. This is lexing from a
165 // scratch buffer.
166 const char *StrData = SM.getCharacterData(SpellingLoc);
167
168 L->BufferPtr = StrData;
169 L->BufferEnd = StrData+TokLen;
Chris Lattner1fa49532009-03-08 08:08:45 +0000170 assert(L->BufferEnd[0] == 0 && "Buffer is not nul terminated!");
Chris Lattner42e00d12009-01-17 08:27:52 +0000171
172 // Set the SourceLocation with the remapping information. This ensures that
173 // GetMappedTokenLoc will remap the tokens as they are lexed.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000174 L->FileLoc = SM.createInstantiationLoc(SM.getLocForStartOfFile(SpellingFID),
Chris Lattnere7fb4842009-02-15 20:52:18 +0000175 InstantiationLocStart,
176 InstantiationLocEnd, TokLen);
Chris Lattner42e00d12009-01-17 08:27:52 +0000177
178 // Ensure that the lexer thinks it is inside a directive, so that end \n will
179 // return an EOM token.
180 L->ParsingPreprocessorDirective = true;
181
182 // This lexer really is for _Pragma.
183 L->Is_PragmaLexer = true;
184 return L;
185}
186
Chris Lattner168ae2d2007-10-17 20:41:00 +0000187
Reid Spencer5f016e22007-07-11 17:01:13 +0000188/// Stringify - Convert the specified string into a C string, with surrounding
189/// ""'s, and with escaped \ and " characters.
190std::string Lexer::Stringify(const std::string &Str, bool Charify) {
191 std::string Result = Str;
192 char Quote = Charify ? '\'' : '"';
193 for (unsigned i = 0, e = Result.size(); i != e; ++i) {
194 if (Result[i] == '\\' || Result[i] == Quote) {
195 Result.insert(Result.begin()+i, '\\');
196 ++i; ++e;
197 }
198 }
199 return Result;
200}
201
Chris Lattnerd8e30832007-07-24 06:57:14 +0000202/// Stringify - Convert the specified string into a C string by escaping '\'
203/// and " characters. This does not add surrounding ""'s to the string.
204void Lexer::Stringify(llvm::SmallVectorImpl<char> &Str) {
205 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
206 if (Str[i] == '\\' || Str[i] == '"') {
207 Str.insert(Str.begin()+i, '\\');
208 ++i; ++e;
209 }
210 }
211}
212
Reid Spencer5f016e22007-07-11 17:01:13 +0000213
Chris Lattner9a611942007-10-17 21:18:47 +0000214/// MeasureTokenLength - Relex the token at the specified location and return
215/// its length in bytes in the input file. If the token needs cleaning (e.g.
216/// includes a trigraph or an escaped newline) then this count includes bytes
217/// that are part of that.
218unsigned Lexer::MeasureTokenLength(SourceLocation Loc,
Chris Lattner2c78b872009-04-14 23:22:57 +0000219 const SourceManager &SM,
220 const LangOptions &LangOpts) {
Chris Lattner9a611942007-10-17 21:18:47 +0000221 // TODO: this could be special cased for common tokens like identifiers, ')',
222 // etc to make this faster, if it mattered. Just look at StrData[0] to handle
223 // all obviously single-char tokens. This could use
224 // Lexer::isObviouslySimpleCharacter for example to handle identifiers or
225 // something.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000226
227 // If this comes from a macro expansion, we really do want the macro name, not
228 // the token this macro expanded to.
Chris Lattner363fdc22009-01-26 22:24:27 +0000229 Loc = SM.getInstantiationLoc(Loc);
230 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
Chris Lattner83503942009-01-17 08:30:10 +0000231 std::pair<const char *,const char *> Buffer = SM.getBufferData(LocInfo.first);
232 const char *StrData = Buffer.first+LocInfo.second;
233
Chris Lattner9a611942007-10-17 21:18:47 +0000234 // Create a lexer starting at the beginning of this token.
Chris Lattnerde96c0f2009-01-17 07:42:27 +0000235 Lexer TheLexer(Loc, LangOpts, Buffer.first, StrData, Buffer.second);
Chris Lattner9a611942007-10-17 21:18:47 +0000236 Token TheTok;
Chris Lattner590f0cc2008-10-12 01:15:46 +0000237 TheLexer.LexFromRawLexer(TheTok);
Chris Lattner9a611942007-10-17 21:18:47 +0000238 return TheTok.getLength();
239}
240
Reid Spencer5f016e22007-07-11 17:01:13 +0000241//===----------------------------------------------------------------------===//
242// Character information.
243//===----------------------------------------------------------------------===//
244
Reid Spencer5f016e22007-07-11 17:01:13 +0000245enum {
246 CHAR_HORZ_WS = 0x01, // ' ', '\t', '\f', '\v'. Note, no '\0'
247 CHAR_VERT_WS = 0x02, // '\r', '\n'
248 CHAR_LETTER = 0x04, // a-z,A-Z
249 CHAR_NUMBER = 0x08, // 0-9
250 CHAR_UNDER = 0x10, // _
251 CHAR_PERIOD = 0x20 // .
252};
253
Chris Lattner03b98662009-07-07 17:09:54 +0000254// Statically initialize CharInfo table based on ASCII character set
255// Reference: FreeBSD 7.2 /usr/share/misc/ascii
256static const unsigned char CharInfo[256] =
257{
258// 0 NUL 1 SOH 2 STX 3 ETX
259// 4 EOT 5 ENQ 6 ACK 7 BEL
260 0 , 0 , 0 , 0 ,
261 0 , 0 , 0 , 0 ,
262// 8 BS 9 HT 10 NL 11 VT
263//12 NP 13 CR 14 SO 15 SI
264 0 , CHAR_HORZ_WS, CHAR_VERT_WS, CHAR_HORZ_WS,
265 CHAR_HORZ_WS, CHAR_VERT_WS, 0 , 0 ,
266//16 DLE 17 DC1 18 DC2 19 DC3
267//20 DC4 21 NAK 22 SYN 23 ETB
268 0 , 0 , 0 , 0 ,
269 0 , 0 , 0 , 0 ,
270//24 CAN 25 EM 26 SUB 27 ESC
271//28 FS 29 GS 30 RS 31 US
272 0 , 0 , 0 , 0 ,
273 0 , 0 , 0 , 0 ,
274//32 SP 33 ! 34 " 35 #
275//36 $ 37 % 38 & 39 '
276 CHAR_HORZ_WS, 0 , 0 , 0 ,
277 0 , 0 , 0 , 0 ,
278//40 ( 41 ) 42 * 43 +
279//44 , 45 - 46 . 47 /
280 0 , 0 , 0 , 0 ,
281 0 , 0 , CHAR_PERIOD , 0 ,
282//48 0 49 1 50 2 51 3
283//52 4 53 5 54 6 55 7
284 CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER ,
285 CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER ,
286//56 8 57 9 58 : 59 ;
287//60 < 61 = 62 > 63 ?
288 CHAR_NUMBER , CHAR_NUMBER , 0 , 0 ,
289 0 , 0 , 0 , 0 ,
290//64 @ 65 A 66 B 67 C
291//68 D 69 E 70 F 71 G
292 0 , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
293 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
294//72 H 73 I 74 J 75 K
295//76 L 77 M 78 N 79 O
296 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
297 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
298//80 P 81 Q 82 R 83 S
299//84 T 85 U 86 V 87 W
300 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
301 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
302//88 X 89 Y 90 Z 91 [
303//92 \ 93 ] 94 ^ 95 _
304 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , 0 ,
305 0 , 0 , 0 , CHAR_UNDER ,
306//96 ` 97 a 98 b 99 c
307//100 d 101 e 102 f 103 g
308 0 , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
309 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
310//104 h 105 i 106 j 107 k
311//108 l 109 m 110 n 111 o
312 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
313 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
314//112 p 113 q 114 r 115 s
315//116 t 117 u 118 v 119 w
316 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
317 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
318//120 x 121 y 122 z 123 {
319//124 | 125 } 126 ~ 127 DEL
320 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , 0 ,
321 0 , 0 , 0 , 0
322};
323
Reid Spencer5f016e22007-07-11 17:01:13 +0000324static void InitCharacterInfo() {
325 static bool isInited = false;
326 if (isInited) return;
Chris Lattner03b98662009-07-07 17:09:54 +0000327 // check the statically-initialized CharInfo table
328 assert(CHAR_HORZ_WS == CharInfo[(int)' ']);
329 assert(CHAR_HORZ_WS == CharInfo[(int)'\t']);
330 assert(CHAR_HORZ_WS == CharInfo[(int)'\f']);
331 assert(CHAR_HORZ_WS == CharInfo[(int)'\v']);
332 assert(CHAR_VERT_WS == CharInfo[(int)'\n']);
333 assert(CHAR_VERT_WS == CharInfo[(int)'\r']);
334 assert(CHAR_UNDER == CharInfo[(int)'_']);
335 assert(CHAR_PERIOD == CharInfo[(int)'.']);
336 for (unsigned i = 'a'; i <= 'z'; ++i) {
337 assert(CHAR_LETTER == CharInfo[i]);
338 assert(CHAR_LETTER == CharInfo[i+'A'-'a']);
339 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000340 for (unsigned i = '0'; i <= '9'; ++i)
Chris Lattner03b98662009-07-07 17:09:54 +0000341 assert(CHAR_NUMBER == CharInfo[i]);
342 isInited = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000343}
344
Chris Lattner03b98662009-07-07 17:09:54 +0000345
Reid Spencer5f016e22007-07-11 17:01:13 +0000346/// isIdentifierBody - Return true if this is the body character of an
347/// identifier, which is [a-zA-Z0-9_].
348static inline bool isIdentifierBody(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000349 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER)) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000350}
351
352/// isHorizontalWhitespace - Return true if this character is horizontal
353/// whitespace: ' ', '\t', '\f', '\v'. Note that this returns false for '\0'.
354static inline bool isHorizontalWhitespace(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000355 return (CharInfo[c] & CHAR_HORZ_WS) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000356}
357
358/// isWhitespace - Return true if this character is horizontal or vertical
359/// whitespace: ' ', '\t', '\f', '\v', '\n', '\r'. Note that this returns false
360/// for '\0'.
361static inline bool isWhitespace(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000362 return (CharInfo[c] & (CHAR_HORZ_WS|CHAR_VERT_WS)) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000363}
364
365/// isNumberBody - Return true if this is the body character of an
366/// preprocessing number, which is [a-zA-Z0-9_.].
367static inline bool isNumberBody(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000368 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER|CHAR_PERIOD)) ?
369 true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000370}
371
372
373//===----------------------------------------------------------------------===//
374// Diagnostics forwarding code.
375//===----------------------------------------------------------------------===//
376
Chris Lattner409a0362007-07-22 18:38:25 +0000377/// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
378/// lexer buffer was all instantiated at a single point, perform the mapping.
379/// This is currently only used for _Pragma implementation, so it is the slow
380/// path of the hot getSourceLocation method. Do not allow it to be inlined.
381static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
382 SourceLocation FileLoc,
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000383 unsigned CharNo,
384 unsigned TokLen) DISABLE_INLINE;
Chris Lattner409a0362007-07-22 18:38:25 +0000385static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
386 SourceLocation FileLoc,
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000387 unsigned CharNo, unsigned TokLen) {
Chris Lattnere7fb4842009-02-15 20:52:18 +0000388 assert(FileLoc.isMacroID() && "Must be an instantiation");
389
Chris Lattner409a0362007-07-22 18:38:25 +0000390 // Otherwise, we're lexing "mapped tokens". This is used for things like
391 // _Pragma handling. Combine the instantiation location of FileLoc with the
Chris Lattnerdf7c17a2009-01-16 07:00:02 +0000392 // spelling location.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000393 SourceManager &SM = PP.getSourceManager();
Chris Lattner409a0362007-07-22 18:38:25 +0000394
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000395 // Create a new SLoc which is expanded from Instantiation(FileLoc) but whose
Chris Lattnerdf7c17a2009-01-16 07:00:02 +0000396 // characters come from spelling(FileLoc)+Offset.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000397 SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc);
Chris Lattnerbcc2a672009-01-19 06:46:35 +0000398 SpellingLoc = SpellingLoc.getFileLocWithOffset(CharNo);
Chris Lattnere7fb4842009-02-15 20:52:18 +0000399
400 // Figure out the expansion loc range, which is the range covered by the
401 // original _Pragma(...) sequence.
402 std::pair<SourceLocation,SourceLocation> II =
403 SM.getImmediateInstantiationRange(FileLoc);
404
405 return SM.createInstantiationLoc(SpellingLoc, II.first, II.second, TokLen);
Chris Lattner409a0362007-07-22 18:38:25 +0000406}
407
Reid Spencer5f016e22007-07-11 17:01:13 +0000408/// getSourceLocation - Return a source location identifier for the specified
409/// offset in the current file.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000410SourceLocation Lexer::getSourceLocation(const char *Loc,
411 unsigned TokLen) const {
Chris Lattner448cec42007-07-22 18:44:36 +0000412 assert(Loc >= BufferStart && Loc <= BufferEnd &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000413 "Location out of range for this buffer!");
Chris Lattner9dc1f532007-07-20 16:37:10 +0000414
415 // In the normal case, we're just lexing from a simple file buffer, return
416 // the file id from FileLoc with the offset specified.
Chris Lattner448cec42007-07-22 18:44:36 +0000417 unsigned CharNo = Loc-BufferStart;
Chris Lattner9dc1f532007-07-20 16:37:10 +0000418 if (FileLoc.isFileID())
Chris Lattnerbcc2a672009-01-19 06:46:35 +0000419 return FileLoc.getFileLocWithOffset(CharNo);
Chris Lattner9dc1f532007-07-20 16:37:10 +0000420
Chris Lattner2b2453a2009-01-17 06:22:33 +0000421 // Otherwise, this is the _Pragma lexer case, which pretends that all of the
422 // tokens are lexed from where the _Pragma was defined.
Chris Lattner168ae2d2007-10-17 20:41:00 +0000423 assert(PP && "This doesn't work on raw lexers");
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000424 return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen);
Reid Spencer5f016e22007-07-11 17:01:13 +0000425}
426
Reid Spencer5f016e22007-07-11 17:01:13 +0000427/// Diag - Forwarding function for diagnostics. This translate a source
428/// position in the current buffer into a SourceLocation object for rendering.
Chris Lattner3cbfe2c2008-11-22 00:59:29 +0000429DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
Chris Lattner3692b092008-11-18 07:59:24 +0000430 return PP->Diag(getSourceLocation(Loc), DiagID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000431}
Reid Spencer5f016e22007-07-11 17:01:13 +0000432
433//===----------------------------------------------------------------------===//
434// Trigraph and Escaped Newline Handling Code.
435//===----------------------------------------------------------------------===//
436
437/// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
438/// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
439static char GetTrigraphCharForLetter(char Letter) {
440 switch (Letter) {
441 default: return 0;
442 case '=': return '#';
443 case ')': return ']';
444 case '(': return '[';
445 case '!': return '|';
446 case '\'': return '^';
447 case '>': return '}';
448 case '/': return '\\';
449 case '<': return '{';
450 case '-': return '~';
451 }
452}
453
454/// DecodeTrigraphChar - If the specified character is a legal trigraph when
455/// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
456/// return the result character. Finally, emit a warning about trigraph use
457/// whether trigraphs are enabled or not.
458static char DecodeTrigraphChar(const char *CP, Lexer *L) {
459 char Res = GetTrigraphCharForLetter(*CP);
Chris Lattner3692b092008-11-18 07:59:24 +0000460 if (!Res || !L) return Res;
461
462 if (!L->getFeatures().Trigraphs) {
Chris Lattner74d15df2008-11-22 02:02:22 +0000463 if (!L->isLexingRawMode())
464 L->Diag(CP-2, diag::trigraph_ignored);
Chris Lattner3692b092008-11-18 07:59:24 +0000465 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000466 }
Chris Lattner3692b092008-11-18 07:59:24 +0000467
Chris Lattner74d15df2008-11-22 02:02:22 +0000468 if (!L->isLexingRawMode())
469 L->Diag(CP-2, diag::trigraph_converted) << std::string()+Res;
Reid Spencer5f016e22007-07-11 17:01:13 +0000470 return Res;
471}
472
Chris Lattner24f0e482009-04-18 22:05:41 +0000473/// getEscapedNewLineSize - Return the size of the specified escaped newline,
474/// or 0 if it is not an escaped newline. P[-1] is known to be a "\" or a
475/// trigraph equivalent on entry to this function.
476unsigned Lexer::getEscapedNewLineSize(const char *Ptr) {
477 unsigned Size = 0;
478 while (isWhitespace(Ptr[Size])) {
479 ++Size;
480
481 if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r')
482 continue;
483
484 // If this is a \r\n or \n\r, skip the other half.
485 if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') &&
486 Ptr[Size-1] != Ptr[Size])
487 ++Size;
488
489 return Size;
490 }
491
492 // Not an escaped newline, must be a \t or something else.
493 return 0;
494}
495
Chris Lattner03374952009-04-18 22:27:02 +0000496/// SkipEscapedNewLines - If P points to an escaped newline (or a series of
497/// them), skip over them and return the first non-escaped-newline found,
498/// otherwise return P.
499const char *Lexer::SkipEscapedNewLines(const char *P) {
500 while (1) {
501 const char *AfterEscape;
502 if (*P == '\\') {
503 AfterEscape = P+1;
504 } else if (*P == '?') {
505 // If not a trigraph for escape, bail out.
506 if (P[1] != '?' || P[2] != '/')
507 return P;
508 AfterEscape = P+3;
509 } else {
510 return P;
511 }
512
513 unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape);
514 if (NewLineSize == 0) return P;
515 P = AfterEscape+NewLineSize;
516 }
517}
518
Chris Lattner24f0e482009-04-18 22:05:41 +0000519
Reid Spencer5f016e22007-07-11 17:01:13 +0000520/// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
521/// get its size, and return it. This is tricky in several cases:
522/// 1. If currently at the start of a trigraph, we warn about the trigraph,
523/// then either return the trigraph (skipping 3 chars) or the '?',
524/// depending on whether trigraphs are enabled or not.
525/// 2. If this is an escaped newline (potentially with whitespace between
526/// the backslash and newline), implicitly skip the newline and return
527/// the char after it.
528/// 3. If this is a UCN, return it. FIXME: C++ UCN's?
529///
530/// This handles the slow/uncommon case of the getCharAndSize method. Here we
531/// know that we can accumulate into Size, and that we have already incremented
532/// Ptr by Size bytes.
533///
534/// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
535/// be updated to match.
536///
537char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
Chris Lattnerd2177732007-07-20 16:59:19 +0000538 Token *Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000539 // If we have a slash, look for an escaped newline.
540 if (Ptr[0] == '\\') {
541 ++Size;
542 ++Ptr;
543Slash:
544 // Common case, backslash-char where the char is not whitespace.
545 if (!isWhitespace(Ptr[0])) return '\\';
546
Chris Lattner5636a3b2009-06-23 05:15:06 +0000547 // See if we have optional whitespace characters between the slash and
548 // newline.
Chris Lattner24f0e482009-04-18 22:05:41 +0000549 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
550 // Remember that this token needs to be cleaned.
551 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +0000552
Chris Lattner24f0e482009-04-18 22:05:41 +0000553 // Warn if there was whitespace between the backslash and newline.
Chris Lattner5636a3b2009-06-23 05:15:06 +0000554 if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode())
Chris Lattner24f0e482009-04-18 22:05:41 +0000555 Diag(Ptr, diag::backslash_newline_space);
Chris Lattner0edfab62009-04-18 21:57:20 +0000556
Chris Lattner24f0e482009-04-18 22:05:41 +0000557 // Found backslash<whitespace><newline>. Parse the char after it.
558 Size += EscapedNewLineSize;
559 Ptr += EscapedNewLineSize;
560 // Use slow version to accumulate a correct size field.
561 return getCharAndSizeSlow(Ptr, Size, Tok);
562 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000563
564 // Otherwise, this is not an escaped newline, just return the slash.
565 return '\\';
566 }
567
568 // If this is a trigraph, process it.
569 if (Ptr[0] == '?' && Ptr[1] == '?') {
570 // If this is actually a legal trigraph (not something like "??x"), emit
571 // a trigraph warning. If so, and if trigraphs are enabled, return it.
572 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : 0)) {
573 // Remember that this token needs to be cleaned.
Chris Lattnerd2177732007-07-20 16:59:19 +0000574 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +0000575
576 Ptr += 3;
577 Size += 3;
578 if (C == '\\') goto Slash;
579 return C;
580 }
581 }
582
583 // If this is neither, return a single character.
584 ++Size;
585 return *Ptr;
586}
587
588
589/// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
590/// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
591/// and that we have already incremented Ptr by Size bytes.
592///
593/// NOTE: When this method is updated, getCharAndSizeSlow (above) should
594/// be updated to match.
595char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
596 const LangOptions &Features) {
597 // If we have a slash, look for an escaped newline.
598 if (Ptr[0] == '\\') {
599 ++Size;
600 ++Ptr;
601Slash:
602 // Common case, backslash-char where the char is not whitespace.
603 if (!isWhitespace(Ptr[0])) return '\\';
604
605 // See if we have optional whitespace characters followed by a newline.
Chris Lattner24f0e482009-04-18 22:05:41 +0000606 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
607 // Found backslash<whitespace><newline>. Parse the char after it.
608 Size += EscapedNewLineSize;
609 Ptr += EscapedNewLineSize;
610
611 // Use slow version to accumulate a correct size field.
612 return getCharAndSizeSlowNoWarn(Ptr, Size, Features);
613 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000614
615 // Otherwise, this is not an escaped newline, just return the slash.
616 return '\\';
617 }
618
619 // If this is a trigraph, process it.
620 if (Features.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
621 // If this is actually a legal trigraph (not something like "??x"), return
622 // it.
623 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
624 Ptr += 3;
625 Size += 3;
626 if (C == '\\') goto Slash;
627 return C;
628 }
629 }
630
631 // If this is neither, return a single character.
632 ++Size;
633 return *Ptr;
634}
635
636//===----------------------------------------------------------------------===//
637// Helper methods for lexing.
638//===----------------------------------------------------------------------===//
639
Chris Lattnerd2177732007-07-20 16:59:19 +0000640void Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000641 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
642 unsigned Size;
643 unsigned char C = *CurPtr++;
644 while (isIdentifierBody(C)) {
645 C = *CurPtr++;
646 }
647 --CurPtr; // Back up over the skipped character.
648
649 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
650 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
651 // FIXME: UCNs.
652 if (C != '\\' && C != '?' && (C != '$' || !Features.DollarIdents)) {
653FinishIdentifier:
654 const char *IdStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +0000655 FormTokenWithChars(Result, CurPtr, tok::identifier);
Reid Spencer5f016e22007-07-11 17:01:13 +0000656
657 // If we are in raw mode, return this identifier raw. There is no need to
658 // look up identifier information or attempt to macro expand it.
659 if (LexingRawMode) return;
660
661 // Fill in Result.IdentifierInfo, looking up the identifier in the
662 // identifier table.
Chris Lattnerd1186fa2009-01-21 07:45:14 +0000663 IdentifierInfo *II = PP->LookUpIdentifierInfo(Result, IdStart);
Reid Spencer5f016e22007-07-11 17:01:13 +0000664
Chris Lattner863c4862009-01-23 18:35:48 +0000665 // Change the kind of this identifier to the appropriate token kind, e.g.
666 // turning "for" into a keyword.
667 Result.setKind(II->getTokenID());
668
Reid Spencer5f016e22007-07-11 17:01:13 +0000669 // Finally, now that we know we have an identifier, pass this off to the
670 // preprocessor, which may macro expand it or something.
Chris Lattnerd1186fa2009-01-21 07:45:14 +0000671 if (II->isHandleIdentifierCase())
Chris Lattner6a170eb2009-01-21 07:43:11 +0000672 PP->HandleIdentifier(Result);
673 return;
Reid Spencer5f016e22007-07-11 17:01:13 +0000674 }
675
676 // Otherwise, $,\,? in identifier found. Enter slower path.
677
678 C = getCharAndSize(CurPtr, Size);
679 while (1) {
680 if (C == '$') {
681 // If we hit a $ and they are not supported in identifiers, we are done.
682 if (!Features.DollarIdents) goto FinishIdentifier;
683
684 // Otherwise, emit a diagnostic and continue.
Chris Lattner74d15df2008-11-22 02:02:22 +0000685 if (!isLexingRawMode())
686 Diag(CurPtr, diag::ext_dollar_in_identifier);
Reid Spencer5f016e22007-07-11 17:01:13 +0000687 CurPtr = ConsumeChar(CurPtr, Size, Result);
688 C = getCharAndSize(CurPtr, Size);
689 continue;
690 } else if (!isIdentifierBody(C)) { // FIXME: UCNs.
691 // Found end of identifier.
692 goto FinishIdentifier;
693 }
694
695 // Otherwise, this character is good, consume it.
696 CurPtr = ConsumeChar(CurPtr, Size, Result);
697
698 C = getCharAndSize(CurPtr, Size);
699 while (isIdentifierBody(C)) { // FIXME: UCNs.
700 CurPtr = ConsumeChar(CurPtr, Size, Result);
701 C = getCharAndSize(CurPtr, Size);
702 }
703 }
704}
705
706
Nate Begeman5253c7f2008-04-14 02:26:39 +0000707/// LexNumericConstant - Lex the remainder of a integer or floating point
Reid Spencer5f016e22007-07-11 17:01:13 +0000708/// constant. From[-1] is the first character lexed. Return the end of the
709/// constant.
Chris Lattnerd2177732007-07-20 16:59:19 +0000710void Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000711 unsigned Size;
712 char C = getCharAndSize(CurPtr, Size);
713 char PrevCh = 0;
714 while (isNumberBody(C)) { // FIXME: UCNs?
715 CurPtr = ConsumeChar(CurPtr, Size, Result);
716 PrevCh = C;
717 C = getCharAndSize(CurPtr, Size);
718 }
719
720 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
721 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e'))
722 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
723
724 // If we have a hex FP constant, continue.
Eli Friedmanf01fdff2009-04-28 00:51:18 +0000725 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p'))
Reid Spencer5f016e22007-07-11 17:01:13 +0000726 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
727
Reid Spencer5f016e22007-07-11 17:01:13 +0000728 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +0000729 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +0000730 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
Chris Lattner47246be2009-01-26 19:29:26 +0000731 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +0000732}
733
734/// LexStringLiteral - Lex the remainder of a string literal, after having lexed
735/// either " or L".
Chris Lattnerd88dc482008-10-12 04:05:48 +0000736void Lexer::LexStringLiteral(Token &Result, const char *CurPtr, bool Wide) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000737 const char *NulCharacter = 0; // Does this string contain the \0 character?
738
739 char C = getAndAdvanceChar(CurPtr, Result);
740 while (C != '"') {
741 // Skip escaped characters.
742 if (C == '\\') {
743 // Skip the escaped character.
744 C = getAndAdvanceChar(CurPtr, Result);
745 } else if (C == '\n' || C == '\r' || // Newline.
746 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Chris Lattner33ab3f62009-03-18 21:10:12 +0000747 if (!isLexingRawMode() && !Features.AsmPreprocessor)
Chris Lattner74d15df2008-11-22 02:02:22 +0000748 Diag(BufferPtr, diag::err_unterminated_string);
Chris Lattner9e6293d2008-10-12 04:51:35 +0000749 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Reid Spencer5f016e22007-07-11 17:01:13 +0000750 return;
751 } else if (C == 0) {
752 NulCharacter = CurPtr-1;
753 }
754 C = getAndAdvanceChar(CurPtr, Result);
755 }
756
757 // If a nul character existed in the string, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +0000758 if (NulCharacter && !isLexingRawMode())
759 Diag(NulCharacter, diag::null_in_string);
Reid Spencer5f016e22007-07-11 17:01:13 +0000760
Reid Spencer5f016e22007-07-11 17:01:13 +0000761 // Update the location of the token as well as the BufferPtr instance var.
Chris Lattner47246be2009-01-26 19:29:26 +0000762 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +0000763 FormTokenWithChars(Result, CurPtr,
764 Wide ? tok::wide_string_literal : tok::string_literal);
Chris Lattner47246be2009-01-26 19:29:26 +0000765 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +0000766}
767
768/// LexAngledStringLiteral - Lex the remainder of an angled string literal,
769/// after having lexed the '<' character. This is used for #include filenames.
Chris Lattnerd2177732007-07-20 16:59:19 +0000770void Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000771 const char *NulCharacter = 0; // Does this string contain the \0 character?
Chris Lattner9cb51ce2009-04-17 23:56:52 +0000772 const char *AfterLessPos = CurPtr;
Reid Spencer5f016e22007-07-11 17:01:13 +0000773 char C = getAndAdvanceChar(CurPtr, Result);
774 while (C != '>') {
775 // Skip escaped characters.
776 if (C == '\\') {
777 // Skip the escaped character.
778 C = getAndAdvanceChar(CurPtr, Result);
779 } else if (C == '\n' || C == '\r' || // Newline.
780 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Chris Lattner9cb51ce2009-04-17 23:56:52 +0000781 // If the filename is unterminated, then it must just be a lone <
782 // character. Return this as such.
783 FormTokenWithChars(Result, AfterLessPos, tok::less);
Reid Spencer5f016e22007-07-11 17:01:13 +0000784 return;
785 } else if (C == 0) {
786 NulCharacter = CurPtr-1;
787 }
788 C = getAndAdvanceChar(CurPtr, Result);
789 }
790
791 // If a nul character existed in the string, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +0000792 if (NulCharacter && !isLexingRawMode())
793 Diag(NulCharacter, diag::null_in_string);
Reid Spencer5f016e22007-07-11 17:01:13 +0000794
Reid Spencer5f016e22007-07-11 17:01:13 +0000795 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +0000796 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +0000797 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
Chris Lattner47246be2009-01-26 19:29:26 +0000798 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +0000799}
800
801
802/// LexCharConstant - Lex the remainder of a character constant, after having
803/// lexed either ' or L'.
Chris Lattnerd2177732007-07-20 16:59:19 +0000804void Lexer::LexCharConstant(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000805 const char *NulCharacter = 0; // Does this character contain the \0 character?
806
807 // Handle the common case of 'x' and '\y' efficiently.
808 char C = getAndAdvanceChar(CurPtr, Result);
809 if (C == '\'') {
Chris Lattner33ab3f62009-03-18 21:10:12 +0000810 if (!isLexingRawMode() && !Features.AsmPreprocessor)
Chris Lattner74d15df2008-11-22 02:02:22 +0000811 Diag(BufferPtr, diag::err_empty_character);
Chris Lattner9e6293d2008-10-12 04:51:35 +0000812 FormTokenWithChars(Result, CurPtr, tok::unknown);
Reid Spencer5f016e22007-07-11 17:01:13 +0000813 return;
814 } else if (C == '\\') {
815 // Skip the escaped character.
816 // FIXME: UCN's.
817 C = getAndAdvanceChar(CurPtr, Result);
818 }
819
820 if (C && C != '\n' && C != '\r' && CurPtr[0] == '\'') {
821 ++CurPtr;
822 } else {
823 // Fall back on generic code for embedded nulls, newlines, wide chars.
824 do {
825 // Skip escaped characters.
826 if (C == '\\') {
827 // Skip the escaped character.
828 C = getAndAdvanceChar(CurPtr, Result);
829 } else if (C == '\n' || C == '\r' || // Newline.
830 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Chris Lattner33ab3f62009-03-18 21:10:12 +0000831 if (!isLexingRawMode() && !Features.AsmPreprocessor)
Chris Lattner74d15df2008-11-22 02:02:22 +0000832 Diag(BufferPtr, diag::err_unterminated_char);
Chris Lattner9e6293d2008-10-12 04:51:35 +0000833 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Reid Spencer5f016e22007-07-11 17:01:13 +0000834 return;
835 } else if (C == 0) {
836 NulCharacter = CurPtr-1;
837 }
838 C = getAndAdvanceChar(CurPtr, Result);
839 } while (C != '\'');
840 }
841
Chris Lattner74d15df2008-11-22 02:02:22 +0000842 if (NulCharacter && !isLexingRawMode())
843 Diag(NulCharacter, diag::null_in_char);
Reid Spencer5f016e22007-07-11 17:01:13 +0000844
Reid Spencer5f016e22007-07-11 17:01:13 +0000845 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +0000846 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +0000847 FormTokenWithChars(Result, CurPtr, tok::char_constant);
Chris Lattner47246be2009-01-26 19:29:26 +0000848 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +0000849}
850
851/// SkipWhitespace - Efficiently skip over a series of whitespace characters.
852/// Update BufferPtr to point to the next non-whitespace character and return.
Chris Lattnerd88dc482008-10-12 04:05:48 +0000853///
854/// This method forms a token and returns true if KeepWhitespaceMode is enabled.
855///
856bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000857 // Whitespace - Skip it, then return the token after the whitespace.
858 unsigned char Char = *CurPtr; // Skip consequtive spaces efficiently.
859 while (1) {
860 // Skip horizontal whitespace very aggressively.
861 while (isHorizontalWhitespace(Char))
862 Char = *++CurPtr;
863
Daniel Dunbarddd3e8b2008-11-25 00:20:22 +0000864 // Otherwise if we have something other than whitespace, we're done.
Reid Spencer5f016e22007-07-11 17:01:13 +0000865 if (Char != '\n' && Char != '\r')
866 break;
867
868 if (ParsingPreprocessorDirective) {
869 // End of preprocessor directive line, let LexTokenInternal handle this.
870 BufferPtr = CurPtr;
Chris Lattnerd88dc482008-10-12 04:05:48 +0000871 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000872 }
873
874 // ok, but handle newline.
875 // The returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +0000876 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +0000877 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +0000878 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +0000879 Char = *++CurPtr;
880 }
881
882 // If this isn't immediately after a newline, there is leading space.
883 char PrevChar = CurPtr[-1];
884 if (PrevChar != '\n' && PrevChar != '\r')
Chris Lattnerd2177732007-07-20 16:59:19 +0000885 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +0000886
Chris Lattnerd88dc482008-10-12 04:05:48 +0000887 // If the client wants us to return whitespace, return it now.
888 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +0000889 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd88dc482008-10-12 04:05:48 +0000890 return true;
891 }
892
Reid Spencer5f016e22007-07-11 17:01:13 +0000893 BufferPtr = CurPtr;
Chris Lattnerd88dc482008-10-12 04:05:48 +0000894 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000895}
896
897// SkipBCPLComment - We have just read the // characters from input. Skip until
898// we find the newline character thats terminate the comment. Then update
Chris Lattner2d381892008-10-12 04:15:42 +0000899/// BufferPtr and return. If we're in KeepCommentMode, this will form the token
900/// and return true.
Chris Lattnerd2177732007-07-20 16:59:19 +0000901bool Lexer::SkipBCPLComment(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000902 // If BCPL comments aren't explicitly enabled for this language, emit an
903 // extension warning.
Chris Lattner74d15df2008-11-22 02:02:22 +0000904 if (!Features.BCPLComment && !isLexingRawMode()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000905 Diag(BufferPtr, diag::ext_bcpl_comment);
906
907 // Mark them enabled so we only emit one warning for this translation
908 // unit.
909 Features.BCPLComment = true;
910 }
911
912 // Scan over the body of the comment. The common case, when scanning, is that
913 // the comment contains normal ascii characters with nothing interesting in
914 // them. As such, optimize for this case with the inner loop.
915 char C;
916 do {
917 C = *CurPtr;
918 // FIXME: Speedup BCPL comment lexing. Just scan for a \n or \r character.
919 // If we find a \n character, scan backwards, checking to see if it's an
920 // escaped newline, like we do for block comments.
921
922 // Skip over characters in the fast loop.
923 while (C != 0 && // Potentially EOF.
924 C != '\\' && // Potentially escaped newline.
925 C != '?' && // Potentially trigraph.
926 C != '\n' && C != '\r') // Newline or DOS-style newline.
927 C = *++CurPtr;
928
929 // If this is a newline, we're done.
930 if (C == '\n' || C == '\r')
931 break; // Found the newline? Break out!
932
933 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
Chris Lattnerbc3e9842008-12-12 07:34:39 +0000934 // properly decode the character. Read it in raw mode to avoid emitting
935 // diagnostics about things like trigraphs. If we see an escaped newline,
936 // we'll handle it below.
Reid Spencer5f016e22007-07-11 17:01:13 +0000937 const char *OldPtr = CurPtr;
Chris Lattnerbc3e9842008-12-12 07:34:39 +0000938 bool OldRawMode = isLexingRawMode();
939 LexingRawMode = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000940 C = getAndAdvanceChar(CurPtr, Result);
Chris Lattnerbc3e9842008-12-12 07:34:39 +0000941 LexingRawMode = OldRawMode;
Chris Lattneread616c2009-04-05 00:26:41 +0000942
943 // If the char that we finally got was a \n, then we must have had something
944 // like \<newline><newline>. We don't want to have consumed the second
945 // newline, we want CurPtr, to end up pointing to it down below.
946 if (C == '\n' || C == '\r') {
947 --CurPtr;
948 C = 'x'; // doesn't matter what this is.
949 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000950
951 // If we read multiple characters, and one of those characters was a \r or
952 // \n, then we had an escaped newline within the comment. Emit diagnostic
953 // unless the next line is also a // comment.
954 if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') {
955 for (; OldPtr != CurPtr; ++OldPtr)
956 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
957 // Okay, we found a // comment that ends in a newline, if the next
958 // line is also a // comment, but has spaces, don't emit a diagnostic.
959 if (isspace(C)) {
960 const char *ForwardPtr = CurPtr;
961 while (isspace(*ForwardPtr)) // Skip whitespace.
962 ++ForwardPtr;
963 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
964 break;
965 }
966
Chris Lattner74d15df2008-11-22 02:02:22 +0000967 if (!isLexingRawMode())
968 Diag(OldPtr-1, diag::ext_multi_line_bcpl_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +0000969 break;
970 }
971 }
972
973 if (CurPtr == BufferEnd+1) { --CurPtr; break; }
974 } while (C != '\n' && C != '\r');
975
976 // Found but did not consume the newline.
Douglas Gregor2e222532009-07-02 17:08:52 +0000977 if (PP)
978 PP->HandleComment(SourceRange(getSourceLocation(BufferPtr),
979 getSourceLocation(CurPtr)));
980
Reid Spencer5f016e22007-07-11 17:01:13 +0000981 // If we are returning comments as tokens, return this comment as a token.
Chris Lattnerfa95a012008-10-12 03:22:02 +0000982 if (inKeepCommentMode())
Reid Spencer5f016e22007-07-11 17:01:13 +0000983 return SaveBCPLComment(Result, CurPtr);
984
985 // If we are inside a preprocessor directive and we see the end of line,
986 // return immediately, so that the lexer can return this as an EOM token.
987 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
988 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +0000989 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000990 }
991
992 // Otherwise, eat the \n character. We don't care if this is a \n\r or
Chris Lattner7a4f0042008-10-12 00:23:07 +0000993 // \r\n sequence. This is an efficiency hack (because we know the \n can't
Chris Lattnerd88dc482008-10-12 04:05:48 +0000994 // contribute to another token), it isn't needed for correctness. Note that
995 // this is ok even in KeepWhitespaceMode, because we would have returned the
996 /// comment above in that mode.
Reid Spencer5f016e22007-07-11 17:01:13 +0000997 ++CurPtr;
998
999 // The next returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00001000 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00001001 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00001002 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001003 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001004 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001005}
1006
1007/// SaveBCPLComment - If in save-comment mode, package up this BCPL comment in
1008/// an appropriate way and return it.
Chris Lattnerd2177732007-07-20 16:59:19 +00001009bool Lexer::SaveBCPLComment(Token &Result, const char *CurPtr) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001010 // If we're not in a preprocessor directive, just return the // comment
1011 // directly.
1012 FormTokenWithChars(Result, CurPtr, tok::comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001013
Chris Lattner9e6293d2008-10-12 04:51:35 +00001014 if (!ParsingPreprocessorDirective)
1015 return true;
1016
1017 // If this BCPL-style comment is in a macro definition, transmogrify it into
1018 // a C-style block comment.
1019 std::string Spelling = PP->getSpelling(Result);
1020 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not bcpl comment?");
1021 Spelling[1] = '*'; // Change prefix to "/*".
1022 Spelling += "*/"; // add suffix.
1023
1024 Result.setKind(tok::comment);
Chris Lattner47246be2009-01-26 19:29:26 +00001025 PP->CreateString(&Spelling[0], Spelling.size(), Result,
1026 Result.getLocation());
Chris Lattner2d381892008-10-12 04:15:42 +00001027 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001028}
1029
1030/// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
1031/// character (either \n or \r) is part of an escaped newline sequence. Issue a
Chris Lattner47a2b402008-12-12 07:14:34 +00001032/// diagnostic if so. We know that the newline is inside of a block comment.
Reid Spencer5f016e22007-07-11 17:01:13 +00001033static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
1034 Lexer *L) {
1035 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
1036
1037 // Back up off the newline.
1038 --CurPtr;
1039
1040 // If this is a two-character newline sequence, skip the other character.
1041 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
1042 // \n\n or \r\r -> not escaped newline.
1043 if (CurPtr[0] == CurPtr[1])
1044 return false;
1045 // \n\r or \r\n -> skip the newline.
1046 --CurPtr;
1047 }
1048
1049 // If we have horizontal whitespace, skip over it. We allow whitespace
1050 // between the slash and newline.
1051 bool HasSpace = false;
1052 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
1053 --CurPtr;
1054 HasSpace = true;
1055 }
1056
1057 // If we have a slash, we know this is an escaped newline.
1058 if (*CurPtr == '\\') {
1059 if (CurPtr[-1] != '*') return false;
1060 } else {
1061 // It isn't a slash, is it the ?? / trigraph?
1062 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
1063 CurPtr[-3] != '*')
1064 return false;
1065
1066 // This is the trigraph ending the comment. Emit a stern warning!
1067 CurPtr -= 2;
1068
1069 // If no trigraphs are enabled, warn that we ignored this trigraph and
1070 // ignore this * character.
1071 if (!L->getFeatures().Trigraphs) {
Chris Lattner74d15df2008-11-22 02:02:22 +00001072 if (!L->isLexingRawMode())
1073 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001074 return false;
1075 }
Chris Lattner74d15df2008-11-22 02:02:22 +00001076 if (!L->isLexingRawMode())
1077 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001078 }
1079
1080 // Warn about having an escaped newline between the */ characters.
Chris Lattner74d15df2008-11-22 02:02:22 +00001081 if (!L->isLexingRawMode())
1082 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
Reid Spencer5f016e22007-07-11 17:01:13 +00001083
1084 // If there was space between the backslash and newline, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001085 if (HasSpace && !L->isLexingRawMode())
1086 L->Diag(CurPtr, diag::backslash_newline_space);
Reid Spencer5f016e22007-07-11 17:01:13 +00001087
1088 return true;
1089}
1090
1091#ifdef __SSE2__
1092#include <emmintrin.h>
1093#elif __ALTIVEC__
1094#include <altivec.h>
1095#undef bool
1096#endif
1097
1098/// SkipBlockComment - We have just read the /* characters from input. Read
1099/// until we find the */ characters that terminate the comment. Note that we
1100/// don't bother decoding trigraphs or escaped newlines in block comments,
1101/// because they cannot cause the comment to end. The only thing that can
1102/// happen is the comment could end with an escaped newline between the */ end
1103/// of comment.
Chris Lattner2d381892008-10-12 04:15:42 +00001104///
1105/// If KeepCommentMode is enabled, this forms a token from the comment and
1106/// returns true.
Chris Lattnerd2177732007-07-20 16:59:19 +00001107bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001108 // Scan one character past where we should, looking for a '/' character. Once
1109 // we find it, check to see if it was preceeded by a *. This common
1110 // optimization helps people who like to put a lot of * characters in their
1111 // comments.
Chris Lattner8146b682007-07-21 23:43:37 +00001112
1113 // The first character we get with newlines and trigraphs skipped to handle
1114 // the degenerate /*/ case below correctly if the * has an escaped newline
1115 // after it.
1116 unsigned CharSize;
1117 unsigned char C = getCharAndSize(CurPtr, CharSize);
1118 CurPtr += CharSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001119 if (C == 0 && CurPtr == BufferEnd+1) {
Chris Lattner74d15df2008-11-22 02:02:22 +00001120 if (!isLexingRawMode())
Chris Lattner0af57422008-10-12 01:31:51 +00001121 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner31f0eca2008-10-12 04:19:49 +00001122 --CurPtr;
1123
1124 // KeepWhitespaceMode should return this broken comment as a token. Since
1125 // it isn't a well formed comment, just return it as an 'unknown' token.
1126 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001127 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner31f0eca2008-10-12 04:19:49 +00001128 return true;
1129 }
1130
1131 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001132 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001133 }
1134
Chris Lattner8146b682007-07-21 23:43:37 +00001135 // Check to see if the first character after the '/*' is another /. If so,
1136 // then this slash does not end the block comment, it is part of it.
1137 if (C == '/')
1138 C = *CurPtr++;
1139
Reid Spencer5f016e22007-07-11 17:01:13 +00001140 while (1) {
1141 // Skip over all non-interesting characters until we find end of buffer or a
1142 // (probably ending) '/' character.
1143 if (CurPtr + 24 < BufferEnd) {
1144 // While not aligned to a 16-byte boundary.
1145 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
1146 C = *CurPtr++;
1147
1148 if (C == '/') goto FoundSlash;
1149
1150#ifdef __SSE2__
1151 __m128i Slashes = _mm_set_epi8('/', '/', '/', '/', '/', '/', '/', '/',
1152 '/', '/', '/', '/', '/', '/', '/', '/');
1153 while (CurPtr+16 <= BufferEnd &&
1154 _mm_movemask_epi8(_mm_cmpeq_epi8(*(__m128i*)CurPtr, Slashes)) == 0)
1155 CurPtr += 16;
1156#elif __ALTIVEC__
1157 __vector unsigned char Slashes = {
1158 '/', '/', '/', '/', '/', '/', '/', '/',
1159 '/', '/', '/', '/', '/', '/', '/', '/'
1160 };
1161 while (CurPtr+16 <= BufferEnd &&
1162 !vec_any_eq(*(vector unsigned char*)CurPtr, Slashes))
1163 CurPtr += 16;
1164#else
1165 // Scan for '/' quickly. Many block comments are very large.
1166 while (CurPtr[0] != '/' &&
1167 CurPtr[1] != '/' &&
1168 CurPtr[2] != '/' &&
1169 CurPtr[3] != '/' &&
1170 CurPtr+4 < BufferEnd) {
1171 CurPtr += 4;
1172 }
1173#endif
1174
1175 // It has to be one of the bytes scanned, increment to it and read one.
1176 C = *CurPtr++;
1177 }
1178
1179 // Loop to scan the remainder.
1180 while (C != '/' && C != '\0')
1181 C = *CurPtr++;
1182
1183 FoundSlash:
1184 if (C == '/') {
1185 if (CurPtr[-2] == '*') // We found the final */. We're done!
1186 break;
1187
1188 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
1189 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
1190 // We found the final */, though it had an escaped newline between the
1191 // * and /. We're done!
1192 break;
1193 }
1194 }
1195 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
1196 // If this is a /* inside of the comment, emit a warning. Don't do this
1197 // if this is a /*/, which will end the comment. This misses cases with
1198 // embedded escaped newlines, but oh well.
Chris Lattner74d15df2008-11-22 02:02:22 +00001199 if (!isLexingRawMode())
1200 Diag(CurPtr-1, diag::warn_nested_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001201 }
1202 } else if (C == 0 && CurPtr == BufferEnd+1) {
Chris Lattner74d15df2008-11-22 02:02:22 +00001203 if (!isLexingRawMode())
1204 Diag(BufferPtr, diag::err_unterminated_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001205 // Note: the user probably forgot a */. We could continue immediately
1206 // after the /*, but this would involve lexing a lot of what really is the
1207 // comment, which surely would confuse the parser.
Chris Lattner31f0eca2008-10-12 04:19:49 +00001208 --CurPtr;
1209
1210 // KeepWhitespaceMode should return this broken comment as a token. Since
1211 // it isn't a well formed comment, just return it as an 'unknown' token.
1212 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001213 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner31f0eca2008-10-12 04:19:49 +00001214 return true;
1215 }
1216
1217 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001218 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001219 }
1220 C = *CurPtr++;
1221 }
1222
Douglas Gregor2e222532009-07-02 17:08:52 +00001223 if (PP)
1224 PP->HandleComment(SourceRange(getSourceLocation(BufferPtr),
1225 getSourceLocation(CurPtr)));
1226
Reid Spencer5f016e22007-07-11 17:01:13 +00001227 // If we are returning comments as tokens, return this comment as a token.
Chris Lattnerfa95a012008-10-12 03:22:02 +00001228 if (inKeepCommentMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001229 FormTokenWithChars(Result, CurPtr, tok::comment);
Chris Lattner2d381892008-10-12 04:15:42 +00001230 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001231 }
1232
1233 // It is common for the tokens immediately after a /**/ comment to be
1234 // whitespace. Instead of going through the big switch, handle it
Chris Lattnerd88dc482008-10-12 04:05:48 +00001235 // efficiently now. This is safe even in KeepWhitespaceMode because we would
1236 // have already returned above with the comment as a token.
Reid Spencer5f016e22007-07-11 17:01:13 +00001237 if (isHorizontalWhitespace(*CurPtr)) {
Chris Lattnerd2177732007-07-20 16:59:19 +00001238 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001239 SkipWhitespace(Result, CurPtr+1);
Chris Lattner2d381892008-10-12 04:15:42 +00001240 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001241 }
1242
1243 // Otherwise, just return so that the next character will be lexed as a token.
1244 BufferPtr = CurPtr;
Chris Lattnerd2177732007-07-20 16:59:19 +00001245 Result.setFlag(Token::LeadingSpace);
Chris Lattner2d381892008-10-12 04:15:42 +00001246 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001247}
1248
1249//===----------------------------------------------------------------------===//
1250// Primary Lexing Entry Points
1251//===----------------------------------------------------------------------===//
1252
Reid Spencer5f016e22007-07-11 17:01:13 +00001253/// ReadToEndOfLine - Read the rest of the current preprocessor line as an
1254/// uninterpreted string. This switches the lexer out of directive mode.
1255std::string Lexer::ReadToEndOfLine() {
1256 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
1257 "Must be in a preprocessing directive!");
1258 std::string Result;
Chris Lattnerd2177732007-07-20 16:59:19 +00001259 Token Tmp;
Reid Spencer5f016e22007-07-11 17:01:13 +00001260
1261 // CurPtr - Cache BufferPtr in an automatic variable.
1262 const char *CurPtr = BufferPtr;
1263 while (1) {
1264 char Char = getAndAdvanceChar(CurPtr, Tmp);
1265 switch (Char) {
1266 default:
1267 Result += Char;
1268 break;
1269 case 0: // Null.
1270 // Found end of file?
1271 if (CurPtr-1 != BufferEnd) {
1272 // Nope, normal character, continue.
1273 Result += Char;
1274 break;
1275 }
1276 // FALL THROUGH.
1277 case '\r':
1278 case '\n':
1279 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
1280 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
1281 BufferPtr = CurPtr-1;
1282
1283 // Next, lex the character, which should handle the EOM transition.
1284 Lex(Tmp);
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001285 assert(Tmp.is(tok::eom) && "Unexpected token!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001286
1287 // Finally, we're done, return the string we found.
1288 return Result;
1289 }
1290 }
1291}
1292
1293/// LexEndOfFile - CurPtr points to the end of this file. Handle this
1294/// condition, reporting diagnostics and handling other edge cases as required.
1295/// This returns true if Result contains a token, false if PP.Lex should be
1296/// called again.
Chris Lattnerd2177732007-07-20 16:59:19 +00001297bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001298 // If we hit the end of the file while parsing a preprocessor directive,
1299 // end the preprocessor directive first. The next token returned will
1300 // then be the end of file.
1301 if (ParsingPreprocessorDirective) {
1302 // Done parsing the "line".
1303 ParsingPreprocessorDirective = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001304 // Update the location of token as well as BufferPtr.
Chris Lattner9e6293d2008-10-12 04:51:35 +00001305 FormTokenWithChars(Result, CurPtr, tok::eom);
Reid Spencer5f016e22007-07-11 17:01:13 +00001306
1307 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattnerf744d132008-10-12 03:27:19 +00001308 SetCommentRetentionState(PP->getCommentRetentionState());
Reid Spencer5f016e22007-07-11 17:01:13 +00001309 return true; // Have a token.
1310 }
1311
1312 // If we are in raw mode, return this event as an EOF token. Let the caller
1313 // that put us in raw mode handle the event.
Chris Lattner74d15df2008-11-22 02:02:22 +00001314 if (isLexingRawMode()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001315 Result.startToken();
1316 BufferPtr = BufferEnd;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001317 FormTokenWithChars(Result, BufferEnd, tok::eof);
Reid Spencer5f016e22007-07-11 17:01:13 +00001318 return true;
1319 }
1320
1321 // Otherwise, issue diagnostics for unterminated #if and missing newline.
1322
1323 // If we are in a #if directive, emit an error.
1324 while (!ConditionalStack.empty()) {
Chris Lattner30c64762008-11-22 06:22:39 +00001325 PP->Diag(ConditionalStack.back().IfLoc,
1326 diag::err_pp_unterminated_conditional);
Reid Spencer5f016e22007-07-11 17:01:13 +00001327 ConditionalStack.pop_back();
1328 }
1329
Chris Lattnerb25e5d72008-04-12 05:54:25 +00001330 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
1331 // a pedwarn.
1332 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r'))
Mike Stump20d0ee52009-04-02 02:29:42 +00001333 Diag(BufferEnd, diag::ext_no_newline_eof)
1334 << CodeModificationHint::CreateInsertion(getSourceLocation(BufferEnd),
1335 "\n");
Reid Spencer5f016e22007-07-11 17:01:13 +00001336
1337 BufferPtr = CurPtr;
1338
1339 // Finally, let the preprocessor handle this.
Chris Lattner168ae2d2007-10-17 20:41:00 +00001340 return PP->HandleEndOfFile(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001341}
1342
1343/// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
1344/// the specified lexer will return a tok::l_paren token, 0 if it is something
1345/// else and 2 if there are no more tokens in the buffer controlled by the
1346/// lexer.
1347unsigned Lexer::isNextPPTokenLParen() {
1348 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
1349
1350 // Switch to 'skipping' mode. This will ensure that we can lex a token
1351 // without emitting diagnostics, disables macro expansion, and will cause EOF
1352 // to return an EOF token instead of popping the include stack.
1353 LexingRawMode = true;
1354
1355 // Save state that can be changed while lexing so that we can restore it.
1356 const char *TmpBufferPtr = BufferPtr;
Chris Lattnera864cf72009-04-24 07:15:46 +00001357 bool inPPDirectiveMode = ParsingPreprocessorDirective;
Reid Spencer5f016e22007-07-11 17:01:13 +00001358
Chris Lattnerd2177732007-07-20 16:59:19 +00001359 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001360 Tok.startToken();
1361 LexTokenInternal(Tok);
1362
1363 // Restore state that may have changed.
1364 BufferPtr = TmpBufferPtr;
Chris Lattnera864cf72009-04-24 07:15:46 +00001365 ParsingPreprocessorDirective = inPPDirectiveMode;
Reid Spencer5f016e22007-07-11 17:01:13 +00001366
1367 // Restore the lexer back to non-skipping mode.
1368 LexingRawMode = false;
1369
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001370 if (Tok.is(tok::eof))
Reid Spencer5f016e22007-07-11 17:01:13 +00001371 return 2;
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001372 return Tok.is(tok::l_paren);
Reid Spencer5f016e22007-07-11 17:01:13 +00001373}
1374
1375
1376/// LexTokenInternal - This implements a simple C family lexer. It is an
1377/// extremely performance critical piece of code. This assumes that the buffer
Chris Lattnerefb173d2009-07-07 05:05:42 +00001378/// has a null character at the end of the file. This returns a preprocessing
1379/// token, not a normal token, as such, it is an internal interface. It assumes
1380/// that the Flags of result have been cleared before calling this.
Chris Lattnerd2177732007-07-20 16:59:19 +00001381void Lexer::LexTokenInternal(Token &Result) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001382LexNextToken:
1383 // New token, can't need cleaning yet.
Chris Lattnerd2177732007-07-20 16:59:19 +00001384 Result.clearFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00001385 Result.setIdentifierInfo(0);
1386
1387 // CurPtr - Cache BufferPtr in an automatic variable.
1388 const char *CurPtr = BufferPtr;
1389
1390 // Small amounts of horizontal whitespace is very common between tokens.
1391 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
1392 ++CurPtr;
1393 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
1394 ++CurPtr;
Chris Lattnerd88dc482008-10-12 04:05:48 +00001395
1396 // If we are keeping whitespace and other tokens, just return what we just
1397 // skipped. The next lexer invocation will return the token after the
1398 // whitespace.
1399 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001400 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd88dc482008-10-12 04:05:48 +00001401 return;
1402 }
1403
Reid Spencer5f016e22007-07-11 17:01:13 +00001404 BufferPtr = CurPtr;
Chris Lattnerd2177732007-07-20 16:59:19 +00001405 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001406 }
1407
1408 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
1409
1410 // Read a character, advancing over it.
1411 char Char = getAndAdvanceChar(CurPtr, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001412 tok::TokenKind Kind;
1413
Reid Spencer5f016e22007-07-11 17:01:13 +00001414 switch (Char) {
1415 case 0: // Null.
1416 // Found end of file?
1417 if (CurPtr-1 == BufferEnd) {
1418 // Read the PP instance variable into an automatic variable, because
1419 // LexEndOfFile will often delete 'this'.
Chris Lattner168ae2d2007-10-17 20:41:00 +00001420 Preprocessor *PPCache = PP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001421 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
1422 return; // Got a token to return.
Chris Lattner168ae2d2007-10-17 20:41:00 +00001423 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
1424 return PPCache->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001425 }
1426
Chris Lattner74d15df2008-11-22 02:02:22 +00001427 if (!isLexingRawMode())
1428 Diag(CurPtr-1, diag::null_in_file);
Chris Lattnerd2177732007-07-20 16:59:19 +00001429 Result.setFlag(Token::LeadingSpace);
Chris Lattnerd88dc482008-10-12 04:05:48 +00001430 if (SkipWhitespace(Result, CurPtr))
1431 return; // KeepWhitespaceMode
1432
Reid Spencer5f016e22007-07-11 17:01:13 +00001433 goto LexNextToken; // GCC isn't tail call eliminating.
1434 case '\n':
1435 case '\r':
1436 // If we are inside a preprocessor directive and we see the end of line,
1437 // we know we are done with the directive, so return an EOM token.
1438 if (ParsingPreprocessorDirective) {
1439 // Done parsing the "line".
1440 ParsingPreprocessorDirective = false;
1441
1442 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattnerf744d132008-10-12 03:27:19 +00001443 SetCommentRetentionState(PP->getCommentRetentionState());
Reid Spencer5f016e22007-07-11 17:01:13 +00001444
1445 // Since we consumed a newline, we are back at the start of a line.
1446 IsAtStartOfLine = true;
1447
Chris Lattner9e6293d2008-10-12 04:51:35 +00001448 Kind = tok::eom;
Reid Spencer5f016e22007-07-11 17:01:13 +00001449 break;
1450 }
1451 // The returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00001452 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00001453 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00001454 Result.clearFlag(Token::LeadingSpace);
Chris Lattnerd88dc482008-10-12 04:05:48 +00001455
1456 if (SkipWhitespace(Result, CurPtr))
1457 return; // KeepWhitespaceMode
Reid Spencer5f016e22007-07-11 17:01:13 +00001458 goto LexNextToken; // GCC isn't tail call eliminating.
1459 case ' ':
1460 case '\t':
1461 case '\f':
1462 case '\v':
Chris Lattner8133cfc2007-07-22 06:29:05 +00001463 SkipHorizontalWhitespace:
Chris Lattnerd2177732007-07-20 16:59:19 +00001464 Result.setFlag(Token::LeadingSpace);
Chris Lattnerd88dc482008-10-12 04:05:48 +00001465 if (SkipWhitespace(Result, CurPtr))
1466 return; // KeepWhitespaceMode
Chris Lattner8133cfc2007-07-22 06:29:05 +00001467
1468 SkipIgnoredUnits:
1469 CurPtr = BufferPtr;
1470
1471 // If the next token is obviously a // or /* */ comment, skip it efficiently
1472 // too (without going through the big switch stmt).
Chris Lattner8402c732009-01-16 22:39:25 +00001473 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
1474 Features.BCPLComment) {
Chris Lattner8133cfc2007-07-22 06:29:05 +00001475 SkipBCPLComment(Result, CurPtr+2);
1476 goto SkipIgnoredUnits;
Chris Lattnerfa95a012008-10-12 03:22:02 +00001477 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
Chris Lattner8133cfc2007-07-22 06:29:05 +00001478 SkipBlockComment(Result, CurPtr+2);
1479 goto SkipIgnoredUnits;
1480 } else if (isHorizontalWhitespace(*CurPtr)) {
1481 goto SkipHorizontalWhitespace;
1482 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001483 goto LexNextToken; // GCC isn't tail call eliminating.
1484
Chris Lattner3a570772008-01-03 17:58:54 +00001485 // C99 6.4.4.1: Integer Constants.
1486 // C99 6.4.4.2: Floating Constants.
1487 case '0': case '1': case '2': case '3': case '4':
1488 case '5': case '6': case '7': case '8': case '9':
1489 // Notify MIOpt that we read a non-whitespace/non-comment token.
1490 MIOpt.ReadToken();
1491 return LexNumericConstant(Result, CurPtr);
1492
1493 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
Reid Spencer5f016e22007-07-11 17:01:13 +00001494 // Notify MIOpt that we read a non-whitespace/non-comment token.
1495 MIOpt.ReadToken();
1496 Char = getCharAndSize(CurPtr, SizeTmp);
1497
1498 // Wide string literal.
1499 if (Char == '"')
1500 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
1501 true);
1502
1503 // Wide character constant.
1504 if (Char == '\'')
1505 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
1506 // FALL THROUGH, treating L like the start of an identifier.
1507
1508 // C99 6.4.2: Identifiers.
1509 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
1510 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
1511 case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U':
1512 case 'V': case 'W': case 'X': case 'Y': case 'Z':
1513 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
1514 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
1515 case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u':
1516 case 'v': case 'w': case 'x': case 'y': case 'z':
1517 case '_':
1518 // Notify MIOpt that we read a non-whitespace/non-comment token.
1519 MIOpt.ReadToken();
1520 return LexIdentifier(Result, CurPtr);
Chris Lattner3a570772008-01-03 17:58:54 +00001521
1522 case '$': // $ in identifiers.
1523 if (Features.DollarIdents) {
Chris Lattner74d15df2008-11-22 02:02:22 +00001524 if (!isLexingRawMode())
1525 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
Chris Lattner3a570772008-01-03 17:58:54 +00001526 // Notify MIOpt that we read a non-whitespace/non-comment token.
1527 MIOpt.ReadToken();
1528 return LexIdentifier(Result, CurPtr);
1529 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001530
Chris Lattner9e6293d2008-10-12 04:51:35 +00001531 Kind = tok::unknown;
Chris Lattner3a570772008-01-03 17:58:54 +00001532 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001533
1534 // C99 6.4.4: Character Constants.
1535 case '\'':
1536 // Notify MIOpt that we read a non-whitespace/non-comment token.
1537 MIOpt.ReadToken();
1538 return LexCharConstant(Result, CurPtr);
1539
1540 // C99 6.4.5: String Literals.
1541 case '"':
1542 // Notify MIOpt that we read a non-whitespace/non-comment token.
1543 MIOpt.ReadToken();
1544 return LexStringLiteral(Result, CurPtr, false);
1545
1546 // C99 6.4.6: Punctuators.
1547 case '?':
Chris Lattner9e6293d2008-10-12 04:51:35 +00001548 Kind = tok::question;
Reid Spencer5f016e22007-07-11 17:01:13 +00001549 break;
1550 case '[':
Chris Lattner9e6293d2008-10-12 04:51:35 +00001551 Kind = tok::l_square;
Reid Spencer5f016e22007-07-11 17:01:13 +00001552 break;
1553 case ']':
Chris Lattner9e6293d2008-10-12 04:51:35 +00001554 Kind = tok::r_square;
Reid Spencer5f016e22007-07-11 17:01:13 +00001555 break;
1556 case '(':
Chris Lattner9e6293d2008-10-12 04:51:35 +00001557 Kind = tok::l_paren;
Reid Spencer5f016e22007-07-11 17:01:13 +00001558 break;
1559 case ')':
Chris Lattner9e6293d2008-10-12 04:51:35 +00001560 Kind = tok::r_paren;
Reid Spencer5f016e22007-07-11 17:01:13 +00001561 break;
1562 case '{':
Chris Lattner9e6293d2008-10-12 04:51:35 +00001563 Kind = tok::l_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00001564 break;
1565 case '}':
Chris Lattner9e6293d2008-10-12 04:51:35 +00001566 Kind = tok::r_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00001567 break;
1568 case '.':
1569 Char = getCharAndSize(CurPtr, SizeTmp);
1570 if (Char >= '0' && Char <= '9') {
1571 // Notify MIOpt that we read a non-whitespace/non-comment token.
1572 MIOpt.ReadToken();
1573
1574 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
1575 } else if (Features.CPlusPlus && Char == '*') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001576 Kind = tok::periodstar;
Reid Spencer5f016e22007-07-11 17:01:13 +00001577 CurPtr += SizeTmp;
1578 } else if (Char == '.' &&
1579 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001580 Kind = tok::ellipsis;
Reid Spencer5f016e22007-07-11 17:01:13 +00001581 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1582 SizeTmp2, Result);
1583 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001584 Kind = tok::period;
Reid Spencer5f016e22007-07-11 17:01:13 +00001585 }
1586 break;
1587 case '&':
1588 Char = getCharAndSize(CurPtr, SizeTmp);
1589 if (Char == '&') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001590 Kind = tok::ampamp;
Reid Spencer5f016e22007-07-11 17:01:13 +00001591 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1592 } else if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001593 Kind = tok::ampequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00001594 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1595 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001596 Kind = tok::amp;
Reid Spencer5f016e22007-07-11 17:01:13 +00001597 }
1598 break;
1599 case '*':
1600 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001601 Kind = tok::starequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00001602 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1603 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001604 Kind = tok::star;
Reid Spencer5f016e22007-07-11 17:01:13 +00001605 }
1606 break;
1607 case '+':
1608 Char = getCharAndSize(CurPtr, SizeTmp);
1609 if (Char == '+') {
Reid Spencer5f016e22007-07-11 17:01:13 +00001610 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001611 Kind = tok::plusplus;
Reid Spencer5f016e22007-07-11 17:01:13 +00001612 } else if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00001613 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001614 Kind = tok::plusequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00001615 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001616 Kind = tok::plus;
Reid Spencer5f016e22007-07-11 17:01:13 +00001617 }
1618 break;
1619 case '-':
1620 Char = getCharAndSize(CurPtr, SizeTmp);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001621 if (Char == '-') { // --
Reid Spencer5f016e22007-07-11 17:01:13 +00001622 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001623 Kind = tok::minusminus;
Reid Spencer5f016e22007-07-11 17:01:13 +00001624 } else if (Char == '>' && Features.CPlusPlus &&
Chris Lattner9e6293d2008-10-12 04:51:35 +00001625 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
Reid Spencer5f016e22007-07-11 17:01:13 +00001626 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1627 SizeTmp2, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001628 Kind = tok::arrowstar;
1629 } else if (Char == '>') { // ->
Reid Spencer5f016e22007-07-11 17:01:13 +00001630 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001631 Kind = tok::arrow;
1632 } else if (Char == '=') { // -=
Reid Spencer5f016e22007-07-11 17:01:13 +00001633 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001634 Kind = tok::minusequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00001635 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001636 Kind = tok::minus;
Reid Spencer5f016e22007-07-11 17:01:13 +00001637 }
1638 break;
1639 case '~':
Chris Lattner9e6293d2008-10-12 04:51:35 +00001640 Kind = tok::tilde;
Reid Spencer5f016e22007-07-11 17:01:13 +00001641 break;
1642 case '!':
1643 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001644 Kind = tok::exclaimequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00001645 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1646 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001647 Kind = tok::exclaim;
Reid Spencer5f016e22007-07-11 17:01:13 +00001648 }
1649 break;
1650 case '/':
1651 // 6.4.9: Comments
1652 Char = getCharAndSize(CurPtr, SizeTmp);
1653 if (Char == '/') { // BCPL comment.
Chris Lattner8402c732009-01-16 22:39:25 +00001654 // Even if BCPL comments are disabled (e.g. in C89 mode), we generally
1655 // want to lex this as a comment. There is one problem with this though,
1656 // that in one particular corner case, this can change the behavior of the
1657 // resultant program. For example, In "foo //**/ bar", C89 would lex
1658 // this as "foo / bar" and langauges with BCPL comments would lex it as
1659 // "foo". Check to see if the character after the second slash is a '*'.
1660 // If so, we will lex that as a "/" instead of the start of a comment.
1661 if (Features.BCPLComment ||
1662 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*') {
1663 if (SkipBCPLComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
1664 return; // KeepCommentMode
Chris Lattner2d381892008-10-12 04:15:42 +00001665
Chris Lattner8402c732009-01-16 22:39:25 +00001666 // It is common for the tokens immediately after a // comment to be
1667 // whitespace (indentation for the next line). Instead of going through
1668 // the big switch, handle it efficiently now.
1669 goto SkipIgnoredUnits;
1670 }
1671 }
1672
1673 if (Char == '*') { // /**/ comment.
Reid Spencer5f016e22007-07-11 17:01:13 +00001674 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattner2d381892008-10-12 04:15:42 +00001675 return; // KeepCommentMode
1676 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattner8402c732009-01-16 22:39:25 +00001677 }
1678
1679 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00001680 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001681 Kind = tok::slashequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00001682 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001683 Kind = tok::slash;
Reid Spencer5f016e22007-07-11 17:01:13 +00001684 }
1685 break;
1686 case '%':
1687 Char = getCharAndSize(CurPtr, SizeTmp);
1688 if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001689 Kind = tok::percentequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00001690 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1691 } else if (Features.Digraphs && Char == '>') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001692 Kind = tok::r_brace; // '%>' -> '}'
Reid Spencer5f016e22007-07-11 17:01:13 +00001693 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1694 } else if (Features.Digraphs && Char == ':') {
1695 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1696 Char = getCharAndSize(CurPtr, SizeTmp);
1697 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001698 Kind = tok::hashhash; // '%:%:' -> '##'
Reid Spencer5f016e22007-07-11 17:01:13 +00001699 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1700 SizeTmp2, Result);
1701 } else if (Char == '@' && Features.Microsoft) { // %:@ -> #@ -> Charize
Reid Spencer5f016e22007-07-11 17:01:13 +00001702 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner74d15df2008-11-22 02:02:22 +00001703 if (!isLexingRawMode())
1704 Diag(BufferPtr, diag::charize_microsoft_ext);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001705 Kind = tok::hashat;
Chris Lattnere91e9322009-03-18 20:58:27 +00001706 } else { // '%:' -> '#'
Reid Spencer5f016e22007-07-11 17:01:13 +00001707 // We parsed a # character. If this occurs at the start of the line,
1708 // it's actually the start of a preprocessing directive. Callback to
1709 // the preprocessor to handle it.
1710 // FIXME: -fpreprocessed mode??
Chris Lattner766703b2009-05-13 06:10:29 +00001711 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer) {
Chris Lattnere91e9322009-03-18 20:58:27 +00001712 FormTokenWithChars(Result, CurPtr, tok::hash);
Chris Lattner168ae2d2007-10-17 20:41:00 +00001713 PP->HandleDirective(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001714
1715 // As an optimization, if the preprocessor didn't switch lexers, tail
1716 // recurse.
Chris Lattner168ae2d2007-10-17 20:41:00 +00001717 if (PP->isCurrentLexer(this)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001718 // Start a new token. If this is a #include or something, the PP may
1719 // want us starting at the beginning of the line again. If so, set
1720 // the StartOfLine flag.
1721 if (IsAtStartOfLine) {
Chris Lattnerd2177732007-07-20 16:59:19 +00001722 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00001723 IsAtStartOfLine = false;
1724 }
1725 goto LexNextToken; // GCC isn't tail call eliminating.
1726 }
1727
Chris Lattner168ae2d2007-10-17 20:41:00 +00001728 return PP->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001729 }
Chris Lattnere91e9322009-03-18 20:58:27 +00001730
1731 Kind = tok::hash;
Reid Spencer5f016e22007-07-11 17:01:13 +00001732 }
1733 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001734 Kind = tok::percent;
Reid Spencer5f016e22007-07-11 17:01:13 +00001735 }
1736 break;
1737 case '<':
1738 Char = getCharAndSize(CurPtr, SizeTmp);
1739 if (ParsingFilename) {
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001740 return LexAngledStringLiteral(Result, CurPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +00001741 } else if (Char == '<' &&
1742 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001743 Kind = tok::lesslessequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00001744 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1745 SizeTmp2, Result);
1746 } else if (Char == '<') {
Reid Spencer5f016e22007-07-11 17:01:13 +00001747 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001748 Kind = tok::lessless;
Reid Spencer5f016e22007-07-11 17:01:13 +00001749 } else if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00001750 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001751 Kind = tok::lessequal;
1752 } else if (Features.Digraphs && Char == ':') { // '<:' -> '['
Reid Spencer5f016e22007-07-11 17:01:13 +00001753 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001754 Kind = tok::l_square;
1755 } else if (Features.Digraphs && Char == '%') { // '<%' -> '{'
Reid Spencer5f016e22007-07-11 17:01:13 +00001756 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001757 Kind = tok::l_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00001758 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001759 Kind = tok::less;
Reid Spencer5f016e22007-07-11 17:01:13 +00001760 }
1761 break;
1762 case '>':
1763 Char = getCharAndSize(CurPtr, SizeTmp);
1764 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00001765 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001766 Kind = tok::greaterequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00001767 } else if (Char == '>' &&
1768 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00001769 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1770 SizeTmp2, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001771 Kind = tok::greatergreaterequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00001772 } else if (Char == '>') {
Reid Spencer5f016e22007-07-11 17:01:13 +00001773 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001774 Kind = tok::greatergreater;
Reid Spencer5f016e22007-07-11 17:01:13 +00001775 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001776 Kind = tok::greater;
Reid Spencer5f016e22007-07-11 17:01:13 +00001777 }
1778 break;
1779 case '^':
1780 Char = getCharAndSize(CurPtr, SizeTmp);
1781 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00001782 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001783 Kind = tok::caretequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00001784 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001785 Kind = tok::caret;
Reid Spencer5f016e22007-07-11 17:01:13 +00001786 }
1787 break;
1788 case '|':
1789 Char = getCharAndSize(CurPtr, SizeTmp);
1790 if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001791 Kind = tok::pipeequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00001792 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1793 } else if (Char == '|') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001794 Kind = tok::pipepipe;
Reid Spencer5f016e22007-07-11 17:01:13 +00001795 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1796 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001797 Kind = tok::pipe;
Reid Spencer5f016e22007-07-11 17:01:13 +00001798 }
1799 break;
1800 case ':':
1801 Char = getCharAndSize(CurPtr, SizeTmp);
1802 if (Features.Digraphs && Char == '>') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001803 Kind = tok::r_square; // ':>' -> ']'
Reid Spencer5f016e22007-07-11 17:01:13 +00001804 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1805 } else if (Features.CPlusPlus && Char == ':') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001806 Kind = tok::coloncolon;
Reid Spencer5f016e22007-07-11 17:01:13 +00001807 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1808 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001809 Kind = tok::colon;
Reid Spencer5f016e22007-07-11 17:01:13 +00001810 }
1811 break;
1812 case ';':
Chris Lattner9e6293d2008-10-12 04:51:35 +00001813 Kind = tok::semi;
Reid Spencer5f016e22007-07-11 17:01:13 +00001814 break;
1815 case '=':
1816 Char = getCharAndSize(CurPtr, SizeTmp);
1817 if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001818 Kind = tok::equalequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00001819 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1820 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001821 Kind = tok::equal;
Reid Spencer5f016e22007-07-11 17:01:13 +00001822 }
1823 break;
1824 case ',':
Chris Lattner9e6293d2008-10-12 04:51:35 +00001825 Kind = tok::comma;
Reid Spencer5f016e22007-07-11 17:01:13 +00001826 break;
1827 case '#':
1828 Char = getCharAndSize(CurPtr, SizeTmp);
1829 if (Char == '#') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001830 Kind = tok::hashhash;
Reid Spencer5f016e22007-07-11 17:01:13 +00001831 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1832 } else if (Char == '@' && Features.Microsoft) { // #@ -> Charize
Chris Lattner9e6293d2008-10-12 04:51:35 +00001833 Kind = tok::hashat;
Chris Lattner74d15df2008-11-22 02:02:22 +00001834 if (!isLexingRawMode())
1835 Diag(BufferPtr, diag::charize_microsoft_ext);
Reid Spencer5f016e22007-07-11 17:01:13 +00001836 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1837 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +00001838 // We parsed a # character. If this occurs at the start of the line,
1839 // it's actually the start of a preprocessing directive. Callback to
1840 // the preprocessor to handle it.
1841 // FIXME: -fpreprocessed mode??
Chris Lattner766703b2009-05-13 06:10:29 +00001842 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer) {
Chris Lattnere91e9322009-03-18 20:58:27 +00001843 FormTokenWithChars(Result, CurPtr, tok::hash);
Chris Lattner168ae2d2007-10-17 20:41:00 +00001844 PP->HandleDirective(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001845
1846 // As an optimization, if the preprocessor didn't switch lexers, tail
1847 // recurse.
Chris Lattner168ae2d2007-10-17 20:41:00 +00001848 if (PP->isCurrentLexer(this)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001849 // Start a new token. If this is a #include or something, the PP may
1850 // want us starting at the beginning of the line again. If so, set
1851 // the StartOfLine flag.
1852 if (IsAtStartOfLine) {
Chris Lattnerd2177732007-07-20 16:59:19 +00001853 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00001854 IsAtStartOfLine = false;
1855 }
1856 goto LexNextToken; // GCC isn't tail call eliminating.
1857 }
Chris Lattner168ae2d2007-10-17 20:41:00 +00001858 return PP->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001859 }
Chris Lattnere91e9322009-03-18 20:58:27 +00001860
1861 Kind = tok::hash;
Reid Spencer5f016e22007-07-11 17:01:13 +00001862 }
1863 break;
1864
Chris Lattner3a570772008-01-03 17:58:54 +00001865 case '@':
1866 // Objective C support.
1867 if (CurPtr[-1] == '@' && Features.ObjC1)
Chris Lattner9e6293d2008-10-12 04:51:35 +00001868 Kind = tok::at;
Chris Lattner3a570772008-01-03 17:58:54 +00001869 else
Chris Lattner9e6293d2008-10-12 04:51:35 +00001870 Kind = tok::unknown;
Chris Lattner3a570772008-01-03 17:58:54 +00001871 break;
1872
Reid Spencer5f016e22007-07-11 17:01:13 +00001873 case '\\':
1874 // FIXME: UCN's.
1875 // FALL THROUGH.
1876 default:
Chris Lattner9e6293d2008-10-12 04:51:35 +00001877 Kind = tok::unknown;
Reid Spencer5f016e22007-07-11 17:01:13 +00001878 break;
1879 }
1880
1881 // Notify MIOpt that we read a non-whitespace/non-comment token.
1882 MIOpt.ReadToken();
1883
1884 // Update the location of token as well as BufferPtr.
Chris Lattner9e6293d2008-10-12 04:51:35 +00001885 FormTokenWithChars(Result, CurPtr, Kind);
Reid Spencer5f016e22007-07-11 17:01:13 +00001886}