1 //===--- Lexer.cpp - C Language Family Lexer ------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Lexer and Token interfaces.
12 //===----------------------------------------------------------------------===//
14 // TODO: GCC Diagnostics emitted by the lexer:
15 // PEDWARN: (form feed|vertical tab) in preprocessing directive
17 // Universal characters, unicode, char mapping:
18 // WARNING: `%.*s' is not in NFKC
19 // WARNING: `%.*s' is not in NFC
22 // TODO: Options to support:
23 // -fexec-charset,-fwide-exec-charset
25 //===----------------------------------------------------------------------===//
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"
34 using namespace clang;
36 static void InitCharacterInfo();
38 //===----------------------------------------------------------------------===//
39 // Token Class Implementation
40 //===----------------------------------------------------------------------===//
42 /// isObjCAtKeyword - Return true if we have an ObjC keyword identifier.
43 bool Token::isObjCAtKeyword(tok::ObjCKeywordKind objcKey) const {
44 return is(tok::identifier) &&
45 getIdentifierInfo()->getObjCKeywordID() == objcKey;
48 /// getObjCKeywordID - Return the ObjC keyword kind.
49 tok::ObjCKeywordKind Token::getObjCKeywordID() const {
50 IdentifierInfo *specId = getIdentifierInfo();
51 return specId ? specId->getObjCKeywordID() : tok::objc_not_keyword;
54 /// isNamedIdentifier - Return true if this token is a ppidentifier with the
55 /// specified name. For example, tok.isNamedIdentifier("this").
56 bool Token::isNamedIdentifier(const char *Name) const {
57 return IdentInfo && !strcmp(IdentInfo->getName(), Name);
61 //===----------------------------------------------------------------------===//
62 // Lexer Class Implementation
63 //===----------------------------------------------------------------------===//
66 /// Lexer constructor - Create a new lexer object for the specified buffer
67 /// with the specified preprocessor managing the lexing process. This lexer
68 /// assumes that the associated file buffer and Preprocessor objects will
69 /// outlive it, so it doesn't take ownership of either of them.
70 Lexer::Lexer(SourceLocation fileloc, Preprocessor &pp,
71 const char *BufStart, const char *BufEnd)
72 : FileLoc(fileloc), PP(&pp), Features(pp.getLangOptions()) {
74 SourceManager &SourceMgr = PP->getSourceManager();
75 unsigned InputFileID = SourceMgr.getPhysicalLoc(FileLoc).getFileID();
76 const llvm::MemoryBuffer *InputFile = SourceMgr.getBuffer(InputFileID);
78 Is_PragmaLexer = false;
81 // BufferStart must always be InputFile->getBufferStart().
82 BufferStart = InputFile->getBufferStart();
84 // BufferPtr and BufferEnd can start out somewhere inside the current buffer.
85 // If unspecified, they starts at the start/end of the buffer.
86 BufferPtr = BufStart ? BufStart : BufferStart;
87 BufferEnd = BufEnd ? BufEnd : InputFile->getBufferEnd();
89 assert(BufferEnd[0] == 0 &&
90 "We assume that the input buffer has a null character at the end"
91 " to simplify lexing!");
93 // Start of the file is a start of line.
94 IsAtStartOfLine = true;
96 // We are not after parsing a #.
97 ParsingPreprocessorDirective = false;
99 // We are not after parsing #include.
100 ParsingFilename = false;
102 // We are not in raw mode. Raw mode disables diagnostics and interpretation
103 // of tokens (e.g. identifiers, thus disabling macro expansion). It is used
104 // to quickly lex the tokens of the buffer, e.g. when handling a "#if 0" block
105 // or otherwise skipping over tokens.
106 LexingRawMode = false;
108 // Default to keeping comments if requested.
109 KeepCommentMode = PP->getCommentRetentionState();
112 /// Lexer constructor - Create a new raw lexer object. This object is only
113 /// suitable for calls to 'LexRawToken'. This lexer assumes that the
114 /// associated file buffer will outlive it, so it doesn't take ownership of
116 Lexer::Lexer(SourceLocation fileloc, const LangOptions &features,
117 const char *BufStart, const char *BufEnd)
118 : FileLoc(fileloc), PP(0), Features(features) {
119 Is_PragmaLexer = false;
122 BufferStart = BufStart;
123 BufferPtr = BufStart;
126 assert(BufferEnd[0] == 0 &&
127 "We assume that the input buffer has a null character at the end"
128 " to simplify lexing!");
130 // Start of the file is a start of line.
131 IsAtStartOfLine = true;
133 // We are not after parsing a #.
134 ParsingPreprocessorDirective = false;
136 // We are not after parsing #include.
137 ParsingFilename = false;
139 // We *are* in raw mode.
140 LexingRawMode = true;
142 // Never keep comments in raw mode.
143 KeepCommentMode = false;
147 /// Stringify - Convert the specified string into a C string, with surrounding
148 /// ""'s, and with escaped \ and " characters.
149 std::string Lexer::Stringify(const std::string &Str, bool Charify) {
150 std::string Result = Str;
151 char Quote = Charify ? '\'' : '"';
152 for (unsigned i = 0, e = Result.size(); i != e; ++i) {
153 if (Result[i] == '\\' || Result[i] == Quote) {
154 Result.insert(Result.begin()+i, '\\');
161 /// Stringify - Convert the specified string into a C string by escaping '\'
162 /// and " characters. This does not add surrounding ""'s to the string.
163 void Lexer::Stringify(llvm::SmallVectorImpl<char> &Str) {
164 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
165 if (Str[i] == '\\' || Str[i] == '"') {
166 Str.insert(Str.begin()+i, '\\');
173 /// MeasureTokenLength - Relex the token at the specified location and return
174 /// its length in bytes in the input file. If the token needs cleaning (e.g.
175 /// includes a trigraph or an escaped newline) then this count includes bytes
176 /// that are part of that.
177 unsigned Lexer::MeasureTokenLength(SourceLocation Loc,
178 const SourceManager &SM) {
179 // If this comes from a macro expansion, we really do want the macro name, not
180 // the token this macro expanded to.
181 Loc = SM.getLogicalLoc(Loc);
183 const char *StrData = SM.getCharacterData(Loc);
185 // TODO: this could be special cased for common tokens like identifiers, ')',
186 // etc to make this faster, if it mattered. Just look at StrData[0] to handle
187 // all obviously single-char tokens. This could use
188 // Lexer::isObviouslySimpleCharacter for example to handle identifiers or
192 const char *BufEnd = SM.getBufferData(Loc.getFileID()).second;
194 // Create a langops struct and enable trigraphs. This is sufficient for
196 LangOptions LangOpts;
197 LangOpts.Trigraphs = true;
199 // Create a lexer starting at the beginning of this token.
200 Lexer TheLexer(Loc, LangOpts, StrData, BufEnd);
202 TheLexer.LexRawToken(TheTok);
203 return TheTok.getLength();
206 //===----------------------------------------------------------------------===//
207 // Character information.
208 //===----------------------------------------------------------------------===//
210 static unsigned char CharInfo[256];
213 CHAR_HORZ_WS = 0x01, // ' ', '\t', '\f', '\v'. Note, no '\0'
214 CHAR_VERT_WS = 0x02, // '\r', '\n'
215 CHAR_LETTER = 0x04, // a-z,A-Z
216 CHAR_NUMBER = 0x08, // 0-9
217 CHAR_UNDER = 0x10, // _
218 CHAR_PERIOD = 0x20 // .
221 static void InitCharacterInfo() {
222 static bool isInited = false;
223 if (isInited) return;
226 // Intiialize the CharInfo table.
227 // TODO: statically initialize this.
228 CharInfo[(int)' '] = CharInfo[(int)'\t'] =
229 CharInfo[(int)'\f'] = CharInfo[(int)'\v'] = CHAR_HORZ_WS;
230 CharInfo[(int)'\n'] = CharInfo[(int)'\r'] = CHAR_VERT_WS;
232 CharInfo[(int)'_'] = CHAR_UNDER;
233 CharInfo[(int)'.'] = CHAR_PERIOD;
234 for (unsigned i = 'a'; i <= 'z'; ++i)
235 CharInfo[i] = CharInfo[i+'A'-'a'] = CHAR_LETTER;
236 for (unsigned i = '0'; i <= '9'; ++i)
237 CharInfo[i] = CHAR_NUMBER;
240 /// isIdentifierBody - Return true if this is the body character of an
241 /// identifier, which is [a-zA-Z0-9_].
242 static inline bool isIdentifierBody(unsigned char c) {
243 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER)) ? true : false;
246 /// isHorizontalWhitespace - Return true if this character is horizontal
247 /// whitespace: ' ', '\t', '\f', '\v'. Note that this returns false for '\0'.
248 static inline bool isHorizontalWhitespace(unsigned char c) {
249 return (CharInfo[c] & CHAR_HORZ_WS) ? true : false;
252 /// isWhitespace - Return true if this character is horizontal or vertical
253 /// whitespace: ' ', '\t', '\f', '\v', '\n', '\r'. Note that this returns false
255 static inline bool isWhitespace(unsigned char c) {
256 return (CharInfo[c] & (CHAR_HORZ_WS|CHAR_VERT_WS)) ? true : false;
259 /// isNumberBody - Return true if this is the body character of an
260 /// preprocessing number, which is [a-zA-Z0-9_.].
261 static inline bool isNumberBody(unsigned char c) {
262 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER|CHAR_PERIOD)) ?
267 //===----------------------------------------------------------------------===//
268 // Diagnostics forwarding code.
269 //===----------------------------------------------------------------------===//
271 /// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
272 /// lexer buffer was all instantiated at a single point, perform the mapping.
273 /// This is currently only used for _Pragma implementation, so it is the slow
274 /// path of the hot getSourceLocation method. Do not allow it to be inlined.
275 static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
276 SourceLocation FileLoc,
277 unsigned CharNo) DISABLE_INLINE;
278 static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
279 SourceLocation FileLoc,
281 // Otherwise, we're lexing "mapped tokens". This is used for things like
282 // _Pragma handling. Combine the instantiation location of FileLoc with the
283 // physical location.
284 SourceManager &SourceMgr = PP.getSourceManager();
286 // Create a new SLoc which is expanded from logical(FileLoc) but whose
287 // characters come from phys(FileLoc)+Offset.
288 SourceLocation VirtLoc = SourceMgr.getLogicalLoc(FileLoc);
289 SourceLocation PhysLoc = SourceMgr.getPhysicalLoc(FileLoc);
290 PhysLoc = SourceLocation::getFileLoc(PhysLoc.getFileID(), CharNo);
291 return SourceMgr.getInstantiationLoc(PhysLoc, VirtLoc);
294 /// getSourceLocation - Return a source location identifier for the specified
295 /// offset in the current file.
296 SourceLocation Lexer::getSourceLocation(const char *Loc) const {
297 assert(Loc >= BufferStart && Loc <= BufferEnd &&
298 "Location out of range for this buffer!");
300 // In the normal case, we're just lexing from a simple file buffer, return
301 // the file id from FileLoc with the offset specified.
302 unsigned CharNo = Loc-BufferStart;
303 if (FileLoc.isFileID())
304 return SourceLocation::getFileLoc(FileLoc.getFileID(), CharNo);
306 assert(PP && "This doesn't work on raw lexers");
307 return GetMappedTokenLoc(*PP, FileLoc, CharNo);
310 /// Diag - Forwarding function for diagnostics. This translate a source
311 /// position in the current buffer into a SourceLocation object for rendering.
312 void Lexer::Diag(const char *Loc, unsigned DiagID,
313 const std::string &Msg) const {
314 if (LexingRawMode && Diagnostic::isBuiltinNoteWarningOrExtension(DiagID))
316 PP->Diag(getSourceLocation(Loc), DiagID, Msg);
318 void Lexer::Diag(SourceLocation Loc, unsigned DiagID,
319 const std::string &Msg) const {
320 if (LexingRawMode && Diagnostic::isBuiltinNoteWarningOrExtension(DiagID))
322 PP->Diag(Loc, DiagID, Msg);
326 //===----------------------------------------------------------------------===//
327 // Trigraph and Escaped Newline Handling Code.
328 //===----------------------------------------------------------------------===//
330 /// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
331 /// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
332 static char GetTrigraphCharForLetter(char Letter) {
335 case '=': return '#';
336 case ')': return ']';
337 case '(': return '[';
338 case '!': return '|';
339 case '\'': return '^';
340 case '>': return '}';
341 case '/': return '\\';
342 case '<': return '{';
343 case '-': return '~';
347 /// DecodeTrigraphChar - If the specified character is a legal trigraph when
348 /// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
349 /// return the result character. Finally, emit a warning about trigraph use
350 /// whether trigraphs are enabled or not.
351 static char DecodeTrigraphChar(const char *CP, Lexer *L) {
352 char Res = GetTrigraphCharForLetter(*CP);
354 if (!L->getFeatures().Trigraphs) {
355 L->Diag(CP-2, diag::trigraph_ignored);
358 L->Diag(CP-2, diag::trigraph_converted, std::string()+Res);
364 /// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
365 /// get its size, and return it. This is tricky in several cases:
366 /// 1. If currently at the start of a trigraph, we warn about the trigraph,
367 /// then either return the trigraph (skipping 3 chars) or the '?',
368 /// depending on whether trigraphs are enabled or not.
369 /// 2. If this is an escaped newline (potentially with whitespace between
370 /// the backslash and newline), implicitly skip the newline and return
371 /// the char after it.
372 /// 3. If this is a UCN, return it. FIXME: C++ UCN's?
374 /// This handles the slow/uncommon case of the getCharAndSize method. Here we
375 /// know that we can accumulate into Size, and that we have already incremented
376 /// Ptr by Size bytes.
378 /// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
379 /// be updated to match.
381 char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
383 // If we have a slash, look for an escaped newline.
384 if (Ptr[0] == '\\') {
388 // Common case, backslash-char where the char is not whitespace.
389 if (!isWhitespace(Ptr[0])) return '\\';
391 // See if we have optional whitespace characters followed by a newline.
393 unsigned SizeTmp = 0;
396 if (Ptr[SizeTmp-1] == '\n' || Ptr[SizeTmp-1] == '\r') {
397 // Remember that this token needs to be cleaned.
398 if (Tok) Tok->setFlag(Token::NeedsCleaning);
400 // Warn if there was whitespace between the backslash and newline.
401 if (SizeTmp != 1 && Tok)
402 Diag(Ptr, diag::backslash_newline_space);
404 // If this is a \r\n or \n\r, skip the newlines.
405 if ((Ptr[SizeTmp] == '\r' || Ptr[SizeTmp] == '\n') &&
406 Ptr[SizeTmp-1] != Ptr[SizeTmp])
409 // Found backslash<whitespace><newline>. Parse the char after it.
412 // Use slow version to accumulate a correct size field.
413 return getCharAndSizeSlow(Ptr, Size, Tok);
415 } while (isWhitespace(Ptr[SizeTmp]));
418 // Otherwise, this is not an escaped newline, just return the slash.
422 // If this is a trigraph, process it.
423 if (Ptr[0] == '?' && Ptr[1] == '?') {
424 // If this is actually a legal trigraph (not something like "??x"), emit
425 // a trigraph warning. If so, and if trigraphs are enabled, return it.
426 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : 0)) {
427 // Remember that this token needs to be cleaned.
428 if (Tok) Tok->setFlag(Token::NeedsCleaning);
432 if (C == '\\') goto Slash;
437 // If this is neither, return a single character.
443 /// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
444 /// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
445 /// and that we have already incremented Ptr by Size bytes.
447 /// NOTE: When this method is updated, getCharAndSizeSlow (above) should
448 /// be updated to match.
449 char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
450 const LangOptions &Features) {
451 // If we have a slash, look for an escaped newline.
452 if (Ptr[0] == '\\') {
456 // Common case, backslash-char where the char is not whitespace.
457 if (!isWhitespace(Ptr[0])) return '\\';
459 // See if we have optional whitespace characters followed by a newline.
461 unsigned SizeTmp = 0;
464 if (Ptr[SizeTmp-1] == '\n' || Ptr[SizeTmp-1] == '\r') {
466 // If this is a \r\n or \n\r, skip the newlines.
467 if ((Ptr[SizeTmp] == '\r' || Ptr[SizeTmp] == '\n') &&
468 Ptr[SizeTmp-1] != Ptr[SizeTmp])
471 // Found backslash<whitespace><newline>. Parse the char after it.
475 // Use slow version to accumulate a correct size field.
476 return getCharAndSizeSlowNoWarn(Ptr, Size, Features);
478 } while (isWhitespace(Ptr[SizeTmp]));
481 // Otherwise, this is not an escaped newline, just return the slash.
485 // If this is a trigraph, process it.
486 if (Features.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
487 // If this is actually a legal trigraph (not something like "??x"), return
489 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
492 if (C == '\\') goto Slash;
497 // If this is neither, return a single character.
502 //===----------------------------------------------------------------------===//
503 // Helper methods for lexing.
504 //===----------------------------------------------------------------------===//
506 void Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
507 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
509 unsigned char C = *CurPtr++;
510 while (isIdentifierBody(C)) {
513 --CurPtr; // Back up over the skipped character.
515 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
516 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
518 if (C != '\\' && C != '?' && (C != '$' || !Features.DollarIdents)) {
520 const char *IdStart = BufferPtr;
521 FormTokenWithChars(Result, CurPtr);
522 Result.setKind(tok::identifier);
524 // If we are in raw mode, return this identifier raw. There is no need to
525 // look up identifier information or attempt to macro expand it.
526 if (LexingRawMode) return;
528 // Fill in Result.IdentifierInfo, looking up the identifier in the
530 PP->LookUpIdentifierInfo(Result, IdStart);
532 // Finally, now that we know we have an identifier, pass this off to the
533 // preprocessor, which may macro expand it or something.
534 return PP->HandleIdentifier(Result);
537 // Otherwise, $,\,? in identifier found. Enter slower path.
539 C = getCharAndSize(CurPtr, Size);
542 // If we hit a $ and they are not supported in identifiers, we are done.
543 if (!Features.DollarIdents) goto FinishIdentifier;
545 // Otherwise, emit a diagnostic and continue.
546 Diag(CurPtr, diag::ext_dollar_in_identifier);
547 CurPtr = ConsumeChar(CurPtr, Size, Result);
548 C = getCharAndSize(CurPtr, Size);
550 } else if (!isIdentifierBody(C)) { // FIXME: UCNs.
551 // Found end of identifier.
552 goto FinishIdentifier;
555 // Otherwise, this character is good, consume it.
556 CurPtr = ConsumeChar(CurPtr, Size, Result);
558 C = getCharAndSize(CurPtr, Size);
559 while (isIdentifierBody(C)) { // FIXME: UCNs.
560 CurPtr = ConsumeChar(CurPtr, Size, Result);
561 C = getCharAndSize(CurPtr, Size);
567 /// LexNumericConstant - Lex the remainer of a integer or floating point
568 /// constant. From[-1] is the first character lexed. Return the end of the
570 void Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
572 char C = getCharAndSize(CurPtr, Size);
574 while (isNumberBody(C)) { // FIXME: UCNs?
575 CurPtr = ConsumeChar(CurPtr, Size, Result);
577 C = getCharAndSize(CurPtr, Size);
580 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
581 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e'))
582 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
584 // If we have a hex FP constant, continue.
585 if (Features.HexFloats &&
586 (C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p'))
587 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
589 Result.setKind(tok::numeric_constant);
591 // Update the location of token as well as BufferPtr.
592 FormTokenWithChars(Result, CurPtr);
595 /// LexStringLiteral - Lex the remainder of a string literal, after having lexed
597 void Lexer::LexStringLiteral(Token &Result, const char *CurPtr, bool Wide){
598 const char *NulCharacter = 0; // Does this string contain the \0 character?
600 char C = getAndAdvanceChar(CurPtr, Result);
602 // Skip escaped characters.
604 // Skip the escaped character.
605 C = getAndAdvanceChar(CurPtr, Result);
606 } else if (C == '\n' || C == '\r' || // Newline.
607 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
608 if (!LexingRawMode) Diag(BufferPtr, diag::err_unterminated_string);
609 Result.setKind(tok::unknown);
610 FormTokenWithChars(Result, CurPtr-1);
613 NulCharacter = CurPtr-1;
615 C = getAndAdvanceChar(CurPtr, Result);
618 // If a nul character existed in the string, warn about it.
619 if (NulCharacter) Diag(NulCharacter, diag::null_in_string);
621 Result.setKind(Wide ? tok::wide_string_literal : tok::string_literal);
623 // Update the location of the token as well as the BufferPtr instance var.
624 FormTokenWithChars(Result, CurPtr);
627 /// LexAngledStringLiteral - Lex the remainder of an angled string literal,
628 /// after having lexed the '<' character. This is used for #include filenames.
629 void Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
630 const char *NulCharacter = 0; // Does this string contain the \0 character?
632 char C = getAndAdvanceChar(CurPtr, Result);
634 // Skip escaped characters.
636 // Skip the escaped character.
637 C = getAndAdvanceChar(CurPtr, Result);
638 } else if (C == '\n' || C == '\r' || // Newline.
639 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
640 if (!LexingRawMode) Diag(BufferPtr, diag::err_unterminated_string);
641 Result.setKind(tok::unknown);
642 FormTokenWithChars(Result, CurPtr-1);
645 NulCharacter = CurPtr-1;
647 C = getAndAdvanceChar(CurPtr, Result);
650 // If a nul character existed in the string, warn about it.
651 if (NulCharacter) Diag(NulCharacter, diag::null_in_string);
653 Result.setKind(tok::angle_string_literal);
655 // Update the location of token as well as BufferPtr.
656 FormTokenWithChars(Result, CurPtr);
660 /// LexCharConstant - Lex the remainder of a character constant, after having
661 /// lexed either ' or L'.
662 void Lexer::LexCharConstant(Token &Result, const char *CurPtr) {
663 const char *NulCharacter = 0; // Does this character contain the \0 character?
665 // Handle the common case of 'x' and '\y' efficiently.
666 char C = getAndAdvanceChar(CurPtr, Result);
668 if (!LexingRawMode) Diag(BufferPtr, diag::err_empty_character);
669 Result.setKind(tok::unknown);
670 FormTokenWithChars(Result, CurPtr);
672 } else if (C == '\\') {
673 // Skip the escaped character.
675 C = getAndAdvanceChar(CurPtr, Result);
678 if (C && C != '\n' && C != '\r' && CurPtr[0] == '\'') {
681 // Fall back on generic code for embedded nulls, newlines, wide chars.
683 // Skip escaped characters.
685 // Skip the escaped character.
686 C = getAndAdvanceChar(CurPtr, Result);
687 } else if (C == '\n' || C == '\r' || // Newline.
688 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
689 if (!LexingRawMode) Diag(BufferPtr, diag::err_unterminated_char);
690 Result.setKind(tok::unknown);
691 FormTokenWithChars(Result, CurPtr-1);
694 NulCharacter = CurPtr-1;
696 C = getAndAdvanceChar(CurPtr, Result);
700 if (NulCharacter) Diag(NulCharacter, diag::null_in_char);
702 Result.setKind(tok::char_constant);
704 // Update the location of token as well as BufferPtr.
705 FormTokenWithChars(Result, CurPtr);
708 /// SkipWhitespace - Efficiently skip over a series of whitespace characters.
709 /// Update BufferPtr to point to the next non-whitespace character and return.
710 void Lexer::SkipWhitespace(Token &Result, const char *CurPtr) {
711 // Whitespace - Skip it, then return the token after the whitespace.
712 unsigned char Char = *CurPtr; // Skip consequtive spaces efficiently.
714 // Skip horizontal whitespace very aggressively.
715 while (isHorizontalWhitespace(Char))
718 // Otherwise if we something other than whitespace, we're done.
719 if (Char != '\n' && Char != '\r')
722 if (ParsingPreprocessorDirective) {
723 // End of preprocessor directive line, let LexTokenInternal handle this.
728 // ok, but handle newline.
729 // The returned token is at the start of the line.
730 Result.setFlag(Token::StartOfLine);
731 // No leading whitespace seen so far.
732 Result.clearFlag(Token::LeadingSpace);
736 // If this isn't immediately after a newline, there is leading space.
737 char PrevChar = CurPtr[-1];
738 if (PrevChar != '\n' && PrevChar != '\r')
739 Result.setFlag(Token::LeadingSpace);
744 // SkipBCPLComment - We have just read the // characters from input. Skip until
745 // we find the newline character thats terminate the comment. Then update
746 /// BufferPtr and return.
747 bool Lexer::SkipBCPLComment(Token &Result, const char *CurPtr) {
748 // If BCPL comments aren't explicitly enabled for this language, emit an
749 // extension warning.
750 if (!Features.BCPLComment) {
751 Diag(BufferPtr, diag::ext_bcpl_comment);
753 // Mark them enabled so we only emit one warning for this translation
755 Features.BCPLComment = true;
758 // Scan over the body of the comment. The common case, when scanning, is that
759 // the comment contains normal ascii characters with nothing interesting in
760 // them. As such, optimize for this case with the inner loop.
764 // FIXME: Speedup BCPL comment lexing. Just scan for a \n or \r character.
765 // If we find a \n character, scan backwards, checking to see if it's an
766 // escaped newline, like we do for block comments.
768 // Skip over characters in the fast loop.
769 while (C != 0 && // Potentially EOF.
770 C != '\\' && // Potentially escaped newline.
771 C != '?' && // Potentially trigraph.
772 C != '\n' && C != '\r') // Newline or DOS-style newline.
775 // If this is a newline, we're done.
776 if (C == '\n' || C == '\r')
777 break; // Found the newline? Break out!
779 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
780 // properly decode the character.
781 const char *OldPtr = CurPtr;
782 C = getAndAdvanceChar(CurPtr, Result);
784 // If we read multiple characters, and one of those characters was a \r or
785 // \n, then we had an escaped newline within the comment. Emit diagnostic
786 // unless the next line is also a // comment.
787 if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') {
788 for (; OldPtr != CurPtr; ++OldPtr)
789 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
790 // Okay, we found a // comment that ends in a newline, if the next
791 // line is also a // comment, but has spaces, don't emit a diagnostic.
793 const char *ForwardPtr = CurPtr;
794 while (isspace(*ForwardPtr)) // Skip whitespace.
796 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
800 Diag(OldPtr-1, diag::ext_multi_line_bcpl_comment);
805 if (CurPtr == BufferEnd+1) { --CurPtr; break; }
806 } while (C != '\n' && C != '\r');
808 // Found but did not consume the newline.
810 // If we are returning comments as tokens, return this comment as a token.
812 return SaveBCPLComment(Result, CurPtr);
814 // If we are inside a preprocessor directive and we see the end of line,
815 // return immediately, so that the lexer can return this as an EOM token.
816 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
821 // Otherwise, eat the \n character. We don't care if this is a \n\r or
825 // The next returned token is at the start of the line.
826 Result.setFlag(Token::StartOfLine);
827 // No leading whitespace seen so far.
828 Result.clearFlag(Token::LeadingSpace);
833 /// SaveBCPLComment - If in save-comment mode, package up this BCPL comment in
834 /// an appropriate way and return it.
835 bool Lexer::SaveBCPLComment(Token &Result, const char *CurPtr) {
836 Result.setKind(tok::comment);
837 FormTokenWithChars(Result, CurPtr);
839 // If this BCPL-style comment is in a macro definition, transmogrify it into
840 // a C-style block comment.
841 if (ParsingPreprocessorDirective) {
842 std::string Spelling = PP->getSpelling(Result);
843 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not bcpl comment?");
844 Spelling[1] = '*'; // Change prefix to "/*".
845 Spelling += "*/"; // add suffix.
847 Result.setLocation(PP->CreateString(&Spelling[0], Spelling.size(),
848 Result.getLocation()));
849 Result.setLength(Spelling.size());
854 /// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
855 /// character (either \n or \r) is part of an escaped newline sequence. Issue a
856 /// diagnostic if so. We know that the is inside of a block comment.
857 static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
859 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
861 // Back up off the newline.
864 // If this is a two-character newline sequence, skip the other character.
865 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
866 // \n\n or \r\r -> not escaped newline.
867 if (CurPtr[0] == CurPtr[1])
869 // \n\r or \r\n -> skip the newline.
873 // If we have horizontal whitespace, skip over it. We allow whitespace
874 // between the slash and newline.
875 bool HasSpace = false;
876 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
881 // If we have a slash, we know this is an escaped newline.
882 if (*CurPtr == '\\') {
883 if (CurPtr[-1] != '*') return false;
885 // It isn't a slash, is it the ?? / trigraph?
886 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
890 // This is the trigraph ending the comment. Emit a stern warning!
893 // If no trigraphs are enabled, warn that we ignored this trigraph and
894 // ignore this * character.
895 if (!L->getFeatures().Trigraphs) {
896 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
899 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
902 // Warn about having an escaped newline between the */ characters.
903 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
905 // If there was space between the backslash and newline, warn about it.
906 if (HasSpace) L->Diag(CurPtr, diag::backslash_newline_space);
912 #include <emmintrin.h>
918 /// SkipBlockComment - We have just read the /* characters from input. Read
919 /// until we find the */ characters that terminate the comment. Note that we
920 /// don't bother decoding trigraphs or escaped newlines in block comments,
921 /// because they cannot cause the comment to end. The only thing that can
922 /// happen is the comment could end with an escaped newline between the */ end
924 bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr) {
925 // Scan one character past where we should, looking for a '/' character. Once
926 // we find it, check to see if it was preceeded by a *. This common
927 // optimization helps people who like to put a lot of * characters in their
930 // The first character we get with newlines and trigraphs skipped to handle
931 // the degenerate /*/ case below correctly if the * has an escaped newline
934 unsigned char C = getCharAndSize(CurPtr, CharSize);
936 if (C == 0 && CurPtr == BufferEnd+1) {
937 Diag(BufferPtr, diag::err_unterminated_block_comment);
938 BufferPtr = CurPtr-1;
942 // Check to see if the first character after the '/*' is another /. If so,
943 // then this slash does not end the block comment, it is part of it.
948 // Skip over all non-interesting characters until we find end of buffer or a
949 // (probably ending) '/' character.
950 if (CurPtr + 24 < BufferEnd) {
951 // While not aligned to a 16-byte boundary.
952 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
955 if (C == '/') goto FoundSlash;
958 __m128i Slashes = _mm_set_epi8('/', '/', '/', '/', '/', '/', '/', '/',
959 '/', '/', '/', '/', '/', '/', '/', '/');
960 while (CurPtr+16 <= BufferEnd &&
961 _mm_movemask_epi8(_mm_cmpeq_epi8(*(__m128i*)CurPtr, Slashes)) == 0)
964 __vector unsigned char Slashes = {
965 '/', '/', '/', '/', '/', '/', '/', '/',
966 '/', '/', '/', '/', '/', '/', '/', '/'
968 while (CurPtr+16 <= BufferEnd &&
969 !vec_any_eq(*(vector unsigned char*)CurPtr, Slashes))
972 // Scan for '/' quickly. Many block comments are very large.
973 while (CurPtr[0] != '/' &&
977 CurPtr+4 < BufferEnd) {
982 // It has to be one of the bytes scanned, increment to it and read one.
986 // Loop to scan the remainder.
987 while (C != '/' && C != '\0')
992 if (CurPtr[-2] == '*') // We found the final */. We're done!
995 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
996 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
997 // We found the final */, though it had an escaped newline between the
998 // * and /. We're done!
1002 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
1003 // If this is a /* inside of the comment, emit a warning. Don't do this
1004 // if this is a /*/, which will end the comment. This misses cases with
1005 // embedded escaped newlines, but oh well.
1006 Diag(CurPtr-1, diag::nested_block_comment);
1008 } else if (C == 0 && CurPtr == BufferEnd+1) {
1009 Diag(BufferPtr, diag::err_unterminated_block_comment);
1010 // Note: the user probably forgot a */. We could continue immediately
1011 // after the /*, but this would involve lexing a lot of what really is the
1012 // comment, which surely would confuse the parser.
1013 BufferPtr = CurPtr-1;
1019 // If we are returning comments as tokens, return this comment as a token.
1020 if (KeepCommentMode) {
1021 Result.setKind(tok::comment);
1022 FormTokenWithChars(Result, CurPtr);
1026 // It is common for the tokens immediately after a /**/ comment to be
1027 // whitespace. Instead of going through the big switch, handle it
1029 if (isHorizontalWhitespace(*CurPtr)) {
1030 Result.setFlag(Token::LeadingSpace);
1031 SkipWhitespace(Result, CurPtr+1);
1035 // Otherwise, just return so that the next character will be lexed as a token.
1037 Result.setFlag(Token::LeadingSpace);
1041 //===----------------------------------------------------------------------===//
1042 // Primary Lexing Entry Points
1043 //===----------------------------------------------------------------------===//
1045 /// LexIncludeFilename - After the preprocessor has parsed a #include, lex and
1046 /// (potentially) macro expand the filename.
1047 void Lexer::LexIncludeFilename(Token &FilenameTok) {
1048 assert(ParsingPreprocessorDirective &&
1049 ParsingFilename == false &&
1050 "Must be in a preprocessing directive!");
1052 // We are now parsing a filename!
1053 ParsingFilename = true;
1055 // Lex the filename.
1058 // We should have obtained the filename now.
1059 ParsingFilename = false;
1062 if (FilenameTok.is(tok::eom))
1063 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1066 /// ReadToEndOfLine - Read the rest of the current preprocessor line as an
1067 /// uninterpreted string. This switches the lexer out of directive mode.
1068 std::string Lexer::ReadToEndOfLine() {
1069 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
1070 "Must be in a preprocessing directive!");
1074 // CurPtr - Cache BufferPtr in an automatic variable.
1075 const char *CurPtr = BufferPtr;
1077 char Char = getAndAdvanceChar(CurPtr, Tmp);
1083 // Found end of file?
1084 if (CurPtr-1 != BufferEnd) {
1085 // Nope, normal character, continue.
1092 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
1093 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
1094 BufferPtr = CurPtr-1;
1096 // Next, lex the character, which should handle the EOM transition.
1098 assert(Tmp.is(tok::eom) && "Unexpected token!");
1100 // Finally, we're done, return the string we found.
1106 /// LexEndOfFile - CurPtr points to the end of this file. Handle this
1107 /// condition, reporting diagnostics and handling other edge cases as required.
1108 /// This returns true if Result contains a token, false if PP.Lex should be
1110 bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
1111 // If we hit the end of the file while parsing a preprocessor directive,
1112 // end the preprocessor directive first. The next token returned will
1113 // then be the end of file.
1114 if (ParsingPreprocessorDirective) {
1115 // Done parsing the "line".
1116 ParsingPreprocessorDirective = false;
1117 Result.setKind(tok::eom);
1118 // Update the location of token as well as BufferPtr.
1119 FormTokenWithChars(Result, CurPtr);
1121 // Restore comment saving mode, in case it was disabled for directive.
1122 KeepCommentMode = PP->getCommentRetentionState();
1123 return true; // Have a token.
1126 // If we are in raw mode, return this event as an EOF token. Let the caller
1127 // that put us in raw mode handle the event.
1128 if (LexingRawMode) {
1129 Result.startToken();
1130 BufferPtr = BufferEnd;
1131 FormTokenWithChars(Result, BufferEnd);
1132 Result.setKind(tok::eof);
1136 // Otherwise, issue diagnostics for unterminated #if and missing newline.
1138 // If we are in a #if directive, emit an error.
1139 while (!ConditionalStack.empty()) {
1140 Diag(ConditionalStack.back().IfLoc, diag::err_pp_unterminated_conditional);
1141 ConditionalStack.pop_back();
1144 // If the file was empty or didn't end in a newline, issue a pedwarn.
1145 if (CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
1146 Diag(BufferEnd, diag::ext_no_newline_eof);
1150 // Finally, let the preprocessor handle this.
1151 return PP->HandleEndOfFile(Result);
1154 /// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
1155 /// the specified lexer will return a tok::l_paren token, 0 if it is something
1156 /// else and 2 if there are no more tokens in the buffer controlled by the
1158 unsigned Lexer::isNextPPTokenLParen() {
1159 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
1161 // Switch to 'skipping' mode. This will ensure that we can lex a token
1162 // without emitting diagnostics, disables macro expansion, and will cause EOF
1163 // to return an EOF token instead of popping the include stack.
1164 LexingRawMode = true;
1166 // Save state that can be changed while lexing so that we can restore it.
1167 const char *TmpBufferPtr = BufferPtr;
1171 LexTokenInternal(Tok);
1173 // Restore state that may have changed.
1174 BufferPtr = TmpBufferPtr;
1176 // Restore the lexer back to non-skipping mode.
1177 LexingRawMode = false;
1179 if (Tok.is(tok::eof))
1181 return Tok.is(tok::l_paren);
1185 /// LexTokenInternal - This implements a simple C family lexer. It is an
1186 /// extremely performance critical piece of code. This assumes that the buffer
1187 /// has a null character at the end of the file. Return true if an error
1188 /// occurred and compilation should terminate, false if normal. This returns a
1189 /// preprocessing token, not a normal token, as such, it is an internal
1190 /// interface. It assumes that the Flags of result have been cleared before
1192 void Lexer::LexTokenInternal(Token &Result) {
1194 // New token, can't need cleaning yet.
1195 Result.clearFlag(Token::NeedsCleaning);
1196 Result.setIdentifierInfo(0);
1198 // CurPtr - Cache BufferPtr in an automatic variable.
1199 const char *CurPtr = BufferPtr;
1201 // Small amounts of horizontal whitespace is very common between tokens.
1202 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
1204 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
1207 Result.setFlag(Token::LeadingSpace);
1210 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
1212 // Read a character, advancing over it.
1213 char Char = getAndAdvanceChar(CurPtr, Result);
1216 // Found end of file?
1217 if (CurPtr-1 == BufferEnd) {
1218 // Read the PP instance variable into an automatic variable, because
1219 // LexEndOfFile will often delete 'this'.
1220 Preprocessor *PPCache = PP;
1221 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
1222 return; // Got a token to return.
1223 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
1224 return PPCache->Lex(Result);
1227 Diag(CurPtr-1, diag::null_in_file);
1228 Result.setFlag(Token::LeadingSpace);
1229 SkipWhitespace(Result, CurPtr);
1230 goto LexNextToken; // GCC isn't tail call eliminating.
1233 // If we are inside a preprocessor directive and we see the end of line,
1234 // we know we are done with the directive, so return an EOM token.
1235 if (ParsingPreprocessorDirective) {
1236 // Done parsing the "line".
1237 ParsingPreprocessorDirective = false;
1239 // Restore comment saving mode, in case it was disabled for directive.
1240 KeepCommentMode = PP->getCommentRetentionState();
1242 // Since we consumed a newline, we are back at the start of a line.
1243 IsAtStartOfLine = true;
1245 Result.setKind(tok::eom);
1248 // The returned token is at the start of the line.
1249 Result.setFlag(Token::StartOfLine);
1250 // No leading whitespace seen so far.
1251 Result.clearFlag(Token::LeadingSpace);
1252 SkipWhitespace(Result, CurPtr);
1253 goto LexNextToken; // GCC isn't tail call eliminating.
1258 SkipHorizontalWhitespace:
1259 Result.setFlag(Token::LeadingSpace);
1260 SkipWhitespace(Result, CurPtr);
1265 // If the next token is obviously a // or /* */ comment, skip it efficiently
1266 // too (without going through the big switch stmt).
1267 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !KeepCommentMode) {
1268 SkipBCPLComment(Result, CurPtr+2);
1269 goto SkipIgnoredUnits;
1270 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !KeepCommentMode) {
1271 SkipBlockComment(Result, CurPtr+2);
1272 goto SkipIgnoredUnits;
1273 } else if (isHorizontalWhitespace(*CurPtr)) {
1274 goto SkipHorizontalWhitespace;
1276 goto LexNextToken; // GCC isn't tail call eliminating.
1278 // C99 6.4.4.1: Integer Constants.
1279 // C99 6.4.4.2: Floating Constants.
1280 case '0': case '1': case '2': case '3': case '4':
1281 case '5': case '6': case '7': case '8': case '9':
1282 // Notify MIOpt that we read a non-whitespace/non-comment token.
1284 return LexNumericConstant(Result, CurPtr);
1286 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
1287 // Notify MIOpt that we read a non-whitespace/non-comment token.
1289 Char = getCharAndSize(CurPtr, SizeTmp);
1291 // Wide string literal.
1293 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
1296 // Wide character constant.
1298 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
1299 // FALL THROUGH, treating L like the start of an identifier.
1301 // C99 6.4.2: Identifiers.
1302 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
1303 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
1304 case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U':
1305 case 'V': case 'W': case 'X': case 'Y': case 'Z':
1306 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
1307 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
1308 case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u':
1309 case 'v': case 'w': case 'x': case 'y': case 'z':
1311 // Notify MIOpt that we read a non-whitespace/non-comment token.
1313 return LexIdentifier(Result, CurPtr);
1315 case '$': // $ in identifiers.
1316 if (Features.DollarIdents) {
1317 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
1318 // Notify MIOpt that we read a non-whitespace/non-comment token.
1320 return LexIdentifier(Result, CurPtr);
1323 Result.setKind(tok::unknown);
1326 // C99 6.4.4: Character Constants.
1328 // Notify MIOpt that we read a non-whitespace/non-comment token.
1330 return LexCharConstant(Result, CurPtr);
1332 // C99 6.4.5: String Literals.
1334 // Notify MIOpt that we read a non-whitespace/non-comment token.
1336 return LexStringLiteral(Result, CurPtr, false);
1338 // C99 6.4.6: Punctuators.
1340 Result.setKind(tok::question);
1343 Result.setKind(tok::l_square);
1346 Result.setKind(tok::r_square);
1349 Result.setKind(tok::l_paren);
1352 Result.setKind(tok::r_paren);
1355 Result.setKind(tok::l_brace);
1358 Result.setKind(tok::r_brace);
1361 Char = getCharAndSize(CurPtr, SizeTmp);
1362 if (Char >= '0' && Char <= '9') {
1363 // Notify MIOpt that we read a non-whitespace/non-comment token.
1366 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
1367 } else if (Features.CPlusPlus && Char == '*') {
1368 Result.setKind(tok::periodstar);
1370 } else if (Char == '.' &&
1371 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
1372 Result.setKind(tok::ellipsis);
1373 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1376 Result.setKind(tok::period);
1380 Char = getCharAndSize(CurPtr, SizeTmp);
1382 Result.setKind(tok::ampamp);
1383 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1384 } else if (Char == '=') {
1385 Result.setKind(tok::ampequal);
1386 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1388 Result.setKind(tok::amp);
1392 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
1393 Result.setKind(tok::starequal);
1394 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1396 Result.setKind(tok::star);
1400 Char = getCharAndSize(CurPtr, SizeTmp);
1402 Result.setKind(tok::plusplus);
1403 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1404 } else if (Char == '=') {
1405 Result.setKind(tok::plusequal);
1406 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1408 Result.setKind(tok::plus);
1412 Char = getCharAndSize(CurPtr, SizeTmp);
1414 Result.setKind(tok::minusminus);
1415 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1416 } else if (Char == '>' && Features.CPlusPlus &&
1417 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') {
1418 Result.setKind(tok::arrowstar); // C++ ->*
1419 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1421 } else if (Char == '>') {
1422 Result.setKind(tok::arrow);
1423 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1424 } else if (Char == '=') {
1425 Result.setKind(tok::minusequal);
1426 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1428 Result.setKind(tok::minus);
1432 Result.setKind(tok::tilde);
1435 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
1436 Result.setKind(tok::exclaimequal);
1437 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1439 Result.setKind(tok::exclaim);
1444 Char = getCharAndSize(CurPtr, SizeTmp);
1445 if (Char == '/') { // BCPL comment.
1446 if (SkipBCPLComment(Result, ConsumeChar(CurPtr, SizeTmp, Result))) {
1447 // It is common for the tokens immediately after a // comment to be
1448 // whitespace (indentation for the next line). Instead of going through
1449 // the big switch, handle it efficiently now.
1450 goto SkipIgnoredUnits;
1452 return; // KeepCommentMode
1453 } else if (Char == '*') { // /**/ comment.
1454 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
1455 goto LexNextToken; // GCC isn't tail call eliminating.
1456 return; // KeepCommentMode
1457 } else if (Char == '=') {
1458 Result.setKind(tok::slashequal);
1459 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1461 Result.setKind(tok::slash);
1465 Char = getCharAndSize(CurPtr, SizeTmp);
1467 Result.setKind(tok::percentequal);
1468 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1469 } else if (Features.Digraphs && Char == '>') {
1470 Result.setKind(tok::r_brace); // '%>' -> '}'
1471 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1472 } else if (Features.Digraphs && Char == ':') {
1473 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1474 Char = getCharAndSize(CurPtr, SizeTmp);
1475 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
1476 Result.setKind(tok::hashhash); // '%:%:' -> '##'
1477 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1479 } else if (Char == '@' && Features.Microsoft) { // %:@ -> #@ -> Charize
1480 Result.setKind(tok::hashat);
1481 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1482 Diag(BufferPtr, diag::charize_microsoft_ext);
1484 Result.setKind(tok::hash); // '%:' -> '#'
1486 // We parsed a # character. If this occurs at the start of the line,
1487 // it's actually the start of a preprocessing directive. Callback to
1488 // the preprocessor to handle it.
1489 // FIXME: -fpreprocessed mode??
1490 if (Result.isAtStartOfLine() && !LexingRawMode) {
1492 PP->HandleDirective(Result);
1494 // As an optimization, if the preprocessor didn't switch lexers, tail
1496 if (PP->isCurrentLexer(this)) {
1497 // Start a new token. If this is a #include or something, the PP may
1498 // want us starting at the beginning of the line again. If so, set
1499 // the StartOfLine flag.
1500 if (IsAtStartOfLine) {
1501 Result.setFlag(Token::StartOfLine);
1502 IsAtStartOfLine = false;
1504 goto LexNextToken; // GCC isn't tail call eliminating.
1507 return PP->Lex(Result);
1511 Result.setKind(tok::percent);
1515 Char = getCharAndSize(CurPtr, SizeTmp);
1516 if (ParsingFilename) {
1517 return LexAngledStringLiteral(Result, CurPtr+SizeTmp);
1518 } else if (Char == '<' &&
1519 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '=') {
1520 Result.setKind(tok::lesslessequal);
1521 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1523 } else if (Char == '<') {
1524 Result.setKind(tok::lessless);
1525 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1526 } else if (Char == '=') {
1527 Result.setKind(tok::lessequal);
1528 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1529 } else if (Features.Digraphs && Char == ':') {
1530 Result.setKind(tok::l_square); // '<:' -> '['
1531 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1532 } else if (Features.Digraphs && Char == '%') {
1533 Result.setKind(tok::l_brace); // '<%' -> '{'
1534 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1536 Result.setKind(tok::less);
1540 Char = getCharAndSize(CurPtr, SizeTmp);
1542 Result.setKind(tok::greaterequal);
1543 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1544 } else if (Char == '>' &&
1545 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '=') {
1546 Result.setKind(tok::greatergreaterequal);
1547 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1549 } else if (Char == '>') {
1550 Result.setKind(tok::greatergreater);
1551 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1553 Result.setKind(tok::greater);
1557 Char = getCharAndSize(CurPtr, SizeTmp);
1559 Result.setKind(tok::caretequal);
1560 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1562 Result.setKind(tok::caret);
1566 Char = getCharAndSize(CurPtr, SizeTmp);
1568 Result.setKind(tok::pipeequal);
1569 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1570 } else if (Char == '|') {
1571 Result.setKind(tok::pipepipe);
1572 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1574 Result.setKind(tok::pipe);
1578 Char = getCharAndSize(CurPtr, SizeTmp);
1579 if (Features.Digraphs && Char == '>') {
1580 Result.setKind(tok::r_square); // ':>' -> ']'
1581 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1582 } else if (Features.CPlusPlus && Char == ':') {
1583 Result.setKind(tok::coloncolon);
1584 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1586 Result.setKind(tok::colon);
1590 Result.setKind(tok::semi);
1593 Char = getCharAndSize(CurPtr, SizeTmp);
1595 Result.setKind(tok::equalequal);
1596 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1598 Result.setKind(tok::equal);
1602 Result.setKind(tok::comma);
1605 Char = getCharAndSize(CurPtr, SizeTmp);
1607 Result.setKind(tok::hashhash);
1608 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1609 } else if (Char == '@' && Features.Microsoft) { // #@ -> Charize
1610 Result.setKind(tok::hashat);
1611 Diag(BufferPtr, diag::charize_microsoft_ext);
1612 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1614 Result.setKind(tok::hash);
1615 // We parsed a # character. If this occurs at the start of the line,
1616 // it's actually the start of a preprocessing directive. Callback to
1617 // the preprocessor to handle it.
1618 // FIXME: -fpreprocessed mode??
1619 if (Result.isAtStartOfLine() && !LexingRawMode) {
1621 PP->HandleDirective(Result);
1623 // As an optimization, if the preprocessor didn't switch lexers, tail
1625 if (PP->isCurrentLexer(this)) {
1626 // Start a new token. If this is a #include or something, the PP may
1627 // want us starting at the beginning of the line again. If so, set
1628 // the StartOfLine flag.
1629 if (IsAtStartOfLine) {
1630 Result.setFlag(Token::StartOfLine);
1631 IsAtStartOfLine = false;
1633 goto LexNextToken; // GCC isn't tail call eliminating.
1635 return PP->Lex(Result);
1641 // Objective C support.
1642 if (CurPtr[-1] == '@' && Features.ObjC1)
1643 Result.setKind(tok::at);
1645 Result.setKind(tok::unknown);
1652 Result.setKind(tok::unknown);
1656 // Notify MIOpt that we read a non-whitespace/non-comment token.
1659 // Update the location of token as well as BufferPtr.
1660 FormTokenWithChars(Result, CurPtr);