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