blob: c45a36a9a59fbca0b6c209d421cc435774fdc31c [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- Lexer.cpp - C Language Family Lexer ------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chris Lattnerd2177732007-07-20 16:59:19 +000010// This file implements the Lexer and Token interfaces.
Reid Spencer5f016e22007-07-11 17:01:13 +000011//
12//===----------------------------------------------------------------------===//
13//
14// TODO: GCC Diagnostics emitted by the lexer:
15// PEDWARN: (form feed|vertical tab) in preprocessing directive
16//
17// Universal characters, unicode, char mapping:
18// WARNING: `%.*s' is not in NFKC
19// WARNING: `%.*s' is not in NFC
20//
21// Other:
22// TODO: Options to support:
23// -fexec-charset,-fwide-exec-charset
24//
25//===----------------------------------------------------------------------===//
26
27#include "clang/Lex/Lexer.h"
28#include "clang/Lex/Preprocessor.h"
29#include "clang/Basic/Diagnostic.h"
Chris Lattner9dc1f532007-07-20 16:37:10 +000030#include "clang/Basic/SourceManager.h"
Chris Lattner409a0362007-07-22 18:38:25 +000031#include "llvm/Support/Compiler.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000032#include "llvm/Support/MemoryBuffer.h"
33#include <cctype>
34using namespace clang;
35
36static void InitCharacterInfo();
37
Chris Lattner25bdb512007-07-20 16:52:03 +000038Lexer::Lexer(SourceLocation fileloc, Preprocessor &pp,
39 const char *BufStart, const char *BufEnd)
40 : FileLoc(fileloc), PP(pp), Features(PP.getLangOptions()) {
41
42 SourceManager &SourceMgr = PP.getSourceManager();
Chris Lattner448cec42007-07-22 18:44:36 +000043 unsigned InputFileID = SourceMgr.getPhysicalLoc(FileLoc).getFileID();
44 const llvm::MemoryBuffer *InputFile = SourceMgr.getBuffer(InputFileID);
Chris Lattner25bdb512007-07-20 16:52:03 +000045
Reid Spencer5f016e22007-07-11 17:01:13 +000046 Is_PragmaLexer = false;
47 IsMainFile = false;
48 InitCharacterInfo();
Chris Lattner448cec42007-07-22 18:44:36 +000049
50 // BufferStart must always be InputFile->getBufferStart().
51 BufferStart = InputFile->getBufferStart();
52
53 // BufferPtr and BufferEnd can start out somewhere inside the current buffer.
54 // If unspecified, they starts at the start/end of the buffer.
55 BufferPtr = BufStart ? BufStart : BufferStart;
Chris Lattner25bdb512007-07-20 16:52:03 +000056 BufferEnd = BufEnd ? BufEnd : InputFile->getBufferEnd();
57
Reid Spencer5f016e22007-07-11 17:01:13 +000058 assert(BufferEnd[0] == 0 &&
59 "We assume that the input buffer has a null character at the end"
60 " to simplify lexing!");
Chris Lattner25bdb512007-07-20 16:52:03 +000061
Reid Spencer5f016e22007-07-11 17:01:13 +000062 // Start of the file is a start of line.
63 IsAtStartOfLine = true;
64
65 // We are not after parsing a #.
66 ParsingPreprocessorDirective = false;
67
68 // We are not after parsing #include.
69 ParsingFilename = false;
70
71 // We are not in raw mode. Raw mode disables diagnostics and interpretation
72 // of tokens (e.g. identifiers, thus disabling macro expansion). It is used
73 // to quickly lex the tokens of the buffer, e.g. when handling a "#if 0" block
74 // or otherwise skipping over tokens.
75 LexingRawMode = false;
76
77 // Default to keeping comments if requested.
78 KeepCommentMode = PP.getCommentRetentionState();
79}
80
81/// Stringify - Convert the specified string into a C string, with surrounding
82/// ""'s, and with escaped \ and " characters.
83std::string Lexer::Stringify(const std::string &Str, bool Charify) {
84 std::string Result = Str;
85 char Quote = Charify ? '\'' : '"';
86 for (unsigned i = 0, e = Result.size(); i != e; ++i) {
87 if (Result[i] == '\\' || Result[i] == Quote) {
88 Result.insert(Result.begin()+i, '\\');
89 ++i; ++e;
90 }
91 }
92 return Result;
93}
94
Chris Lattnerd8e30832007-07-24 06:57:14 +000095/// Stringify - Convert the specified string into a C string by escaping '\'
96/// and " characters. This does not add surrounding ""'s to the string.
97void Lexer::Stringify(llvm::SmallVectorImpl<char> &Str) {
98 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
99 if (Str[i] == '\\' || Str[i] == '"') {
100 Str.insert(Str.begin()+i, '\\');
101 ++i; ++e;
102 }
103 }
104}
105
Reid Spencer5f016e22007-07-11 17:01:13 +0000106
107//===----------------------------------------------------------------------===//
108// Character information.
109//===----------------------------------------------------------------------===//
110
111static unsigned char CharInfo[256];
112
113enum {
114 CHAR_HORZ_WS = 0x01, // ' ', '\t', '\f', '\v'. Note, no '\0'
115 CHAR_VERT_WS = 0x02, // '\r', '\n'
116 CHAR_LETTER = 0x04, // a-z,A-Z
117 CHAR_NUMBER = 0x08, // 0-9
118 CHAR_UNDER = 0x10, // _
119 CHAR_PERIOD = 0x20 // .
120};
121
122static void InitCharacterInfo() {
123 static bool isInited = false;
124 if (isInited) return;
125 isInited = true;
126
127 // Intiialize the CharInfo table.
128 // TODO: statically initialize this.
129 CharInfo[(int)' '] = CharInfo[(int)'\t'] =
130 CharInfo[(int)'\f'] = CharInfo[(int)'\v'] = CHAR_HORZ_WS;
131 CharInfo[(int)'\n'] = CharInfo[(int)'\r'] = CHAR_VERT_WS;
132
133 CharInfo[(int)'_'] = CHAR_UNDER;
134 CharInfo[(int)'.'] = CHAR_PERIOD;
135 for (unsigned i = 'a'; i <= 'z'; ++i)
136 CharInfo[i] = CharInfo[i+'A'-'a'] = CHAR_LETTER;
137 for (unsigned i = '0'; i <= '9'; ++i)
138 CharInfo[i] = CHAR_NUMBER;
139}
140
141/// isIdentifierBody - Return true if this is the body character of an
142/// identifier, which is [a-zA-Z0-9_].
143static inline bool isIdentifierBody(unsigned char c) {
144 return CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER);
145}
146
147/// isHorizontalWhitespace - Return true if this character is horizontal
148/// whitespace: ' ', '\t', '\f', '\v'. Note that this returns false for '\0'.
149static inline bool isHorizontalWhitespace(unsigned char c) {
150 return CharInfo[c] & CHAR_HORZ_WS;
151}
152
153/// isWhitespace - Return true if this character is horizontal or vertical
154/// whitespace: ' ', '\t', '\f', '\v', '\n', '\r'. Note that this returns false
155/// for '\0'.
156static inline bool isWhitespace(unsigned char c) {
157 return CharInfo[c] & (CHAR_HORZ_WS|CHAR_VERT_WS);
158}
159
160/// isNumberBody - Return true if this is the body character of an
161/// preprocessing number, which is [a-zA-Z0-9_.].
162static inline bool isNumberBody(unsigned char c) {
163 return CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER|CHAR_PERIOD);
164}
165
166
167//===----------------------------------------------------------------------===//
168// Diagnostics forwarding code.
169//===----------------------------------------------------------------------===//
170
Chris Lattner409a0362007-07-22 18:38:25 +0000171/// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
172/// lexer buffer was all instantiated at a single point, perform the mapping.
173/// This is currently only used for _Pragma implementation, so it is the slow
174/// path of the hot getSourceLocation method. Do not allow it to be inlined.
175static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
176 SourceLocation FileLoc,
177 unsigned CharNo) DISABLE_INLINE;
178static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
179 SourceLocation FileLoc,
180 unsigned CharNo) {
181 // Otherwise, we're lexing "mapped tokens". This is used for things like
182 // _Pragma handling. Combine the instantiation location of FileLoc with the
183 // physical location.
184 SourceManager &SourceMgr = PP.getSourceManager();
185
186 // Create a new SLoc which is expanded from logical(FileLoc) but whose
187 // characters come from phys(FileLoc)+Offset.
188 SourceLocation VirtLoc = SourceMgr.getLogicalLoc(FileLoc);
189 SourceLocation PhysLoc = SourceMgr.getPhysicalLoc(FileLoc);
190 PhysLoc = SourceLocation::getFileLoc(PhysLoc.getFileID(), CharNo);
191 return SourceMgr.getInstantiationLoc(PhysLoc, VirtLoc);
192}
193
Reid Spencer5f016e22007-07-11 17:01:13 +0000194/// getSourceLocation - Return a source location identifier for the specified
195/// offset in the current file.
196SourceLocation Lexer::getSourceLocation(const char *Loc) const {
Chris Lattner448cec42007-07-22 18:44:36 +0000197 assert(Loc >= BufferStart && Loc <= BufferEnd &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000198 "Location out of range for this buffer!");
Chris Lattner9dc1f532007-07-20 16:37:10 +0000199
200 // In the normal case, we're just lexing from a simple file buffer, return
201 // the file id from FileLoc with the offset specified.
Chris Lattner448cec42007-07-22 18:44:36 +0000202 unsigned CharNo = Loc-BufferStart;
Chris Lattner9dc1f532007-07-20 16:37:10 +0000203 if (FileLoc.isFileID())
204 return SourceLocation::getFileLoc(FileLoc.getFileID(), CharNo);
205
Chris Lattner409a0362007-07-22 18:38:25 +0000206 return GetMappedTokenLoc(PP, FileLoc, CharNo);
Reid Spencer5f016e22007-07-11 17:01:13 +0000207}
208
Reid Spencer5f016e22007-07-11 17:01:13 +0000209/// Diag - Forwarding function for diagnostics. This translate a source
210/// position in the current buffer into a SourceLocation object for rendering.
211void Lexer::Diag(const char *Loc, unsigned DiagID,
212 const std::string &Msg) const {
213 if (LexingRawMode && Diagnostic::isNoteWarningOrExtension(DiagID))
214 return;
215 PP.Diag(getSourceLocation(Loc), DiagID, Msg);
216}
217void Lexer::Diag(SourceLocation Loc, unsigned DiagID,
218 const std::string &Msg) const {
219 if (LexingRawMode && Diagnostic::isNoteWarningOrExtension(DiagID))
220 return;
221 PP.Diag(Loc, DiagID, Msg);
222}
223
224
225//===----------------------------------------------------------------------===//
226// Trigraph and Escaped Newline Handling Code.
227//===----------------------------------------------------------------------===//
228
229/// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
230/// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
231static char GetTrigraphCharForLetter(char Letter) {
232 switch (Letter) {
233 default: return 0;
234 case '=': return '#';
235 case ')': return ']';
236 case '(': return '[';
237 case '!': return '|';
238 case '\'': return '^';
239 case '>': return '}';
240 case '/': return '\\';
241 case '<': return '{';
242 case '-': return '~';
243 }
244}
245
246/// DecodeTrigraphChar - If the specified character is a legal trigraph when
247/// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
248/// return the result character. Finally, emit a warning about trigraph use
249/// whether trigraphs are enabled or not.
250static char DecodeTrigraphChar(const char *CP, Lexer *L) {
251 char Res = GetTrigraphCharForLetter(*CP);
252 if (Res && L) {
253 if (!L->getFeatures().Trigraphs) {
254 L->Diag(CP-2, diag::trigraph_ignored);
255 return 0;
256 } else {
257 L->Diag(CP-2, diag::trigraph_converted, std::string()+Res);
258 }
259 }
260 return Res;
261}
262
263/// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
264/// get its size, and return it. This is tricky in several cases:
265/// 1. If currently at the start of a trigraph, we warn about the trigraph,
266/// then either return the trigraph (skipping 3 chars) or the '?',
267/// depending on whether trigraphs are enabled or not.
268/// 2. If this is an escaped newline (potentially with whitespace between
269/// the backslash and newline), implicitly skip the newline and return
270/// the char after it.
271/// 3. If this is a UCN, return it. FIXME: C++ UCN's?
272///
273/// This handles the slow/uncommon case of the getCharAndSize method. Here we
274/// know that we can accumulate into Size, and that we have already incremented
275/// Ptr by Size bytes.
276///
277/// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
278/// be updated to match.
279///
280char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
Chris Lattnerd2177732007-07-20 16:59:19 +0000281 Token *Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000282 // If we have a slash, look for an escaped newline.
283 if (Ptr[0] == '\\') {
284 ++Size;
285 ++Ptr;
286Slash:
287 // Common case, backslash-char where the char is not whitespace.
288 if (!isWhitespace(Ptr[0])) return '\\';
289
290 // See if we have optional whitespace characters followed by a newline.
291 {
292 unsigned SizeTmp = 0;
293 do {
294 ++SizeTmp;
295 if (Ptr[SizeTmp-1] == '\n' || Ptr[SizeTmp-1] == '\r') {
296 // Remember that this token needs to be cleaned.
Chris Lattnerd2177732007-07-20 16:59:19 +0000297 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +0000298
299 // Warn if there was whitespace between the backslash and newline.
300 if (SizeTmp != 1 && Tok)
301 Diag(Ptr, diag::backslash_newline_space);
302
303 // If this is a \r\n or \n\r, skip the newlines.
304 if ((Ptr[SizeTmp] == '\r' || Ptr[SizeTmp] == '\n') &&
305 Ptr[SizeTmp-1] != Ptr[SizeTmp])
306 ++SizeTmp;
307
308 // Found backslash<whitespace><newline>. Parse the char after it.
309 Size += SizeTmp;
310 Ptr += SizeTmp;
311 // Use slow version to accumulate a correct size field.
312 return getCharAndSizeSlow(Ptr, Size, Tok);
313 }
314 } while (isWhitespace(Ptr[SizeTmp]));
315 }
316
317 // Otherwise, this is not an escaped newline, just return the slash.
318 return '\\';
319 }
320
321 // If this is a trigraph, process it.
322 if (Ptr[0] == '?' && Ptr[1] == '?') {
323 // If this is actually a legal trigraph (not something like "??x"), emit
324 // a trigraph warning. If so, and if trigraphs are enabled, return it.
325 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : 0)) {
326 // Remember that this token needs to be cleaned.
Chris Lattnerd2177732007-07-20 16:59:19 +0000327 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +0000328
329 Ptr += 3;
330 Size += 3;
331 if (C == '\\') goto Slash;
332 return C;
333 }
334 }
335
336 // If this is neither, return a single character.
337 ++Size;
338 return *Ptr;
339}
340
341
342/// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
343/// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
344/// and that we have already incremented Ptr by Size bytes.
345///
346/// NOTE: When this method is updated, getCharAndSizeSlow (above) should
347/// be updated to match.
348char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
349 const LangOptions &Features) {
350 // If we have a slash, look for an escaped newline.
351 if (Ptr[0] == '\\') {
352 ++Size;
353 ++Ptr;
354Slash:
355 // Common case, backslash-char where the char is not whitespace.
356 if (!isWhitespace(Ptr[0])) return '\\';
357
358 // See if we have optional whitespace characters followed by a newline.
359 {
360 unsigned SizeTmp = 0;
361 do {
362 ++SizeTmp;
363 if (Ptr[SizeTmp-1] == '\n' || Ptr[SizeTmp-1] == '\r') {
364
365 // If this is a \r\n or \n\r, skip the newlines.
366 if ((Ptr[SizeTmp] == '\r' || Ptr[SizeTmp] == '\n') &&
367 Ptr[SizeTmp-1] != Ptr[SizeTmp])
368 ++SizeTmp;
369
370 // Found backslash<whitespace><newline>. Parse the char after it.
371 Size += SizeTmp;
372 Ptr += SizeTmp;
373
374 // Use slow version to accumulate a correct size field.
375 return getCharAndSizeSlowNoWarn(Ptr, Size, Features);
376 }
377 } while (isWhitespace(Ptr[SizeTmp]));
378 }
379
380 // Otherwise, this is not an escaped newline, just return the slash.
381 return '\\';
382 }
383
384 // If this is a trigraph, process it.
385 if (Features.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
386 // If this is actually a legal trigraph (not something like "??x"), return
387 // it.
388 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
389 Ptr += 3;
390 Size += 3;
391 if (C == '\\') goto Slash;
392 return C;
393 }
394 }
395
396 // If this is neither, return a single character.
397 ++Size;
398 return *Ptr;
399}
400
401//===----------------------------------------------------------------------===//
402// Helper methods for lexing.
403//===----------------------------------------------------------------------===//
404
Chris Lattnerd2177732007-07-20 16:59:19 +0000405void Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000406 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
407 unsigned Size;
408 unsigned char C = *CurPtr++;
409 while (isIdentifierBody(C)) {
410 C = *CurPtr++;
411 }
412 --CurPtr; // Back up over the skipped character.
413
414 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
415 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
416 // FIXME: UCNs.
417 if (C != '\\' && C != '?' && (C != '$' || !Features.DollarIdents)) {
418FinishIdentifier:
419 const char *IdStart = BufferPtr;
420 FormTokenWithChars(Result, CurPtr);
421 Result.setKind(tok::identifier);
422
423 // If we are in raw mode, return this identifier raw. There is no need to
424 // look up identifier information or attempt to macro expand it.
425 if (LexingRawMode) return;
426
427 // Fill in Result.IdentifierInfo, looking up the identifier in the
428 // identifier table.
429 PP.LookUpIdentifierInfo(Result, IdStart);
430
431 // Finally, now that we know we have an identifier, pass this off to the
432 // preprocessor, which may macro expand it or something.
433 return PP.HandleIdentifier(Result);
434 }
435
436 // Otherwise, $,\,? in identifier found. Enter slower path.
437
438 C = getCharAndSize(CurPtr, Size);
439 while (1) {
440 if (C == '$') {
441 // If we hit a $ and they are not supported in identifiers, we are done.
442 if (!Features.DollarIdents) goto FinishIdentifier;
443
444 // Otherwise, emit a diagnostic and continue.
445 Diag(CurPtr, diag::ext_dollar_in_identifier);
446 CurPtr = ConsumeChar(CurPtr, Size, Result);
447 C = getCharAndSize(CurPtr, Size);
448 continue;
449 } else if (!isIdentifierBody(C)) { // FIXME: UCNs.
450 // Found end of identifier.
451 goto FinishIdentifier;
452 }
453
454 // Otherwise, this character is good, consume it.
455 CurPtr = ConsumeChar(CurPtr, Size, Result);
456
457 C = getCharAndSize(CurPtr, Size);
458 while (isIdentifierBody(C)) { // FIXME: UCNs.
459 CurPtr = ConsumeChar(CurPtr, Size, Result);
460 C = getCharAndSize(CurPtr, Size);
461 }
462 }
463}
464
465
466/// LexNumericConstant - Lex the remainer of a integer or floating point
467/// constant. From[-1] is the first character lexed. Return the end of the
468/// constant.
Chris Lattnerd2177732007-07-20 16:59:19 +0000469void Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000470 unsigned Size;
471 char C = getCharAndSize(CurPtr, Size);
472 char PrevCh = 0;
473 while (isNumberBody(C)) { // FIXME: UCNs?
474 CurPtr = ConsumeChar(CurPtr, Size, Result);
475 PrevCh = C;
476 C = getCharAndSize(CurPtr, Size);
477 }
478
479 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
480 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e'))
481 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
482
483 // If we have a hex FP constant, continue.
484 if (Features.HexFloats &&
485 (C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p'))
486 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
487
488 Result.setKind(tok::numeric_constant);
489
490 // Update the location of token as well as BufferPtr.
491 FormTokenWithChars(Result, CurPtr);
492}
493
494/// LexStringLiteral - Lex the remainder of a string literal, after having lexed
495/// either " or L".
Chris Lattnerd2177732007-07-20 16:59:19 +0000496void Lexer::LexStringLiteral(Token &Result, const char *CurPtr, bool Wide){
Reid Spencer5f016e22007-07-11 17:01:13 +0000497 const char *NulCharacter = 0; // Does this string contain the \0 character?
498
499 char C = getAndAdvanceChar(CurPtr, Result);
500 while (C != '"') {
501 // Skip escaped characters.
502 if (C == '\\') {
503 // Skip the escaped character.
504 C = getAndAdvanceChar(CurPtr, Result);
505 } else if (C == '\n' || C == '\r' || // Newline.
506 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
507 if (!LexingRawMode) Diag(BufferPtr, diag::err_unterminated_string);
508 Result.setKind(tok::unknown);
509 FormTokenWithChars(Result, CurPtr-1);
510 return;
511 } else if (C == 0) {
512 NulCharacter = CurPtr-1;
513 }
514 C = getAndAdvanceChar(CurPtr, Result);
515 }
516
517 // If a nul character existed in the string, warn about it.
518 if (NulCharacter) Diag(NulCharacter, diag::null_in_string);
519
520 Result.setKind(Wide ? tok::wide_string_literal : tok::string_literal);
521
522 // Update the location of the token as well as the BufferPtr instance var.
523 FormTokenWithChars(Result, CurPtr);
524}
525
526/// LexAngledStringLiteral - Lex the remainder of an angled string literal,
527/// after having lexed the '<' character. This is used for #include filenames.
Chris Lattnerd2177732007-07-20 16:59:19 +0000528void Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000529 const char *NulCharacter = 0; // Does this string contain the \0 character?
530
531 char C = getAndAdvanceChar(CurPtr, Result);
532 while (C != '>') {
533 // Skip escaped characters.
534 if (C == '\\') {
535 // Skip the escaped character.
536 C = getAndAdvanceChar(CurPtr, Result);
537 } else if (C == '\n' || C == '\r' || // Newline.
538 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
539 if (!LexingRawMode) Diag(BufferPtr, diag::err_unterminated_string);
540 Result.setKind(tok::unknown);
541 FormTokenWithChars(Result, CurPtr-1);
542 return;
543 } else if (C == 0) {
544 NulCharacter = CurPtr-1;
545 }
546 C = getAndAdvanceChar(CurPtr, Result);
547 }
548
549 // If a nul character existed in the string, warn about it.
550 if (NulCharacter) Diag(NulCharacter, diag::null_in_string);
551
552 Result.setKind(tok::angle_string_literal);
553
554 // Update the location of token as well as BufferPtr.
555 FormTokenWithChars(Result, CurPtr);
556}
557
558
559/// LexCharConstant - Lex the remainder of a character constant, after having
560/// lexed either ' or L'.
Chris Lattnerd2177732007-07-20 16:59:19 +0000561void Lexer::LexCharConstant(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000562 const char *NulCharacter = 0; // Does this character contain the \0 character?
563
564 // Handle the common case of 'x' and '\y' efficiently.
565 char C = getAndAdvanceChar(CurPtr, Result);
566 if (C == '\'') {
567 if (!LexingRawMode) Diag(BufferPtr, diag::err_empty_character);
568 Result.setKind(tok::unknown);
569 FormTokenWithChars(Result, CurPtr);
570 return;
571 } else if (C == '\\') {
572 // Skip the escaped character.
573 // FIXME: UCN's.
574 C = getAndAdvanceChar(CurPtr, Result);
575 }
576
577 if (C && C != '\n' && C != '\r' && CurPtr[0] == '\'') {
578 ++CurPtr;
579 } else {
580 // Fall back on generic code for embedded nulls, newlines, wide chars.
581 do {
582 // Skip escaped characters.
583 if (C == '\\') {
584 // Skip the escaped character.
585 C = getAndAdvanceChar(CurPtr, Result);
586 } else if (C == '\n' || C == '\r' || // Newline.
587 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
588 if (!LexingRawMode) Diag(BufferPtr, diag::err_unterminated_char);
589 Result.setKind(tok::unknown);
590 FormTokenWithChars(Result, CurPtr-1);
591 return;
592 } else if (C == 0) {
593 NulCharacter = CurPtr-1;
594 }
595 C = getAndAdvanceChar(CurPtr, Result);
596 } while (C != '\'');
597 }
598
599 if (NulCharacter) Diag(NulCharacter, diag::null_in_char);
600
601 Result.setKind(tok::char_constant);
602
603 // Update the location of token as well as BufferPtr.
604 FormTokenWithChars(Result, CurPtr);
605}
606
607/// SkipWhitespace - Efficiently skip over a series of whitespace characters.
608/// Update BufferPtr to point to the next non-whitespace character and return.
Chris Lattnerd2177732007-07-20 16:59:19 +0000609void Lexer::SkipWhitespace(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000610 // Whitespace - Skip it, then return the token after the whitespace.
611 unsigned char Char = *CurPtr; // Skip consequtive spaces efficiently.
612 while (1) {
613 // Skip horizontal whitespace very aggressively.
614 while (isHorizontalWhitespace(Char))
615 Char = *++CurPtr;
616
617 // Otherwise if we something other than whitespace, we're done.
618 if (Char != '\n' && Char != '\r')
619 break;
620
621 if (ParsingPreprocessorDirective) {
622 // End of preprocessor directive line, let LexTokenInternal handle this.
623 BufferPtr = CurPtr;
624 return;
625 }
626
627 // ok, but handle newline.
628 // The returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +0000629 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +0000630 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +0000631 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +0000632 Char = *++CurPtr;
633 }
634
635 // If this isn't immediately after a newline, there is leading space.
636 char PrevChar = CurPtr[-1];
637 if (PrevChar != '\n' && PrevChar != '\r')
Chris Lattnerd2177732007-07-20 16:59:19 +0000638 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +0000639
Reid Spencer5f016e22007-07-11 17:01:13 +0000640 BufferPtr = CurPtr;
641}
642
643// SkipBCPLComment - We have just read the // characters from input. Skip until
644// we find the newline character thats terminate the comment. Then update
645/// BufferPtr and return.
Chris Lattnerd2177732007-07-20 16:59:19 +0000646bool Lexer::SkipBCPLComment(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000647 // If BCPL comments aren't explicitly enabled for this language, emit an
648 // extension warning.
649 if (!Features.BCPLComment) {
650 Diag(BufferPtr, diag::ext_bcpl_comment);
651
652 // Mark them enabled so we only emit one warning for this translation
653 // unit.
654 Features.BCPLComment = true;
655 }
656
657 // Scan over the body of the comment. The common case, when scanning, is that
658 // the comment contains normal ascii characters with nothing interesting in
659 // them. As such, optimize for this case with the inner loop.
660 char C;
661 do {
662 C = *CurPtr;
663 // FIXME: Speedup BCPL comment lexing. Just scan for a \n or \r character.
664 // If we find a \n character, scan backwards, checking to see if it's an
665 // escaped newline, like we do for block comments.
666
667 // Skip over characters in the fast loop.
668 while (C != 0 && // Potentially EOF.
669 C != '\\' && // Potentially escaped newline.
670 C != '?' && // Potentially trigraph.
671 C != '\n' && C != '\r') // Newline or DOS-style newline.
672 C = *++CurPtr;
673
674 // If this is a newline, we're done.
675 if (C == '\n' || C == '\r')
676 break; // Found the newline? Break out!
677
678 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
679 // properly decode the character.
680 const char *OldPtr = CurPtr;
681 C = getAndAdvanceChar(CurPtr, Result);
682
683 // If we read multiple characters, and one of those characters was a \r or
684 // \n, then we had an escaped newline within the comment. Emit diagnostic
685 // unless the next line is also a // comment.
686 if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') {
687 for (; OldPtr != CurPtr; ++OldPtr)
688 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
689 // Okay, we found a // comment that ends in a newline, if the next
690 // line is also a // comment, but has spaces, don't emit a diagnostic.
691 if (isspace(C)) {
692 const char *ForwardPtr = CurPtr;
693 while (isspace(*ForwardPtr)) // Skip whitespace.
694 ++ForwardPtr;
695 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
696 break;
697 }
698
699 Diag(OldPtr-1, diag::ext_multi_line_bcpl_comment);
700 break;
701 }
702 }
703
704 if (CurPtr == BufferEnd+1) { --CurPtr; break; }
705 } while (C != '\n' && C != '\r');
706
707 // Found but did not consume the newline.
708
709 // If we are returning comments as tokens, return this comment as a token.
710 if (KeepCommentMode)
711 return SaveBCPLComment(Result, CurPtr);
712
713 // If we are inside a preprocessor directive and we see the end of line,
714 // return immediately, so that the lexer can return this as an EOM token.
715 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
716 BufferPtr = CurPtr;
717 return true;
718 }
719
720 // Otherwise, eat the \n character. We don't care if this is a \n\r or
721 // \r\n sequence.
722 ++CurPtr;
723
724 // The next returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +0000725 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +0000726 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +0000727 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +0000728 BufferPtr = CurPtr;
729 return true;
730}
731
732/// SaveBCPLComment - If in save-comment mode, package up this BCPL comment in
733/// an appropriate way and return it.
Chris Lattnerd2177732007-07-20 16:59:19 +0000734bool Lexer::SaveBCPLComment(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000735 Result.setKind(tok::comment);
736 FormTokenWithChars(Result, CurPtr);
737
738 // If this BCPL-style comment is in a macro definition, transmogrify it into
739 // a C-style block comment.
740 if (ParsingPreprocessorDirective) {
741 std::string Spelling = PP.getSpelling(Result);
742 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not bcpl comment?");
743 Spelling[1] = '*'; // Change prefix to "/*".
744 Spelling += "*/"; // add suffix.
745
746 Result.setLocation(PP.CreateString(&Spelling[0], Spelling.size(),
747 Result.getLocation()));
748 Result.setLength(Spelling.size());
749 }
750 return false;
751}
752
753/// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
754/// character (either \n or \r) is part of an escaped newline sequence. Issue a
755/// diagnostic if so. We know that the is inside of a block comment.
756static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
757 Lexer *L) {
758 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
759
760 // Back up off the newline.
761 --CurPtr;
762
763 // If this is a two-character newline sequence, skip the other character.
764 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
765 // \n\n or \r\r -> not escaped newline.
766 if (CurPtr[0] == CurPtr[1])
767 return false;
768 // \n\r or \r\n -> skip the newline.
769 --CurPtr;
770 }
771
772 // If we have horizontal whitespace, skip over it. We allow whitespace
773 // between the slash and newline.
774 bool HasSpace = false;
775 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
776 --CurPtr;
777 HasSpace = true;
778 }
779
780 // If we have a slash, we know this is an escaped newline.
781 if (*CurPtr == '\\') {
782 if (CurPtr[-1] != '*') return false;
783 } else {
784 // It isn't a slash, is it the ?? / trigraph?
785 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
786 CurPtr[-3] != '*')
787 return false;
788
789 // This is the trigraph ending the comment. Emit a stern warning!
790 CurPtr -= 2;
791
792 // If no trigraphs are enabled, warn that we ignored this trigraph and
793 // ignore this * character.
794 if (!L->getFeatures().Trigraphs) {
795 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
796 return false;
797 }
798 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
799 }
800
801 // Warn about having an escaped newline between the */ characters.
802 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
803
804 // If there was space between the backslash and newline, warn about it.
805 if (HasSpace) L->Diag(CurPtr, diag::backslash_newline_space);
806
807 return true;
808}
809
810#ifdef __SSE2__
811#include <emmintrin.h>
812#elif __ALTIVEC__
813#include <altivec.h>
814#undef bool
815#endif
816
817/// SkipBlockComment - We have just read the /* characters from input. Read
818/// until we find the */ characters that terminate the comment. Note that we
819/// don't bother decoding trigraphs or escaped newlines in block comments,
820/// because they cannot cause the comment to end. The only thing that can
821/// happen is the comment could end with an escaped newline between the */ end
822/// of comment.
Chris Lattnerd2177732007-07-20 16:59:19 +0000823bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000824 // Scan one character past where we should, looking for a '/' character. Once
825 // we find it, check to see if it was preceeded by a *. This common
826 // optimization helps people who like to put a lot of * characters in their
827 // comments.
Chris Lattner8146b682007-07-21 23:43:37 +0000828
829 // The first character we get with newlines and trigraphs skipped to handle
830 // the degenerate /*/ case below correctly if the * has an escaped newline
831 // after it.
832 unsigned CharSize;
833 unsigned char C = getCharAndSize(CurPtr, CharSize);
834 CurPtr += CharSize;
Reid Spencer5f016e22007-07-11 17:01:13 +0000835 if (C == 0 && CurPtr == BufferEnd+1) {
836 Diag(BufferPtr, diag::err_unterminated_block_comment);
837 BufferPtr = CurPtr-1;
838 return true;
839 }
840
Chris Lattner8146b682007-07-21 23:43:37 +0000841 // Check to see if the first character after the '/*' is another /. If so,
842 // then this slash does not end the block comment, it is part of it.
843 if (C == '/')
844 C = *CurPtr++;
845
Reid Spencer5f016e22007-07-11 17:01:13 +0000846 while (1) {
847 // Skip over all non-interesting characters until we find end of buffer or a
848 // (probably ending) '/' character.
849 if (CurPtr + 24 < BufferEnd) {
850 // While not aligned to a 16-byte boundary.
851 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
852 C = *CurPtr++;
853
854 if (C == '/') goto FoundSlash;
855
856#ifdef __SSE2__
857 __m128i Slashes = _mm_set_epi8('/', '/', '/', '/', '/', '/', '/', '/',
858 '/', '/', '/', '/', '/', '/', '/', '/');
859 while (CurPtr+16 <= BufferEnd &&
860 _mm_movemask_epi8(_mm_cmpeq_epi8(*(__m128i*)CurPtr, Slashes)) == 0)
861 CurPtr += 16;
862#elif __ALTIVEC__
863 __vector unsigned char Slashes = {
864 '/', '/', '/', '/', '/', '/', '/', '/',
865 '/', '/', '/', '/', '/', '/', '/', '/'
866 };
867 while (CurPtr+16 <= BufferEnd &&
868 !vec_any_eq(*(vector unsigned char*)CurPtr, Slashes))
869 CurPtr += 16;
870#else
871 // Scan for '/' quickly. Many block comments are very large.
872 while (CurPtr[0] != '/' &&
873 CurPtr[1] != '/' &&
874 CurPtr[2] != '/' &&
875 CurPtr[3] != '/' &&
876 CurPtr+4 < BufferEnd) {
877 CurPtr += 4;
878 }
879#endif
880
881 // It has to be one of the bytes scanned, increment to it and read one.
882 C = *CurPtr++;
883 }
884
885 // Loop to scan the remainder.
886 while (C != '/' && C != '\0')
887 C = *CurPtr++;
888
889 FoundSlash:
890 if (C == '/') {
891 if (CurPtr[-2] == '*') // We found the final */. We're done!
892 break;
893
894 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
895 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
896 // We found the final */, though it had an escaped newline between the
897 // * and /. We're done!
898 break;
899 }
900 }
901 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
902 // If this is a /* inside of the comment, emit a warning. Don't do this
903 // if this is a /*/, which will end the comment. This misses cases with
904 // embedded escaped newlines, but oh well.
905 Diag(CurPtr-1, diag::nested_block_comment);
906 }
907 } else if (C == 0 && CurPtr == BufferEnd+1) {
908 Diag(BufferPtr, diag::err_unterminated_block_comment);
909 // Note: the user probably forgot a */. We could continue immediately
910 // after the /*, but this would involve lexing a lot of what really is the
911 // comment, which surely would confuse the parser.
912 BufferPtr = CurPtr-1;
913 return true;
914 }
915 C = *CurPtr++;
916 }
917
918 // If we are returning comments as tokens, return this comment as a token.
919 if (KeepCommentMode) {
920 Result.setKind(tok::comment);
921 FormTokenWithChars(Result, CurPtr);
922 return false;
923 }
924
925 // It is common for the tokens immediately after a /**/ comment to be
926 // whitespace. Instead of going through the big switch, handle it
927 // efficiently now.
928 if (isHorizontalWhitespace(*CurPtr)) {
Chris Lattnerd2177732007-07-20 16:59:19 +0000929 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +0000930 SkipWhitespace(Result, CurPtr+1);
931 return true;
932 }
933
934 // Otherwise, just return so that the next character will be lexed as a token.
935 BufferPtr = CurPtr;
Chris Lattnerd2177732007-07-20 16:59:19 +0000936 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +0000937 return true;
938}
939
940//===----------------------------------------------------------------------===//
941// Primary Lexing Entry Points
942//===----------------------------------------------------------------------===//
943
944/// LexIncludeFilename - After the preprocessor has parsed a #include, lex and
945/// (potentially) macro expand the filename.
Chris Lattnerd2177732007-07-20 16:59:19 +0000946void Lexer::LexIncludeFilename(Token &FilenameTok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000947 assert(ParsingPreprocessorDirective &&
948 ParsingFilename == false &&
949 "Must be in a preprocessing directive!");
950
951 // We are now parsing a filename!
952 ParsingFilename = true;
953
954 // Lex the filename.
955 Lex(FilenameTok);
956
957 // We should have obtained the filename now.
958 ParsingFilename = false;
959
960 // No filename?
961 if (FilenameTok.getKind() == tok::eom)
962 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
963}
964
965/// ReadToEndOfLine - Read the rest of the current preprocessor line as an
966/// uninterpreted string. This switches the lexer out of directive mode.
967std::string Lexer::ReadToEndOfLine() {
968 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
969 "Must be in a preprocessing directive!");
970 std::string Result;
Chris Lattnerd2177732007-07-20 16:59:19 +0000971 Token Tmp;
Reid Spencer5f016e22007-07-11 17:01:13 +0000972
973 // CurPtr - Cache BufferPtr in an automatic variable.
974 const char *CurPtr = BufferPtr;
975 while (1) {
976 char Char = getAndAdvanceChar(CurPtr, Tmp);
977 switch (Char) {
978 default:
979 Result += Char;
980 break;
981 case 0: // Null.
982 // Found end of file?
983 if (CurPtr-1 != BufferEnd) {
984 // Nope, normal character, continue.
985 Result += Char;
986 break;
987 }
988 // FALL THROUGH.
989 case '\r':
990 case '\n':
991 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
992 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
993 BufferPtr = CurPtr-1;
994
995 // Next, lex the character, which should handle the EOM transition.
996 Lex(Tmp);
997 assert(Tmp.getKind() == tok::eom && "Unexpected token!");
998
999 // Finally, we're done, return the string we found.
1000 return Result;
1001 }
1002 }
1003}
1004
1005/// LexEndOfFile - CurPtr points to the end of this file. Handle this
1006/// condition, reporting diagnostics and handling other edge cases as required.
1007/// This returns true if Result contains a token, false if PP.Lex should be
1008/// called again.
Chris Lattnerd2177732007-07-20 16:59:19 +00001009bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001010 // If we hit the end of the file while parsing a preprocessor directive,
1011 // end the preprocessor directive first. The next token returned will
1012 // then be the end of file.
1013 if (ParsingPreprocessorDirective) {
1014 // Done parsing the "line".
1015 ParsingPreprocessorDirective = false;
1016 Result.setKind(tok::eom);
1017 // Update the location of token as well as BufferPtr.
1018 FormTokenWithChars(Result, CurPtr);
1019
1020 // Restore comment saving mode, in case it was disabled for directive.
1021 KeepCommentMode = PP.getCommentRetentionState();
1022 return true; // Have a token.
1023 }
1024
1025 // If we are in raw mode, return this event as an EOF token. Let the caller
1026 // that put us in raw mode handle the event.
1027 if (LexingRawMode) {
1028 Result.startToken();
1029 BufferPtr = BufferEnd;
1030 FormTokenWithChars(Result, BufferEnd);
1031 Result.setKind(tok::eof);
1032 return true;
1033 }
1034
1035 // Otherwise, issue diagnostics for unterminated #if and missing newline.
1036
1037 // If we are in a #if directive, emit an error.
1038 while (!ConditionalStack.empty()) {
1039 Diag(ConditionalStack.back().IfLoc, diag::err_pp_unterminated_conditional);
1040 ConditionalStack.pop_back();
1041 }
1042
1043 // If the file was empty or didn't end in a newline, issue a pedwarn.
1044 if (CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
1045 Diag(BufferEnd, diag::ext_no_newline_eof);
1046
1047 BufferPtr = CurPtr;
1048
1049 // Finally, let the preprocessor handle this.
1050 return PP.HandleEndOfFile(Result);
1051}
1052
1053/// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
1054/// the specified lexer will return a tok::l_paren token, 0 if it is something
1055/// else and 2 if there are no more tokens in the buffer controlled by the
1056/// lexer.
1057unsigned Lexer::isNextPPTokenLParen() {
1058 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
1059
1060 // Switch to 'skipping' mode. This will ensure that we can lex a token
1061 // without emitting diagnostics, disables macro expansion, and will cause EOF
1062 // to return an EOF token instead of popping the include stack.
1063 LexingRawMode = true;
1064
1065 // Save state that can be changed while lexing so that we can restore it.
1066 const char *TmpBufferPtr = BufferPtr;
1067
Chris Lattnerd2177732007-07-20 16:59:19 +00001068 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001069 Tok.startToken();
1070 LexTokenInternal(Tok);
1071
1072 // Restore state that may have changed.
1073 BufferPtr = TmpBufferPtr;
1074
1075 // Restore the lexer back to non-skipping mode.
1076 LexingRawMode = false;
1077
1078 if (Tok.getKind() == tok::eof)
1079 return 2;
1080 return Tok.getKind() == tok::l_paren;
1081}
1082
1083
1084/// LexTokenInternal - This implements a simple C family lexer. It is an
1085/// extremely performance critical piece of code. This assumes that the buffer
1086/// has a null character at the end of the file. Return true if an error
1087/// occurred and compilation should terminate, false if normal. This returns a
1088/// preprocessing token, not a normal token, as such, it is an internal
1089/// interface. It assumes that the Flags of result have been cleared before
1090/// calling this.
Chris Lattnerd2177732007-07-20 16:59:19 +00001091void Lexer::LexTokenInternal(Token &Result) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001092LexNextToken:
1093 // New token, can't need cleaning yet.
Chris Lattnerd2177732007-07-20 16:59:19 +00001094 Result.clearFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00001095 Result.setIdentifierInfo(0);
1096
1097 // CurPtr - Cache BufferPtr in an automatic variable.
1098 const char *CurPtr = BufferPtr;
1099
1100 // Small amounts of horizontal whitespace is very common between tokens.
1101 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
1102 ++CurPtr;
1103 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
1104 ++CurPtr;
1105 BufferPtr = CurPtr;
Chris Lattnerd2177732007-07-20 16:59:19 +00001106 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001107 }
1108
1109 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
1110
1111 // Read a character, advancing over it.
1112 char Char = getAndAdvanceChar(CurPtr, Result);
1113 switch (Char) {
1114 case 0: // Null.
1115 // Found end of file?
1116 if (CurPtr-1 == BufferEnd) {
1117 // Read the PP instance variable into an automatic variable, because
1118 // LexEndOfFile will often delete 'this'.
1119 Preprocessor &PPCache = PP;
1120 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
1121 return; // Got a token to return.
1122 return PPCache.Lex(Result);
1123 }
1124
1125 Diag(CurPtr-1, diag::null_in_file);
Chris Lattnerd2177732007-07-20 16:59:19 +00001126 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001127 SkipWhitespace(Result, CurPtr);
1128 goto LexNextToken; // GCC isn't tail call eliminating.
1129 case '\n':
1130 case '\r':
1131 // If we are inside a preprocessor directive and we see the end of line,
1132 // we know we are done with the directive, so return an EOM token.
1133 if (ParsingPreprocessorDirective) {
1134 // Done parsing the "line".
1135 ParsingPreprocessorDirective = false;
1136
1137 // Restore comment saving mode, in case it was disabled for directive.
1138 KeepCommentMode = PP.getCommentRetentionState();
1139
1140 // Since we consumed a newline, we are back at the start of a line.
1141 IsAtStartOfLine = true;
1142
1143 Result.setKind(tok::eom);
1144 break;
1145 }
1146 // The returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00001147 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00001148 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00001149 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001150 SkipWhitespace(Result, CurPtr);
1151 goto LexNextToken; // GCC isn't tail call eliminating.
1152 case ' ':
1153 case '\t':
1154 case '\f':
1155 case '\v':
Chris Lattner8133cfc2007-07-22 06:29:05 +00001156 SkipHorizontalWhitespace:
Chris Lattnerd2177732007-07-20 16:59:19 +00001157 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001158 SkipWhitespace(Result, CurPtr);
Chris Lattner8133cfc2007-07-22 06:29:05 +00001159
1160 SkipIgnoredUnits:
1161 CurPtr = BufferPtr;
1162
1163 // If the next token is obviously a // or /* */ comment, skip it efficiently
1164 // too (without going through the big switch stmt).
1165 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !KeepCommentMode) {
1166 SkipBCPLComment(Result, CurPtr+2);
1167 goto SkipIgnoredUnits;
1168 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !KeepCommentMode) {
1169 SkipBlockComment(Result, CurPtr+2);
1170 goto SkipIgnoredUnits;
1171 } else if (isHorizontalWhitespace(*CurPtr)) {
1172 goto SkipHorizontalWhitespace;
1173 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001174 goto LexNextToken; // GCC isn't tail call eliminating.
1175
1176 case 'L':
1177 // Notify MIOpt that we read a non-whitespace/non-comment token.
1178 MIOpt.ReadToken();
1179 Char = getCharAndSize(CurPtr, SizeTmp);
1180
1181 // Wide string literal.
1182 if (Char == '"')
1183 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
1184 true);
1185
1186 // Wide character constant.
1187 if (Char == '\'')
1188 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
1189 // FALL THROUGH, treating L like the start of an identifier.
1190
1191 // C99 6.4.2: Identifiers.
1192 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
1193 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
1194 case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U':
1195 case 'V': case 'W': case 'X': case 'Y': case 'Z':
1196 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
1197 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
1198 case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u':
1199 case 'v': case 'w': case 'x': case 'y': case 'z':
1200 case '_':
1201 // Notify MIOpt that we read a non-whitespace/non-comment token.
1202 MIOpt.ReadToken();
1203 return LexIdentifier(Result, CurPtr);
1204
1205 // C99 6.4.4.1: Integer Constants.
1206 // C99 6.4.4.2: Floating Constants.
1207 case '0': case '1': case '2': case '3': case '4':
1208 case '5': case '6': case '7': case '8': case '9':
1209 // Notify MIOpt that we read a non-whitespace/non-comment token.
1210 MIOpt.ReadToken();
1211 return LexNumericConstant(Result, CurPtr);
1212
1213 // C99 6.4.4: Character Constants.
1214 case '\'':
1215 // Notify MIOpt that we read a non-whitespace/non-comment token.
1216 MIOpt.ReadToken();
1217 return LexCharConstant(Result, CurPtr);
1218
1219 // C99 6.4.5: String Literals.
1220 case '"':
1221 // Notify MIOpt that we read a non-whitespace/non-comment token.
1222 MIOpt.ReadToken();
1223 return LexStringLiteral(Result, CurPtr, false);
1224
1225 // C99 6.4.6: Punctuators.
1226 case '?':
1227 Result.setKind(tok::question);
1228 break;
1229 case '[':
1230 Result.setKind(tok::l_square);
1231 break;
1232 case ']':
1233 Result.setKind(tok::r_square);
1234 break;
1235 case '(':
1236 Result.setKind(tok::l_paren);
1237 break;
1238 case ')':
1239 Result.setKind(tok::r_paren);
1240 break;
1241 case '{':
1242 Result.setKind(tok::l_brace);
1243 break;
1244 case '}':
1245 Result.setKind(tok::r_brace);
1246 break;
1247 case '.':
1248 Char = getCharAndSize(CurPtr, SizeTmp);
1249 if (Char >= '0' && Char <= '9') {
1250 // Notify MIOpt that we read a non-whitespace/non-comment token.
1251 MIOpt.ReadToken();
1252
1253 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
1254 } else if (Features.CPlusPlus && Char == '*') {
1255 Result.setKind(tok::periodstar);
1256 CurPtr += SizeTmp;
1257 } else if (Char == '.' &&
1258 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
1259 Result.setKind(tok::ellipsis);
1260 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1261 SizeTmp2, Result);
1262 } else {
1263 Result.setKind(tok::period);
1264 }
1265 break;
1266 case '&':
1267 Char = getCharAndSize(CurPtr, SizeTmp);
1268 if (Char == '&') {
1269 Result.setKind(tok::ampamp);
1270 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1271 } else if (Char == '=') {
1272 Result.setKind(tok::ampequal);
1273 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1274 } else {
1275 Result.setKind(tok::amp);
1276 }
1277 break;
1278 case '*':
1279 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
1280 Result.setKind(tok::starequal);
1281 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1282 } else {
1283 Result.setKind(tok::star);
1284 }
1285 break;
1286 case '+':
1287 Char = getCharAndSize(CurPtr, SizeTmp);
1288 if (Char == '+') {
1289 Result.setKind(tok::plusplus);
1290 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1291 } else if (Char == '=') {
1292 Result.setKind(tok::plusequal);
1293 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1294 } else {
1295 Result.setKind(tok::plus);
1296 }
1297 break;
1298 case '-':
1299 Char = getCharAndSize(CurPtr, SizeTmp);
1300 if (Char == '-') {
1301 Result.setKind(tok::minusminus);
1302 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1303 } else if (Char == '>' && Features.CPlusPlus &&
1304 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') {
1305 Result.setKind(tok::arrowstar); // C++ ->*
1306 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1307 SizeTmp2, Result);
1308 } else if (Char == '>') {
1309 Result.setKind(tok::arrow);
1310 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1311 } else if (Char == '=') {
1312 Result.setKind(tok::minusequal);
1313 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1314 } else {
1315 Result.setKind(tok::minus);
1316 }
1317 break;
1318 case '~':
1319 Result.setKind(tok::tilde);
1320 break;
1321 case '!':
1322 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
1323 Result.setKind(tok::exclaimequal);
1324 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1325 } else {
1326 Result.setKind(tok::exclaim);
1327 }
1328 break;
1329 case '/':
1330 // 6.4.9: Comments
1331 Char = getCharAndSize(CurPtr, SizeTmp);
1332 if (Char == '/') { // BCPL comment.
Chris Lattner8133cfc2007-07-22 06:29:05 +00001333 if (SkipBCPLComment(Result, ConsumeChar(CurPtr, SizeTmp, Result))) {
1334 // It is common for the tokens immediately after a // comment to be
Chris Lattner409a0362007-07-22 18:38:25 +00001335 // whitespace (indentation for the next line). Instead of going through
1336 // the big switch, handle it efficiently now.
Chris Lattner8133cfc2007-07-22 06:29:05 +00001337 goto SkipIgnoredUnits;
1338 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001339 return; // KeepCommentMode
1340 } else if (Char == '*') { // /**/ comment.
1341 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
1342 goto LexNextToken; // GCC isn't tail call eliminating.
1343 return; // KeepCommentMode
1344 } else if (Char == '=') {
1345 Result.setKind(tok::slashequal);
1346 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1347 } else {
1348 Result.setKind(tok::slash);
1349 }
1350 break;
1351 case '%':
1352 Char = getCharAndSize(CurPtr, SizeTmp);
1353 if (Char == '=') {
1354 Result.setKind(tok::percentequal);
1355 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1356 } else if (Features.Digraphs && Char == '>') {
1357 Result.setKind(tok::r_brace); // '%>' -> '}'
1358 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1359 } else if (Features.Digraphs && Char == ':') {
1360 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1361 Char = getCharAndSize(CurPtr, SizeTmp);
1362 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
1363 Result.setKind(tok::hashhash); // '%:%:' -> '##'
1364 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1365 SizeTmp2, Result);
1366 } else if (Char == '@' && Features.Microsoft) { // %:@ -> #@ -> Charize
1367 Result.setKind(tok::hashat);
1368 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1369 Diag(BufferPtr, diag::charize_microsoft_ext);
1370 } else {
1371 Result.setKind(tok::hash); // '%:' -> '#'
1372
1373 // We parsed a # character. If this occurs at the start of the line,
1374 // it's actually the start of a preprocessing directive. Callback to
1375 // the preprocessor to handle it.
1376 // FIXME: -fpreprocessed mode??
1377 if (Result.isAtStartOfLine() && !LexingRawMode) {
1378 BufferPtr = CurPtr;
1379 PP.HandleDirective(Result);
1380
1381 // As an optimization, if the preprocessor didn't switch lexers, tail
1382 // recurse.
1383 if (PP.isCurrentLexer(this)) {
1384 // Start a new token. If this is a #include or something, the PP may
1385 // want us starting at the beginning of the line again. If so, set
1386 // the StartOfLine flag.
1387 if (IsAtStartOfLine) {
Chris Lattnerd2177732007-07-20 16:59:19 +00001388 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00001389 IsAtStartOfLine = false;
1390 }
1391 goto LexNextToken; // GCC isn't tail call eliminating.
1392 }
1393
1394 return PP.Lex(Result);
1395 }
1396 }
1397 } else {
1398 Result.setKind(tok::percent);
1399 }
1400 break;
1401 case '<':
1402 Char = getCharAndSize(CurPtr, SizeTmp);
1403 if (ParsingFilename) {
1404 return LexAngledStringLiteral(Result, CurPtr+SizeTmp);
1405 } else if (Char == '<' &&
1406 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '=') {
1407 Result.setKind(tok::lesslessequal);
1408 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1409 SizeTmp2, Result);
1410 } else if (Char == '<') {
1411 Result.setKind(tok::lessless);
1412 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1413 } else if (Char == '=') {
1414 Result.setKind(tok::lessequal);
1415 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1416 } else if (Features.Digraphs && Char == ':') {
1417 Result.setKind(tok::l_square); // '<:' -> '['
1418 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1419 } else if (Features.Digraphs && Char == '>') {
1420 Result.setKind(tok::l_brace); // '<%' -> '{'
1421 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1422 } else {
1423 Result.setKind(tok::less);
1424 }
1425 break;
1426 case '>':
1427 Char = getCharAndSize(CurPtr, SizeTmp);
1428 if (Char == '=') {
1429 Result.setKind(tok::greaterequal);
1430 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1431 } else if (Char == '>' &&
1432 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '=') {
1433 Result.setKind(tok::greatergreaterequal);
1434 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1435 SizeTmp2, Result);
1436 } else if (Char == '>') {
1437 Result.setKind(tok::greatergreater);
1438 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1439 } else {
1440 Result.setKind(tok::greater);
1441 }
1442 break;
1443 case '^':
1444 Char = getCharAndSize(CurPtr, SizeTmp);
1445 if (Char == '=') {
1446 Result.setKind(tok::caretequal);
1447 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1448 } else {
1449 Result.setKind(tok::caret);
1450 }
1451 break;
1452 case '|':
1453 Char = getCharAndSize(CurPtr, SizeTmp);
1454 if (Char == '=') {
1455 Result.setKind(tok::pipeequal);
1456 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1457 } else if (Char == '|') {
1458 Result.setKind(tok::pipepipe);
1459 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1460 } else {
1461 Result.setKind(tok::pipe);
1462 }
1463 break;
1464 case ':':
1465 Char = getCharAndSize(CurPtr, SizeTmp);
1466 if (Features.Digraphs && Char == '>') {
1467 Result.setKind(tok::r_square); // ':>' -> ']'
1468 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1469 } else if (Features.CPlusPlus && Char == ':') {
1470 Result.setKind(tok::coloncolon);
1471 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1472 } else {
1473 Result.setKind(tok::colon);
1474 }
1475 break;
1476 case ';':
1477 Result.setKind(tok::semi);
1478 break;
1479 case '=':
1480 Char = getCharAndSize(CurPtr, SizeTmp);
1481 if (Char == '=') {
1482 Result.setKind(tok::equalequal);
1483 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1484 } else {
1485 Result.setKind(tok::equal);
1486 }
1487 break;
1488 case ',':
1489 Result.setKind(tok::comma);
1490 break;
1491 case '#':
1492 Char = getCharAndSize(CurPtr, SizeTmp);
1493 if (Char == '#') {
1494 Result.setKind(tok::hashhash);
1495 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1496 } else if (Char == '@' && Features.Microsoft) { // #@ -> Charize
1497 Result.setKind(tok::hashat);
1498 Diag(BufferPtr, diag::charize_microsoft_ext);
1499 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1500 } else {
1501 Result.setKind(tok::hash);
1502 // We parsed a # character. If this occurs at the start of the line,
1503 // it's actually the start of a preprocessing directive. Callback to
1504 // the preprocessor to handle it.
1505 // FIXME: -fpreprocessed mode??
1506 if (Result.isAtStartOfLine() && !LexingRawMode) {
1507 BufferPtr = CurPtr;
1508 PP.HandleDirective(Result);
1509
1510 // As an optimization, if the preprocessor didn't switch lexers, tail
1511 // recurse.
1512 if (PP.isCurrentLexer(this)) {
1513 // Start a new token. If this is a #include or something, the PP may
1514 // want us starting at the beginning of the line again. If so, set
1515 // the StartOfLine flag.
1516 if (IsAtStartOfLine) {
Chris Lattnerd2177732007-07-20 16:59:19 +00001517 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00001518 IsAtStartOfLine = false;
1519 }
1520 goto LexNextToken; // GCC isn't tail call eliminating.
1521 }
1522 return PP.Lex(Result);
1523 }
1524 }
1525 break;
1526
1527 case '\\':
1528 // FIXME: UCN's.
1529 // FALL THROUGH.
1530 default:
1531 // Objective C support.
1532 if (CurPtr[-1] == '@' && Features.ObjC1) {
1533 Result.setKind(tok::at);
1534 break;
1535 } else if (CurPtr[-1] == '$' && Features.DollarIdents) {// $ in identifiers.
1536 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
1537 // Notify MIOpt that we read a non-whitespace/non-comment token.
1538 MIOpt.ReadToken();
1539 return LexIdentifier(Result, CurPtr);
1540 }
1541
1542 Result.setKind(tok::unknown);
1543 break;
1544 }
1545
1546 // Notify MIOpt that we read a non-whitespace/non-comment token.
1547 MIOpt.ReadToken();
1548
1549 // Update the location of token as well as BufferPtr.
1550 FormTokenWithChars(Result, CurPtr);
1551}