1 //===--- Lexer.cpp - C Language Family Lexer ------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // 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/Lex/LexDiagnostic.h" 30 #include "clang/Basic/SourceManager.h" 31 #include "llvm/Support/Compiler.h" 32 #include "llvm/Support/MemoryBuffer.h" 33 #include <cctype> 34 using namespace clang; 35 36 static void InitCharacterInfo(); 37 38 //===----------------------------------------------------------------------===// 39 // Token Class Implementation 40 //===----------------------------------------------------------------------===// 41 42 /// isObjCAtKeyword - Return true if we have an ObjC keyword identifier. 43 bool Token::isObjCAtKeyword(tok::ObjCKeywordKind objcKey) const { 44 if (IdentifierInfo *II = getIdentifierInfo()) 45 return II->getObjCKeywordID() == objcKey; 46 return false; 47 } 48 49 /// getObjCKeywordID - Return the ObjC keyword kind. 50 tok::ObjCKeywordKind Token::getObjCKeywordID() const { 51 IdentifierInfo *specId = getIdentifierInfo(); 52 return specId ? specId->getObjCKeywordID() : tok::objc_not_keyword; 53 } 54 55 56 //===----------------------------------------------------------------------===// 57 // Lexer Class Implementation 58 //===----------------------------------------------------------------------===// 59 60 void Lexer::InitLexer(const char *BufStart, const char *BufPtr, 61 const char *BufEnd) { 62 InitCharacterInfo(); 63 64 BufferStart = BufStart; 65 BufferPtr = BufPtr; 66 BufferEnd = BufEnd; 67 68 assert(BufEnd[0] == 0 && 69 "We assume that the input buffer has a null character at the end" 70 " to simplify lexing!"); 71 72 Is_PragmaLexer = false; 73 74 // Start of the file is a start of line. 75 IsAtStartOfLine = true; 76 77 // We are not after parsing a #. 78 ParsingPreprocessorDirective = false; 79 80 // We are not after parsing #include. 81 ParsingFilename = false; 82 83 // We are not in raw mode. Raw mode disables diagnostics and interpretation 84 // of tokens (e.g. identifiers, thus disabling macro expansion). It is used 85 // to quickly lex the tokens of the buffer, e.g. when handling a "#if 0" block 86 // or otherwise skipping over tokens. 87 LexingRawMode = false; 88 89 // Default to not keeping comments. 90 ExtendedTokenMode = 0; 91 } 92 93 /// Lexer constructor - Create a new lexer object for the specified buffer 94 /// with the specified preprocessor managing the lexing process. This lexer 95 /// assumes that the associated file buffer and Preprocessor objects will 96 /// outlive it, so it doesn't take ownership of either of them. 97 Lexer::Lexer(FileID FID, Preprocessor &PP) 98 : PreprocessorLexer(&PP, FID), 99 FileLoc(PP.getSourceManager().getLocForStartOfFile(FID)), 100 Features(PP.getLangOptions()) { 101 102 const llvm::MemoryBuffer *InputFile = PP.getSourceManager().getBuffer(FID); 103 104 InitLexer(InputFile->getBufferStart(), InputFile->getBufferStart(), 105 InputFile->getBufferEnd()); 106 107 // Default to keeping comments if the preprocessor wants them. 108 SetCommentRetentionState(PP.getCommentRetentionState()); 109 } 110 111 /// Lexer constructor - Create a new raw lexer object. This object is only 112 /// suitable for calls to 'LexRawToken'. This lexer assumes that the text 113 /// range will outlive it, so it doesn't take ownership of it. 114 Lexer::Lexer(SourceLocation fileloc, const LangOptions &features, 115 const char *BufStart, const char *BufPtr, const char *BufEnd) 116 : FileLoc(fileloc), Features(features) { 117 118 InitLexer(BufStart, BufPtr, BufEnd); 119 120 // We *are* in raw mode. 121 LexingRawMode = true; 122 } 123 124 /// Lexer constructor - Create a new raw lexer object. This object is only 125 /// suitable for calls to 'LexRawToken'. This lexer assumes that the text 126 /// range will outlive it, so it doesn't take ownership of it. 127 Lexer::Lexer(FileID FID, const SourceManager &SM, const LangOptions &features) 128 : FileLoc(SM.getLocForStartOfFile(FID)), Features(features) { 129 const llvm::MemoryBuffer *FromFile = SM.getBuffer(FID); 130 131 InitLexer(FromFile->getBufferStart(), FromFile->getBufferStart(), 132 FromFile->getBufferEnd()); 133 134 // We *are* in raw mode. 135 LexingRawMode = true; 136 } 137 138 /// Create_PragmaLexer: Lexer constructor - Create a new lexer object for 139 /// _Pragma expansion. This has a variety of magic semantics that this method 140 /// sets up. It returns a new'd Lexer that must be delete'd when done. 141 /// 142 /// On entrance to this routine, TokStartLoc is a macro location which has a 143 /// spelling loc that indicates the bytes to be lexed for the token and an 144 /// instantiation location that indicates where all lexed tokens should be 145 /// "expanded from". 146 /// 147 /// FIXME: It would really be nice to make _Pragma just be a wrapper around a 148 /// normal lexer that remaps tokens as they fly by. This would require making 149 /// Preprocessor::Lex virtual. Given that, we could just dump in a magic lexer 150 /// interface that could handle this stuff. This would pull GetMappedTokenLoc 151 /// out of the critical path of the lexer! 152 /// 153 Lexer *Lexer::Create_PragmaLexer(SourceLocation SpellingLoc, 154 SourceLocation InstantiationLocStart, 155 SourceLocation InstantiationLocEnd, 156 unsigned TokLen, Preprocessor &PP) { 157 SourceManager &SM = PP.getSourceManager(); 158 159 // Create the lexer as if we were going to lex the file normally. 160 FileID SpellingFID = SM.getFileID(SpellingLoc); 161 Lexer *L = new Lexer(SpellingFID, PP); 162 163 // Now that the lexer is created, change the start/end locations so that we 164 // just lex the subsection of the file that we want. This is lexing from a 165 // scratch buffer. 166 const char *StrData = SM.getCharacterData(SpellingLoc); 167 168 L->BufferPtr = StrData; 169 L->BufferEnd = StrData+TokLen; 170 assert(L->BufferEnd[0] == 0 && "Buffer is not nul terminated!"); 171 172 // Set the SourceLocation with the remapping information. This ensures that 173 // GetMappedTokenLoc will remap the tokens as they are lexed. 174 L->FileLoc = SM.createInstantiationLoc(SM.getLocForStartOfFile(SpellingFID), 175 InstantiationLocStart, 176 InstantiationLocEnd, TokLen); 177 178 // Ensure that the lexer thinks it is inside a directive, so that end \n will 179 // return an EOM token. 180 L->ParsingPreprocessorDirective = true; 181 182 // This lexer really is for _Pragma. 183 L->Is_PragmaLexer = true; 184 return L; 185 } 186 187 188 /// Stringify - Convert the specified string into a C string, with surrounding 189 /// ""'s, and with escaped \ and " characters. 190 std::string Lexer::Stringify(const std::string &Str, bool Charify) { 191 std::string Result = Str; 192 char Quote = Charify ? '\'' : '"'; 193 for (unsigned i = 0, e = Result.size(); i != e; ++i) { 194 if (Result[i] == '\\' || Result[i] == Quote) { 195 Result.insert(Result.begin()+i, '\\'); 196 ++i; ++e; 197 } 198 } 199 return Result; 200 } 201 202 /// Stringify - Convert the specified string into a C string by escaping '\' 203 /// and " characters. This does not add surrounding ""'s to the string. 204 void Lexer::Stringify(llvm::SmallVectorImpl<char> &Str) { 205 for (unsigned i = 0, e = Str.size(); i != e; ++i) { 206 if (Str[i] == '\\' || Str[i] == '"') { 207 Str.insert(Str.begin()+i, '\\'); 208 ++i; ++e; 209 } 210 } 211 } 212 213 214 /// MeasureTokenLength - Relex the token at the specified location and return 215 /// its length in bytes in the input file. If the token needs cleaning (e.g. 216 /// includes a trigraph or an escaped newline) then this count includes bytes 217 /// that are part of that. 218 unsigned Lexer::MeasureTokenLength(SourceLocation Loc, 219 const SourceManager &SM, 220 const LangOptions &LangOpts) { 221 // TODO: this could be special cased for common tokens like identifiers, ')', 222 // etc to make this faster, if it mattered. Just look at StrData[0] to handle 223 // all obviously single-char tokens. This could use 224 // Lexer::isObviouslySimpleCharacter for example to handle identifiers or 225 // something. 226 227 // If this comes from a macro expansion, we really do want the macro name, not 228 // the token this macro expanded to. 229 Loc = SM.getInstantiationLoc(Loc); 230 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc); 231 std::pair<const char *,const char *> Buffer = SM.getBufferData(LocInfo.first); 232 const char *StrData = Buffer.first+LocInfo.second; 233 234 // Create a lexer starting at the beginning of this token. 235 Lexer TheLexer(Loc, LangOpts, Buffer.first, StrData, Buffer.second); 236 Token TheTok; 237 TheLexer.LexFromRawLexer(TheTok); 238 return TheTok.getLength(); 239 } 240 241 //===----------------------------------------------------------------------===// 242 // Character information. 243 //===----------------------------------------------------------------------===// 244 245 enum { 246 CHAR_HORZ_WS = 0x01, // ' ', '\t', '\f', '\v'. Note, no '\0' 247 CHAR_VERT_WS = 0x02, // '\r', '\n' 248 CHAR_LETTER = 0x04, // a-z,A-Z 249 CHAR_NUMBER = 0x08, // 0-9 250 CHAR_UNDER = 0x10, // _ 251 CHAR_PERIOD = 0x20 // . 252 }; 253 254 // Statically initialize CharInfo table based on ASCII character set 255 // Reference: FreeBSD 7.2 /usr/share/misc/ascii 256 static const unsigned char CharInfo[256] = 257 { 258 // 0 NUL 1 SOH 2 STX 3 ETX 259 // 4 EOT 5 ENQ 6 ACK 7 BEL 260 0 , 0 , 0 , 0 , 261 0 , 0 , 0 , 0 , 262 // 8 BS 9 HT 10 NL 11 VT 263 //12 NP 13 CR 14 SO 15 SI 264 0 , CHAR_HORZ_WS, CHAR_VERT_WS, CHAR_HORZ_WS, 265 CHAR_HORZ_WS, CHAR_VERT_WS, 0 , 0 , 266 //16 DLE 17 DC1 18 DC2 19 DC3 267 //20 DC4 21 NAK 22 SYN 23 ETB 268 0 , 0 , 0 , 0 , 269 0 , 0 , 0 , 0 , 270 //24 CAN 25 EM 26 SUB 27 ESC 271 //28 FS 29 GS 30 RS 31 US 272 0 , 0 , 0 , 0 , 273 0 , 0 , 0 , 0 , 274 //32 SP 33 ! 34 " 35 # 275 //36 $ 37 % 38 & 39 ' 276 CHAR_HORZ_WS, 0 , 0 , 0 , 277 0 , 0 , 0 , 0 , 278 //40 ( 41 ) 42 * 43 + 279 //44 , 45 - 46 . 47 / 280 0 , 0 , 0 , 0 , 281 0 , 0 , CHAR_PERIOD , 0 , 282 //48 0 49 1 50 2 51 3 283 //52 4 53 5 54 6 55 7 284 CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER , 285 CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER , 286 //56 8 57 9 58 : 59 ; 287 //60 < 61 = 62 > 63 ? 288 CHAR_NUMBER , CHAR_NUMBER , 0 , 0 , 289 0 , 0 , 0 , 0 , 290 //64 @ 65 A 66 B 67 C 291 //68 D 69 E 70 F 71 G 292 0 , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , 293 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , 294 //72 H 73 I 74 J 75 K 295 //76 L 77 M 78 N 79 O 296 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , 297 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , 298 //80 P 81 Q 82 R 83 S 299 //84 T 85 U 86 V 87 W 300 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , 301 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , 302 //88 X 89 Y 90 Z 91 [ 303 //92 \ 93 ] 94 ^ 95 _ 304 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , 0 , 305 0 , 0 , 0 , CHAR_UNDER , 306 //96 ` 97 a 98 b 99 c 307 //100 d 101 e 102 f 103 g 308 0 , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , 309 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , 310 //104 h 105 i 106 j 107 k 311 //108 l 109 m 110 n 111 o 312 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , 313 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , 314 //112 p 113 q 114 r 115 s 315 //116 t 117 u 118 v 119 w 316 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , 317 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , 318 //120 x 121 y 122 z 123 { 319 //124 | 125 } 126 ~ 127 DEL 320 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , 0 , 321 0 , 0 , 0 , 0 322 }; 323 324 static void InitCharacterInfo() { 325 static bool isInited = false; 326 if (isInited) return; 327 // check the statically-initialized CharInfo table 328 assert(CHAR_HORZ_WS == CharInfo[(int)' ']); 329 assert(CHAR_HORZ_WS == CharInfo[(int)'\t']); 330 assert(CHAR_HORZ_WS == CharInfo[(int)'\f']); 331 assert(CHAR_HORZ_WS == CharInfo[(int)'\v']); 332 assert(CHAR_VERT_WS == CharInfo[(int)'\n']); 333 assert(CHAR_VERT_WS == CharInfo[(int)'\r']); 334 assert(CHAR_UNDER == CharInfo[(int)'_']); 335 assert(CHAR_PERIOD == CharInfo[(int)'.']); 336 for (unsigned i = 'a'; i <= 'z'; ++i) { 337 assert(CHAR_LETTER == CharInfo[i]); 338 assert(CHAR_LETTER == CharInfo[i+'A'-'a']); 339 } 340 for (unsigned i = '0'; i <= '9'; ++i) 341 assert(CHAR_NUMBER == CharInfo[i]); 342 isInited = true; 343 } 344 345 346 /// isIdentifierBody - Return true if this is the body character of an 347 /// identifier, which is [a-zA-Z0-9_]. 348 static inline bool isIdentifierBody(unsigned char c) { 349 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER)) ? true : false; 350 } 351 352 /// isHorizontalWhitespace - Return true if this character is horizontal 353 /// whitespace: ' ', '\t', '\f', '\v'. Note that this returns false for '\0'. 354 static inline bool isHorizontalWhitespace(unsigned char c) { 355 return (CharInfo[c] & CHAR_HORZ_WS) ? true : false; 356 } 357 358 /// isWhitespace - Return true if this character is horizontal or vertical 359 /// whitespace: ' ', '\t', '\f', '\v', '\n', '\r'. Note that this returns false 360 /// for '\0'. 361 static inline bool isWhitespace(unsigned char c) { 362 return (CharInfo[c] & (CHAR_HORZ_WS|CHAR_VERT_WS)) ? true : false; 363 } 364 365 /// isNumberBody - Return true if this is the body character of an 366 /// preprocessing number, which is [a-zA-Z0-9_.]. 367 static inline bool isNumberBody(unsigned char c) { 368 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER|CHAR_PERIOD)) ? 369 true : false; 370 } 371 372 373 //===----------------------------------------------------------------------===// 374 // Diagnostics forwarding code. 375 //===----------------------------------------------------------------------===// 376 377 /// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the 378 /// lexer buffer was all instantiated at a single point, perform the mapping. 379 /// This is currently only used for _Pragma implementation, so it is the slow 380 /// path of the hot getSourceLocation method. Do not allow it to be inlined. 381 static SourceLocation GetMappedTokenLoc(Preprocessor &PP, 382 SourceLocation FileLoc, 383 unsigned CharNo, 384 unsigned TokLen) DISABLE_INLINE; 385 static SourceLocation GetMappedTokenLoc(Preprocessor &PP, 386 SourceLocation FileLoc, 387 unsigned CharNo, unsigned TokLen) { 388 assert(FileLoc.isMacroID() && "Must be an instantiation"); 389 390 // Otherwise, we're lexing "mapped tokens". This is used for things like 391 // _Pragma handling. Combine the instantiation location of FileLoc with the 392 // spelling location. 393 SourceManager &SM = PP.getSourceManager(); 394 395 // Create a new SLoc which is expanded from Instantiation(FileLoc) but whose 396 // characters come from spelling(FileLoc)+Offset. 397 SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc); 398 SpellingLoc = SpellingLoc.getFileLocWithOffset(CharNo); 399 400 // Figure out the expansion loc range, which is the range covered by the 401 // original _Pragma(...) sequence. 402 std::pair<SourceLocation,SourceLocation> II = 403 SM.getImmediateInstantiationRange(FileLoc); 404 405 return SM.createInstantiationLoc(SpellingLoc, II.first, II.second, TokLen); 406 } 407 408 /// getSourceLocation - Return a source location identifier for the specified 409 /// offset in the current file. 410 SourceLocation Lexer::getSourceLocation(const char *Loc, 411 unsigned TokLen) const { 412 assert(Loc >= BufferStart && Loc <= BufferEnd && 413 "Location out of range for this buffer!"); 414 415 // In the normal case, we're just lexing from a simple file buffer, return 416 // the file id from FileLoc with the offset specified. 417 unsigned CharNo = Loc-BufferStart; 418 if (FileLoc.isFileID()) 419 return FileLoc.getFileLocWithOffset(CharNo); 420 421 // Otherwise, this is the _Pragma lexer case, which pretends that all of the 422 // tokens are lexed from where the _Pragma was defined. 423 assert(PP && "This doesn't work on raw lexers"); 424 return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen); 425 } 426 427 /// Diag - Forwarding function for diagnostics. This translate a source 428 /// position in the current buffer into a SourceLocation object for rendering. 429 DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const { 430 return PP->Diag(getSourceLocation(Loc), DiagID); 431 } 432 433 //===----------------------------------------------------------------------===// 434 // Trigraph and Escaped Newline Handling Code. 435 //===----------------------------------------------------------------------===// 436 437 /// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair, 438 /// return the decoded trigraph letter it corresponds to, or '\0' if nothing. 439 static char GetTrigraphCharForLetter(char Letter) { 440 switch (Letter) { 441 default: return 0; 442 case '=': return '#'; 443 case ')': return ']'; 444 case '(': return '['; 445 case '!': return '|'; 446 case '\'': return '^'; 447 case '>': return '}'; 448 case '/': return '\\'; 449 case '<': return '{'; 450 case '-': return '~'; 451 } 452 } 453 454 /// DecodeTrigraphChar - If the specified character is a legal trigraph when 455 /// prefixed with ??, emit a trigraph warning. If trigraphs are enabled, 456 /// return the result character. Finally, emit a warning about trigraph use 457 /// whether trigraphs are enabled or not. 458 static char DecodeTrigraphChar(const char *CP, Lexer *L) { 459 char Res = GetTrigraphCharForLetter(*CP); 460 if (!Res || !L) return Res; 461 462 if (!L->getFeatures().Trigraphs) { 463 if (!L->isLexingRawMode()) 464 L->Diag(CP-2, diag::trigraph_ignored); 465 return 0; 466 } 467 468 if (!L->isLexingRawMode()) 469 L->Diag(CP-2, diag::trigraph_converted) << std::string()+Res; 470 return Res; 471 } 472 473 /// getEscapedNewLineSize - Return the size of the specified escaped newline, 474 /// or 0 if it is not an escaped newline. P[-1] is known to be a "\" or a 475 /// trigraph equivalent on entry to this function. 476 unsigned Lexer::getEscapedNewLineSize(const char *Ptr) { 477 unsigned Size = 0; 478 while (isWhitespace(Ptr[Size])) { 479 ++Size; 480 481 if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r') 482 continue; 483 484 // If this is a \r\n or \n\r, skip the other half. 485 if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') && 486 Ptr[Size-1] != Ptr[Size]) 487 ++Size; 488 489 return Size; 490 } 491 492 // Not an escaped newline, must be a \t or something else. 493 return 0; 494 } 495 496 /// SkipEscapedNewLines - If P points to an escaped newline (or a series of 497 /// them), skip over them and return the first non-escaped-newline found, 498 /// otherwise return P. 499 const char *Lexer::SkipEscapedNewLines(const char *P) { 500 while (1) { 501 const char *AfterEscape; 502 if (*P == '\\') { 503 AfterEscape = P+1; 504 } else if (*P == '?') { 505 // If not a trigraph for escape, bail out. 506 if (P[1] != '?' || P[2] != '/') 507 return P; 508 AfterEscape = P+3; 509 } else { 510 return P; 511 } 512 513 unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape); 514 if (NewLineSize == 0) return P; 515 P = AfterEscape+NewLineSize; 516 } 517 } 518 519 520 /// getCharAndSizeSlow - Peek a single 'character' from the specified buffer, 521 /// get its size, and return it. This is tricky in several cases: 522 /// 1. If currently at the start of a trigraph, we warn about the trigraph, 523 /// then either return the trigraph (skipping 3 chars) or the '?', 524 /// depending on whether trigraphs are enabled or not. 525 /// 2. If this is an escaped newline (potentially with whitespace between 526 /// the backslash and newline), implicitly skip the newline and return 527 /// the char after it. 528 /// 3. If this is a UCN, return it. FIXME: C++ UCN's? 529 /// 530 /// This handles the slow/uncommon case of the getCharAndSize method. Here we 531 /// know that we can accumulate into Size, and that we have already incremented 532 /// Ptr by Size bytes. 533 /// 534 /// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should 535 /// be updated to match. 536 /// 537 char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size, 538 Token *Tok) { 539 // If we have a slash, look for an escaped newline. 540 if (Ptr[0] == '\\') { 541 ++Size; 542 ++Ptr; 543 Slash: 544 // Common case, backslash-char where the char is not whitespace. 545 if (!isWhitespace(Ptr[0])) return '\\'; 546 547 // See if we have optional whitespace characters between the slash and 548 // newline. 549 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) { 550 // Remember that this token needs to be cleaned. 551 if (Tok) Tok->setFlag(Token::NeedsCleaning); 552 553 // Warn if there was whitespace between the backslash and newline. 554 if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode()) 555 Diag(Ptr, diag::backslash_newline_space); 556 557 // Found backslash<whitespace><newline>. Parse the char after it. 558 Size += EscapedNewLineSize; 559 Ptr += EscapedNewLineSize; 560 // Use slow version to accumulate a correct size field. 561 return getCharAndSizeSlow(Ptr, Size, Tok); 562 } 563 564 // Otherwise, this is not an escaped newline, just return the slash. 565 return '\\'; 566 } 567 568 // If this is a trigraph, process it. 569 if (Ptr[0] == '?' && Ptr[1] == '?') { 570 // If this is actually a legal trigraph (not something like "??x"), emit 571 // a trigraph warning. If so, and if trigraphs are enabled, return it. 572 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : 0)) { 573 // Remember that this token needs to be cleaned. 574 if (Tok) Tok->setFlag(Token::NeedsCleaning); 575 576 Ptr += 3; 577 Size += 3; 578 if (C == '\\') goto Slash; 579 return C; 580 } 581 } 582 583 // If this is neither, return a single character. 584 ++Size; 585 return *Ptr; 586 } 587 588 589 /// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the 590 /// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size, 591 /// and that we have already incremented Ptr by Size bytes. 592 /// 593 /// NOTE: When this method is updated, getCharAndSizeSlow (above) should 594 /// be updated to match. 595 char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size, 596 const LangOptions &Features) { 597 // If we have a slash, look for an escaped newline. 598 if (Ptr[0] == '\\') { 599 ++Size; 600 ++Ptr; 601 Slash: 602 // Common case, backslash-char where the char is not whitespace. 603 if (!isWhitespace(Ptr[0])) return '\\'; 604 605 // See if we have optional whitespace characters followed by a newline. 606 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) { 607 // Found backslash<whitespace><newline>. Parse the char after it. 608 Size += EscapedNewLineSize; 609 Ptr += EscapedNewLineSize; 610 611 // Use slow version to accumulate a correct size field. 612 return getCharAndSizeSlowNoWarn(Ptr, Size, Features); 613 } 614 615 // Otherwise, this is not an escaped newline, just return the slash. 616 return '\\'; 617 } 618 619 // If this is a trigraph, process it. 620 if (Features.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') { 621 // If this is actually a legal trigraph (not something like "??x"), return 622 // it. 623 if (char C = GetTrigraphCharForLetter(Ptr[2])) { 624 Ptr += 3; 625 Size += 3; 626 if (C == '\\') goto Slash; 627 return C; 628 } 629 } 630 631 // If this is neither, return a single character. 632 ++Size; 633 return *Ptr; 634 } 635 636 //===----------------------------------------------------------------------===// 637 // Helper methods for lexing. 638 //===----------------------------------------------------------------------===// 639 640 void Lexer::LexIdentifier(Token &Result, const char *CurPtr) { 641 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$] 642 unsigned Size; 643 unsigned char C = *CurPtr++; 644 while (isIdentifierBody(C)) { 645 C = *CurPtr++; 646 } 647 --CurPtr; // Back up over the skipped character. 648 649 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline 650 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN. 651 // FIXME: UCNs. 652 if (C != '\\' && C != '?' && (C != '$' || !Features.DollarIdents)) { 653 FinishIdentifier: 654 const char *IdStart = BufferPtr; 655 FormTokenWithChars(Result, CurPtr, tok::identifier); 656 657 // If we are in raw mode, return this identifier raw. There is no need to 658 // look up identifier information or attempt to macro expand it. 659 if (LexingRawMode) return; 660 661 // Fill in Result.IdentifierInfo, looking up the identifier in the 662 // identifier table. 663 IdentifierInfo *II = PP->LookUpIdentifierInfo(Result, IdStart); 664 665 // Change the kind of this identifier to the appropriate token kind, e.g. 666 // turning "for" into a keyword. 667 Result.setKind(II->getTokenID()); 668 669 // Finally, now that we know we have an identifier, pass this off to the 670 // preprocessor, which may macro expand it or something. 671 if (II->isHandleIdentifierCase()) 672 PP->HandleIdentifier(Result); 673 return; 674 } 675 676 // Otherwise, $,\,? in identifier found. Enter slower path. 677 678 C = getCharAndSize(CurPtr, Size); 679 while (1) { 680 if (C == '$') { 681 // If we hit a $ and they are not supported in identifiers, we are done. 682 if (!Features.DollarIdents) goto FinishIdentifier; 683 684 // Otherwise, emit a diagnostic and continue. 685 if (!isLexingRawMode()) 686 Diag(CurPtr, diag::ext_dollar_in_identifier); 687 CurPtr = ConsumeChar(CurPtr, Size, Result); 688 C = getCharAndSize(CurPtr, Size); 689 continue; 690 } else if (!isIdentifierBody(C)) { // FIXME: UCNs. 691 // Found end of identifier. 692 goto FinishIdentifier; 693 } 694 695 // Otherwise, this character is good, consume it. 696 CurPtr = ConsumeChar(CurPtr, Size, Result); 697 698 C = getCharAndSize(CurPtr, Size); 699 while (isIdentifierBody(C)) { // FIXME: UCNs. 700 CurPtr = ConsumeChar(CurPtr, Size, Result); 701 C = getCharAndSize(CurPtr, Size); 702 } 703 } 704 } 705 706 707 /// LexNumericConstant - Lex the remainder of a integer or floating point 708 /// constant. From[-1] is the first character lexed. Return the end of the 709 /// constant. 710 void Lexer::LexNumericConstant(Token &Result, const char *CurPtr) { 711 unsigned Size; 712 char C = getCharAndSize(CurPtr, Size); 713 char PrevCh = 0; 714 while (isNumberBody(C)) { // FIXME: UCNs? 715 CurPtr = ConsumeChar(CurPtr, Size, Result); 716 PrevCh = C; 717 C = getCharAndSize(CurPtr, Size); 718 } 719 720 // If we fell out, check for a sign, due to 1e+12. If we have one, continue. 721 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) 722 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result)); 723 724 // If we have a hex FP constant, continue. 725 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p')) 726 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result)); 727 728 // Update the location of token as well as BufferPtr. 729 const char *TokStart = BufferPtr; 730 FormTokenWithChars(Result, CurPtr, tok::numeric_constant); 731 Result.setLiteralData(TokStart); 732 } 733 734 /// LexStringLiteral - Lex the remainder of a string literal, after having lexed 735 /// either " or L". 736 void Lexer::LexStringLiteral(Token &Result, const char *CurPtr, bool Wide) { 737 const char *NulCharacter = 0; // Does this string contain the \0 character? 738 739 char C = getAndAdvanceChar(CurPtr, Result); 740 while (C != '"') { 741 // Skip escaped characters. 742 if (C == '\\') { 743 // Skip the escaped character. 744 C = getAndAdvanceChar(CurPtr, Result); 745 } else if (C == '\n' || C == '\r' || // Newline. 746 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file. 747 if (!isLexingRawMode() && !Features.AsmPreprocessor) 748 Diag(BufferPtr, diag::err_unterminated_string); 749 FormTokenWithChars(Result, CurPtr-1, tok::unknown); 750 return; 751 } else if (C == 0) { 752 NulCharacter = CurPtr-1; 753 } 754 C = getAndAdvanceChar(CurPtr, Result); 755 } 756 757 // If a nul character existed in the string, warn about it. 758 if (NulCharacter && !isLexingRawMode()) 759 Diag(NulCharacter, diag::null_in_string); 760 761 // Update the location of the token as well as the BufferPtr instance var. 762 const char *TokStart = BufferPtr; 763 FormTokenWithChars(Result, CurPtr, 764 Wide ? tok::wide_string_literal : tok::string_literal); 765 Result.setLiteralData(TokStart); 766 } 767 768 /// LexAngledStringLiteral - Lex the remainder of an angled string literal, 769 /// after having lexed the '<' character. This is used for #include filenames. 770 void Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) { 771 const char *NulCharacter = 0; // Does this string contain the \0 character? 772 const char *AfterLessPos = CurPtr; 773 char C = getAndAdvanceChar(CurPtr, Result); 774 while (C != '>') { 775 // Skip escaped characters. 776 if (C == '\\') { 777 // Skip the escaped character. 778 C = getAndAdvanceChar(CurPtr, Result); 779 } else if (C == '\n' || C == '\r' || // Newline. 780 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file. 781 // If the filename is unterminated, then it must just be a lone < 782 // character. Return this as such. 783 FormTokenWithChars(Result, AfterLessPos, tok::less); 784 return; 785 } else if (C == 0) { 786 NulCharacter = CurPtr-1; 787 } 788 C = getAndAdvanceChar(CurPtr, Result); 789 } 790 791 // If a nul character existed in the string, warn about it. 792 if (NulCharacter && !isLexingRawMode()) 793 Diag(NulCharacter, diag::null_in_string); 794 795 // Update the location of token as well as BufferPtr. 796 const char *TokStart = BufferPtr; 797 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal); 798 Result.setLiteralData(TokStart); 799 } 800 801 802 /// LexCharConstant - Lex the remainder of a character constant, after having 803 /// lexed either ' or L'. 804 void Lexer::LexCharConstant(Token &Result, const char *CurPtr) { 805 const char *NulCharacter = 0; // Does this character contain the \0 character? 806 807 // Handle the common case of 'x' and '\y' efficiently. 808 char C = getAndAdvanceChar(CurPtr, Result); 809 if (C == '\'') { 810 if (!isLexingRawMode() && !Features.AsmPreprocessor) 811 Diag(BufferPtr, diag::err_empty_character); 812 FormTokenWithChars(Result, CurPtr, tok::unknown); 813 return; 814 } else if (C == '\\') { 815 // Skip the escaped character. 816 // FIXME: UCN's. 817 C = getAndAdvanceChar(CurPtr, Result); 818 } 819 820 if (C && C != '\n' && C != '\r' && CurPtr[0] == '\'') { 821 ++CurPtr; 822 } else { 823 // Fall back on generic code for embedded nulls, newlines, wide chars. 824 do { 825 // Skip escaped characters. 826 if (C == '\\') { 827 // Skip the escaped character. 828 C = getAndAdvanceChar(CurPtr, Result); 829 } else if (C == '\n' || C == '\r' || // Newline. 830 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file. 831 if (!isLexingRawMode() && !Features.AsmPreprocessor) 832 Diag(BufferPtr, diag::err_unterminated_char); 833 FormTokenWithChars(Result, CurPtr-1, tok::unknown); 834 return; 835 } else if (C == 0) { 836 NulCharacter = CurPtr-1; 837 } 838 C = getAndAdvanceChar(CurPtr, Result); 839 } while (C != '\''); 840 } 841 842 if (NulCharacter && !isLexingRawMode()) 843 Diag(NulCharacter, diag::null_in_char); 844 845 // Update the location of token as well as BufferPtr. 846 const char *TokStart = BufferPtr; 847 FormTokenWithChars(Result, CurPtr, tok::char_constant); 848 Result.setLiteralData(TokStart); 849 } 850 851 /// SkipWhitespace - Efficiently skip over a series of whitespace characters. 852 /// Update BufferPtr to point to the next non-whitespace character and return. 853 /// 854 /// This method forms a token and returns true if KeepWhitespaceMode is enabled. 855 /// 856 bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr) { 857 // Whitespace - Skip it, then return the token after the whitespace. 858 unsigned char Char = *CurPtr; // Skip consequtive spaces efficiently. 859 while (1) { 860 // Skip horizontal whitespace very aggressively. 861 while (isHorizontalWhitespace(Char)) 862 Char = *++CurPtr; 863 864 // Otherwise if we have something other than whitespace, we're done. 865 if (Char != '\n' && Char != '\r') 866 break; 867 868 if (ParsingPreprocessorDirective) { 869 // End of preprocessor directive line, let LexTokenInternal handle this. 870 BufferPtr = CurPtr; 871 return false; 872 } 873 874 // ok, but handle newline. 875 // The returned token is at the start of the line. 876 Result.setFlag(Token::StartOfLine); 877 // No leading whitespace seen so far. 878 Result.clearFlag(Token::LeadingSpace); 879 Char = *++CurPtr; 880 } 881 882 // If this isn't immediately after a newline, there is leading space. 883 char PrevChar = CurPtr[-1]; 884 if (PrevChar != '\n' && PrevChar != '\r') 885 Result.setFlag(Token::LeadingSpace); 886 887 // If the client wants us to return whitespace, return it now. 888 if (isKeepWhitespaceMode()) { 889 FormTokenWithChars(Result, CurPtr, tok::unknown); 890 return true; 891 } 892 893 BufferPtr = CurPtr; 894 return false; 895 } 896 897 // SkipBCPLComment - We have just read the // characters from input. Skip until 898 // we find the newline character thats terminate the comment. Then update 899 /// BufferPtr and return. If we're in KeepCommentMode, this will form the token 900 /// and return true. 901 bool Lexer::SkipBCPLComment(Token &Result, const char *CurPtr) { 902 // If BCPL comments aren't explicitly enabled for this language, emit an 903 // extension warning. 904 if (!Features.BCPLComment && !isLexingRawMode()) { 905 Diag(BufferPtr, diag::ext_bcpl_comment); 906 907 // Mark them enabled so we only emit one warning for this translation 908 // unit. 909 Features.BCPLComment = true; 910 } 911 912 // Scan over the body of the comment. The common case, when scanning, is that 913 // the comment contains normal ascii characters with nothing interesting in 914 // them. As such, optimize for this case with the inner loop. 915 char C; 916 do { 917 C = *CurPtr; 918 // FIXME: Speedup BCPL comment lexing. Just scan for a \n or \r character. 919 // If we find a \n character, scan backwards, checking to see if it's an 920 // escaped newline, like we do for block comments. 921 922 // Skip over characters in the fast loop. 923 while (C != 0 && // Potentially EOF. 924 C != '\\' && // Potentially escaped newline. 925 C != '?' && // Potentially trigraph. 926 C != '\n' && C != '\r') // Newline or DOS-style newline. 927 C = *++CurPtr; 928 929 // If this is a newline, we're done. 930 if (C == '\n' || C == '\r') 931 break; // Found the newline? Break out! 932 933 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to 934 // properly decode the character. Read it in raw mode to avoid emitting 935 // diagnostics about things like trigraphs. If we see an escaped newline, 936 // we'll handle it below. 937 const char *OldPtr = CurPtr; 938 bool OldRawMode = isLexingRawMode(); 939 LexingRawMode = true; 940 C = getAndAdvanceChar(CurPtr, Result); 941 LexingRawMode = OldRawMode; 942 943 // If the char that we finally got was a \n, then we must have had something 944 // like \<newline><newline>. We don't want to have consumed the second 945 // newline, we want CurPtr, to end up pointing to it down below. 946 if (C == '\n' || C == '\r') { 947 --CurPtr; 948 C = 'x'; // doesn't matter what this is. 949 } 950 951 // If we read multiple characters, and one of those characters was a \r or 952 // \n, then we had an escaped newline within the comment. Emit diagnostic 953 // unless the next line is also a // comment. 954 if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') { 955 for (; OldPtr != CurPtr; ++OldPtr) 956 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') { 957 // Okay, we found a // comment that ends in a newline, if the next 958 // line is also a // comment, but has spaces, don't emit a diagnostic. 959 if (isspace(C)) { 960 const char *ForwardPtr = CurPtr; 961 while (isspace(*ForwardPtr)) // Skip whitespace. 962 ++ForwardPtr; 963 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/') 964 break; 965 } 966 967 if (!isLexingRawMode()) 968 Diag(OldPtr-1, diag::ext_multi_line_bcpl_comment); 969 break; 970 } 971 } 972 973 if (CurPtr == BufferEnd+1) { --CurPtr; break; } 974 } while (C != '\n' && C != '\r'); 975 976 // Found but did not consume the newline. 977 if (PP) 978 PP->HandleComment(SourceRange(getSourceLocation(BufferPtr), 979 getSourceLocation(CurPtr))); 980 981 // If we are returning comments as tokens, return this comment as a token. 982 if (inKeepCommentMode()) 983 return SaveBCPLComment(Result, CurPtr); 984 985 // If we are inside a preprocessor directive and we see the end of line, 986 // return immediately, so that the lexer can return this as an EOM token. 987 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) { 988 BufferPtr = CurPtr; 989 return false; 990 } 991 992 // Otherwise, eat the \n character. We don't care if this is a \n\r or 993 // \r\n sequence. This is an efficiency hack (because we know the \n can't 994 // contribute to another token), it isn't needed for correctness. Note that 995 // this is ok even in KeepWhitespaceMode, because we would have returned the 996 /// comment above in that mode. 997 ++CurPtr; 998 999 // The next returned token is at the start of the line. 1000 Result.setFlag(Token::StartOfLine); 1001 // No leading whitespace seen so far. 1002 Result.clearFlag(Token::LeadingSpace); 1003 BufferPtr = CurPtr; 1004 return false; 1005 } 1006 1007 /// SaveBCPLComment - If in save-comment mode, package up this BCPL comment in 1008 /// an appropriate way and return it. 1009 bool Lexer::SaveBCPLComment(Token &Result, const char *CurPtr) { 1010 // If we're not in a preprocessor directive, just return the // comment 1011 // directly. 1012 FormTokenWithChars(Result, CurPtr, tok::comment); 1013 1014 if (!ParsingPreprocessorDirective) 1015 return true; 1016 1017 // If this BCPL-style comment is in a macro definition, transmogrify it into 1018 // a C-style block comment. 1019 std::string Spelling = PP->getSpelling(Result); 1020 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not bcpl comment?"); 1021 Spelling[1] = '*'; // Change prefix to "/*". 1022 Spelling += "*/"; // add suffix. 1023 1024 Result.setKind(tok::comment); 1025 PP->CreateString(&Spelling[0], Spelling.size(), Result, 1026 Result.getLocation()); 1027 return true; 1028 } 1029 1030 /// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline 1031 /// character (either \n or \r) is part of an escaped newline sequence. Issue a 1032 /// diagnostic if so. We know that the newline is inside of a block comment. 1033 static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr, 1034 Lexer *L) { 1035 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r'); 1036 1037 // Back up off the newline. 1038 --CurPtr; 1039 1040 // If this is a two-character newline sequence, skip the other character. 1041 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') { 1042 // \n\n or \r\r -> not escaped newline. 1043 if (CurPtr[0] == CurPtr[1]) 1044 return false; 1045 // \n\r or \r\n -> skip the newline. 1046 --CurPtr; 1047 } 1048 1049 // If we have horizontal whitespace, skip over it. We allow whitespace 1050 // between the slash and newline. 1051 bool HasSpace = false; 1052 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) { 1053 --CurPtr; 1054 HasSpace = true; 1055 } 1056 1057 // If we have a slash, we know this is an escaped newline. 1058 if (*CurPtr == '\\') { 1059 if (CurPtr[-1] != '*') return false; 1060 } else { 1061 // It isn't a slash, is it the ?? / trigraph? 1062 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' || 1063 CurPtr[-3] != '*') 1064 return false; 1065 1066 // This is the trigraph ending the comment. Emit a stern warning! 1067 CurPtr -= 2; 1068 1069 // If no trigraphs are enabled, warn that we ignored this trigraph and 1070 // ignore this * character. 1071 if (!L->getFeatures().Trigraphs) { 1072 if (!L->isLexingRawMode()) 1073 L->Diag(CurPtr, diag::trigraph_ignored_block_comment); 1074 return false; 1075 } 1076 if (!L->isLexingRawMode()) 1077 L->Diag(CurPtr, diag::trigraph_ends_block_comment); 1078 } 1079 1080 // Warn about having an escaped newline between the */ characters. 1081 if (!L->isLexingRawMode()) 1082 L->Diag(CurPtr, diag::escaped_newline_block_comment_end); 1083 1084 // If there was space between the backslash and newline, warn about it. 1085 if (HasSpace && !L->isLexingRawMode()) 1086 L->Diag(CurPtr, diag::backslash_newline_space); 1087 1088 return true; 1089 } 1090 1091 #ifdef __SSE2__ 1092 #include <emmintrin.h> 1093 #elif __ALTIVEC__ 1094 #include <altivec.h> 1095 #undef bool 1096 #endif 1097 1098 /// SkipBlockComment - We have just read the /* characters from input. Read 1099 /// until we find the */ characters that terminate the comment. Note that we 1100 /// don't bother decoding trigraphs or escaped newlines in block comments, 1101 /// because they cannot cause the comment to end. The only thing that can 1102 /// happen is the comment could end with an escaped newline between the */ end 1103 /// of comment. 1104 /// 1105 /// If KeepCommentMode is enabled, this forms a token from the comment and 1106 /// returns true. 1107 bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr) { 1108 // Scan one character past where we should, looking for a '/' character. Once 1109 // we find it, check to see if it was preceeded by a *. This common 1110 // optimization helps people who like to put a lot of * characters in their 1111 // comments. 1112 1113 // The first character we get with newlines and trigraphs skipped to handle 1114 // the degenerate /*/ case below correctly if the * has an escaped newline 1115 // after it. 1116 unsigned CharSize; 1117 unsigned char C = getCharAndSize(CurPtr, CharSize); 1118 CurPtr += CharSize; 1119 if (C == 0 && CurPtr == BufferEnd+1) { 1120 if (!isLexingRawMode()) 1121 Diag(BufferPtr, diag::err_unterminated_block_comment); 1122 --CurPtr; 1123 1124 // KeepWhitespaceMode should return this broken comment as a token. Since 1125 // it isn't a well formed comment, just return it as an 'unknown' token. 1126 if (isKeepWhitespaceMode()) { 1127 FormTokenWithChars(Result, CurPtr, tok::unknown); 1128 return true; 1129 } 1130 1131 BufferPtr = CurPtr; 1132 return false; 1133 } 1134 1135 // Check to see if the first character after the '/*' is another /. If so, 1136 // then this slash does not end the block comment, it is part of it. 1137 if (C == '/') 1138 C = *CurPtr++; 1139 1140 while (1) { 1141 // Skip over all non-interesting characters until we find end of buffer or a 1142 // (probably ending) '/' character. 1143 if (CurPtr + 24 < BufferEnd) { 1144 // While not aligned to a 16-byte boundary. 1145 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0) 1146 C = *CurPtr++; 1147 1148 if (C == '/') goto FoundSlash; 1149 1150 #ifdef __SSE2__ 1151 __m128i Slashes = _mm_set_epi8('/', '/', '/', '/', '/', '/', '/', '/', 1152 '/', '/', '/', '/', '/', '/', '/', '/'); 1153 while (CurPtr+16 <= BufferEnd && 1154 _mm_movemask_epi8(_mm_cmpeq_epi8(*(__m128i*)CurPtr, Slashes)) == 0) 1155 CurPtr += 16; 1156 #elif __ALTIVEC__ 1157 __vector unsigned char Slashes = { 1158 '/', '/', '/', '/', '/', '/', '/', '/', 1159 '/', '/', '/', '/', '/', '/', '/', '/' 1160 }; 1161 while (CurPtr+16 <= BufferEnd && 1162 !vec_any_eq(*(vector unsigned char*)CurPtr, Slashes)) 1163 CurPtr += 16; 1164 #else 1165 // Scan for '/' quickly. Many block comments are very large. 1166 while (CurPtr[0] != '/' && 1167 CurPtr[1] != '/' && 1168 CurPtr[2] != '/' && 1169 CurPtr[3] != '/' && 1170 CurPtr+4 < BufferEnd) { 1171 CurPtr += 4; 1172 } 1173 #endif 1174 1175 // It has to be one of the bytes scanned, increment to it and read one. 1176 C = *CurPtr++; 1177 } 1178 1179 // Loop to scan the remainder. 1180 while (C != '/' && C != '\0') 1181 C = *CurPtr++; 1182 1183 FoundSlash: 1184 if (C == '/') { 1185 if (CurPtr[-2] == '*') // We found the final */. We're done! 1186 break; 1187 1188 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) { 1189 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) { 1190 // We found the final */, though it had an escaped newline between the 1191 // * and /. We're done! 1192 break; 1193 } 1194 } 1195 if (CurPtr[0] == '*' && CurPtr[1] != '/') { 1196 // If this is a /* inside of the comment, emit a warning. Don't do this 1197 // if this is a /*/, which will end the comment. This misses cases with 1198 // embedded escaped newlines, but oh well. 1199 if (!isLexingRawMode()) 1200 Diag(CurPtr-1, diag::warn_nested_block_comment); 1201 } 1202 } else if (C == 0 && CurPtr == BufferEnd+1) { 1203 if (!isLexingRawMode()) 1204 Diag(BufferPtr, diag::err_unterminated_block_comment); 1205 // Note: the user probably forgot a */. We could continue immediately 1206 // after the /*, but this would involve lexing a lot of what really is the 1207 // comment, which surely would confuse the parser. 1208 --CurPtr; 1209 1210 // KeepWhitespaceMode should return this broken comment as a token. Since 1211 // it isn't a well formed comment, just return it as an 'unknown' token. 1212 if (isKeepWhitespaceMode()) { 1213 FormTokenWithChars(Result, CurPtr, tok::unknown); 1214 return true; 1215 } 1216 1217 BufferPtr = CurPtr; 1218 return false; 1219 } 1220 C = *CurPtr++; 1221 } 1222 1223 if (PP) 1224 PP->HandleComment(SourceRange(getSourceLocation(BufferPtr), 1225 getSourceLocation(CurPtr))); 1226 1227 // If we are returning comments as tokens, return this comment as a token. 1228 if (inKeepCommentMode()) { 1229 FormTokenWithChars(Result, CurPtr, tok::comment); 1230 return true; 1231 } 1232 1233 // It is common for the tokens immediately after a /**/ comment to be 1234 // whitespace. Instead of going through the big switch, handle it 1235 // efficiently now. This is safe even in KeepWhitespaceMode because we would 1236 // have already returned above with the comment as a token. 1237 if (isHorizontalWhitespace(*CurPtr)) { 1238 Result.setFlag(Token::LeadingSpace); 1239 SkipWhitespace(Result, CurPtr+1); 1240 return false; 1241 } 1242 1243 // Otherwise, just return so that the next character will be lexed as a token. 1244 BufferPtr = CurPtr; 1245 Result.setFlag(Token::LeadingSpace); 1246 return false; 1247 } 1248 1249 //===----------------------------------------------------------------------===// 1250 // Primary Lexing Entry Points 1251 //===----------------------------------------------------------------------===// 1252 1253 /// ReadToEndOfLine - Read the rest of the current preprocessor line as an 1254 /// uninterpreted string. This switches the lexer out of directive mode. 1255 std::string Lexer::ReadToEndOfLine() { 1256 assert(ParsingPreprocessorDirective && ParsingFilename == false && 1257 "Must be in a preprocessing directive!"); 1258 std::string Result; 1259 Token Tmp; 1260 1261 // CurPtr - Cache BufferPtr in an automatic variable. 1262 const char *CurPtr = BufferPtr; 1263 while (1) { 1264 char Char = getAndAdvanceChar(CurPtr, Tmp); 1265 switch (Char) { 1266 default: 1267 Result += Char; 1268 break; 1269 case 0: // Null. 1270 // Found end of file? 1271 if (CurPtr-1 != BufferEnd) { 1272 // Nope, normal character, continue. 1273 Result += Char; 1274 break; 1275 } 1276 // FALL THROUGH. 1277 case '\r': 1278 case '\n': 1279 // Okay, we found the end of the line. First, back up past the \0, \r, \n. 1280 assert(CurPtr[-1] == Char && "Trigraphs for newline?"); 1281 BufferPtr = CurPtr-1; 1282 1283 // Next, lex the character, which should handle the EOM transition. 1284 Lex(Tmp); 1285 assert(Tmp.is(tok::eom) && "Unexpected token!"); 1286 1287 // Finally, we're done, return the string we found. 1288 return Result; 1289 } 1290 } 1291 } 1292 1293 /// LexEndOfFile - CurPtr points to the end of this file. Handle this 1294 /// condition, reporting diagnostics and handling other edge cases as required. 1295 /// This returns true if Result contains a token, false if PP.Lex should be 1296 /// called again. 1297 bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) { 1298 // If we hit the end of the file while parsing a preprocessor directive, 1299 // end the preprocessor directive first. The next token returned will 1300 // then be the end of file. 1301 if (ParsingPreprocessorDirective) { 1302 // Done parsing the "line". 1303 ParsingPreprocessorDirective = false; 1304 // Update the location of token as well as BufferPtr. 1305 FormTokenWithChars(Result, CurPtr, tok::eom); 1306 1307 // Restore comment saving mode, in case it was disabled for directive. 1308 SetCommentRetentionState(PP->getCommentRetentionState()); 1309 return true; // Have a token. 1310 } 1311 1312 // If we are in raw mode, return this event as an EOF token. Let the caller 1313 // that put us in raw mode handle the event. 1314 if (isLexingRawMode()) { 1315 Result.startToken(); 1316 BufferPtr = BufferEnd; 1317 FormTokenWithChars(Result, BufferEnd, tok::eof); 1318 return true; 1319 } 1320 1321 // Otherwise, issue diagnostics for unterminated #if and missing newline. 1322 1323 // If we are in a #if directive, emit an error. 1324 while (!ConditionalStack.empty()) { 1325 PP->Diag(ConditionalStack.back().IfLoc, 1326 diag::err_pp_unterminated_conditional); 1327 ConditionalStack.pop_back(); 1328 } 1329 1330 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue 1331 // a pedwarn. 1332 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r')) 1333 Diag(BufferEnd, diag::ext_no_newline_eof) 1334 << CodeModificationHint::CreateInsertion(getSourceLocation(BufferEnd), 1335 "\n"); 1336 1337 BufferPtr = CurPtr; 1338 1339 // Finally, let the preprocessor handle this. 1340 return PP->HandleEndOfFile(Result); 1341 } 1342 1343 /// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from 1344 /// the specified lexer will return a tok::l_paren token, 0 if it is something 1345 /// else and 2 if there are no more tokens in the buffer controlled by the 1346 /// lexer. 1347 unsigned Lexer::isNextPPTokenLParen() { 1348 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?"); 1349 1350 // Switch to 'skipping' mode. This will ensure that we can lex a token 1351 // without emitting diagnostics, disables macro expansion, and will cause EOF 1352 // to return an EOF token instead of popping the include stack. 1353 LexingRawMode = true; 1354 1355 // Save state that can be changed while lexing so that we can restore it. 1356 const char *TmpBufferPtr = BufferPtr; 1357 bool inPPDirectiveMode = ParsingPreprocessorDirective; 1358 1359 Token Tok; 1360 Tok.startToken(); 1361 LexTokenInternal(Tok); 1362 1363 // Restore state that may have changed. 1364 BufferPtr = TmpBufferPtr; 1365 ParsingPreprocessorDirective = inPPDirectiveMode; 1366 1367 // Restore the lexer back to non-skipping mode. 1368 LexingRawMode = false; 1369 1370 if (Tok.is(tok::eof)) 1371 return 2; 1372 return Tok.is(tok::l_paren); 1373 } 1374 1375 1376 /// LexTokenInternal - This implements a simple C family lexer. It is an 1377 /// extremely performance critical piece of code. This assumes that the buffer 1378 /// has a null character at the end of the file. This returns a preprocessing 1379 /// token, not a normal token, as such, it is an internal interface. It assumes 1380 /// that the Flags of result have been cleared before calling this. 1381 void Lexer::LexTokenInternal(Token &Result) { 1382 LexNextToken: 1383 // New token, can't need cleaning yet. 1384 Result.clearFlag(Token::NeedsCleaning); 1385 Result.setIdentifierInfo(0); 1386 1387 // CurPtr - Cache BufferPtr in an automatic variable. 1388 const char *CurPtr = BufferPtr; 1389 1390 // Small amounts of horizontal whitespace is very common between tokens. 1391 if ((*CurPtr == ' ') || (*CurPtr == '\t')) { 1392 ++CurPtr; 1393 while ((*CurPtr == ' ') || (*CurPtr == '\t')) 1394 ++CurPtr; 1395 1396 // If we are keeping whitespace and other tokens, just return what we just 1397 // skipped. The next lexer invocation will return the token after the 1398 // whitespace. 1399 if (isKeepWhitespaceMode()) { 1400 FormTokenWithChars(Result, CurPtr, tok::unknown); 1401 return; 1402 } 1403 1404 BufferPtr = CurPtr; 1405 Result.setFlag(Token::LeadingSpace); 1406 } 1407 1408 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below. 1409 1410 // Read a character, advancing over it. 1411 char Char = getAndAdvanceChar(CurPtr, Result); 1412 tok::TokenKind Kind; 1413 1414 switch (Char) { 1415 case 0: // Null. 1416 // Found end of file? 1417 if (CurPtr-1 == BufferEnd) { 1418 // Read the PP instance variable into an automatic variable, because 1419 // LexEndOfFile will often delete 'this'. 1420 Preprocessor *PPCache = PP; 1421 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file. 1422 return; // Got a token to return. 1423 assert(PPCache && "Raw buffer::LexEndOfFile should return a token"); 1424 return PPCache->Lex(Result); 1425 } 1426 1427 if (!isLexingRawMode()) 1428 Diag(CurPtr-1, diag::null_in_file); 1429 Result.setFlag(Token::LeadingSpace); 1430 if (SkipWhitespace(Result, CurPtr)) 1431 return; // KeepWhitespaceMode 1432 1433 goto LexNextToken; // GCC isn't tail call eliminating. 1434 case '\n': 1435 case '\r': 1436 // If we are inside a preprocessor directive and we see the end of line, 1437 // we know we are done with the directive, so return an EOM token. 1438 if (ParsingPreprocessorDirective) { 1439 // Done parsing the "line". 1440 ParsingPreprocessorDirective = false; 1441 1442 // Restore comment saving mode, in case it was disabled for directive. 1443 SetCommentRetentionState(PP->getCommentRetentionState()); 1444 1445 // Since we consumed a newline, we are back at the start of a line. 1446 IsAtStartOfLine = true; 1447 1448 Kind = tok::eom; 1449 break; 1450 } 1451 // The returned token is at the start of the line. 1452 Result.setFlag(Token::StartOfLine); 1453 // No leading whitespace seen so far. 1454 Result.clearFlag(Token::LeadingSpace); 1455 1456 if (SkipWhitespace(Result, CurPtr)) 1457 return; // KeepWhitespaceMode 1458 goto LexNextToken; // GCC isn't tail call eliminating. 1459 case ' ': 1460 case '\t': 1461 case '\f': 1462 case '\v': 1463 SkipHorizontalWhitespace: 1464 Result.setFlag(Token::LeadingSpace); 1465 if (SkipWhitespace(Result, CurPtr)) 1466 return; // KeepWhitespaceMode 1467 1468 SkipIgnoredUnits: 1469 CurPtr = BufferPtr; 1470 1471 // If the next token is obviously a // or /* */ comment, skip it efficiently 1472 // too (without going through the big switch stmt). 1473 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() && 1474 Features.BCPLComment) { 1475 SkipBCPLComment(Result, CurPtr+2); 1476 goto SkipIgnoredUnits; 1477 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) { 1478 SkipBlockComment(Result, CurPtr+2); 1479 goto SkipIgnoredUnits; 1480 } else if (isHorizontalWhitespace(*CurPtr)) { 1481 goto SkipHorizontalWhitespace; 1482 } 1483 goto LexNextToken; // GCC isn't tail call eliminating. 1484 1485 // C99 6.4.4.1: Integer Constants. 1486 // C99 6.4.4.2: Floating Constants. 1487 case '0': case '1': case '2': case '3': case '4': 1488 case '5': case '6': case '7': case '8': case '9': 1489 // Notify MIOpt that we read a non-whitespace/non-comment token. 1490 MIOpt.ReadToken(); 1491 return LexNumericConstant(Result, CurPtr); 1492 1493 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz"). 1494 // Notify MIOpt that we read a non-whitespace/non-comment token. 1495 MIOpt.ReadToken(); 1496 Char = getCharAndSize(CurPtr, SizeTmp); 1497 1498 // Wide string literal. 1499 if (Char == '"') 1500 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result), 1501 true); 1502 1503 // Wide character constant. 1504 if (Char == '\'') 1505 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result)); 1506 // FALL THROUGH, treating L like the start of an identifier. 1507 1508 // C99 6.4.2: Identifiers. 1509 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': 1510 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N': 1511 case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': 1512 case 'V': case 'W': case 'X': case 'Y': case 'Z': 1513 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': 1514 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': 1515 case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': 1516 case 'v': case 'w': case 'x': case 'y': case 'z': 1517 case '_': 1518 // Notify MIOpt that we read a non-whitespace/non-comment token. 1519 MIOpt.ReadToken(); 1520 return LexIdentifier(Result, CurPtr); 1521 1522 case '$': // $ in identifiers. 1523 if (Features.DollarIdents) { 1524 if (!isLexingRawMode()) 1525 Diag(CurPtr-1, diag::ext_dollar_in_identifier); 1526 // Notify MIOpt that we read a non-whitespace/non-comment token. 1527 MIOpt.ReadToken(); 1528 return LexIdentifier(Result, CurPtr); 1529 } 1530 1531 Kind = tok::unknown; 1532 break; 1533 1534 // C99 6.4.4: Character Constants. 1535 case '\'': 1536 // Notify MIOpt that we read a non-whitespace/non-comment token. 1537 MIOpt.ReadToken(); 1538 return LexCharConstant(Result, CurPtr); 1539 1540 // C99 6.4.5: String Literals. 1541 case '"': 1542 // Notify MIOpt that we read a non-whitespace/non-comment token. 1543 MIOpt.ReadToken(); 1544 return LexStringLiteral(Result, CurPtr, false); 1545 1546 // C99 6.4.6: Punctuators. 1547 case '?': 1548 Kind = tok::question; 1549 break; 1550 case '[': 1551 Kind = tok::l_square; 1552 break; 1553 case ']': 1554 Kind = tok::r_square; 1555 break; 1556 case '(': 1557 Kind = tok::l_paren; 1558 break; 1559 case ')': 1560 Kind = tok::r_paren; 1561 break; 1562 case '{': 1563 Kind = tok::l_brace; 1564 break; 1565 case '}': 1566 Kind = tok::r_brace; 1567 break; 1568 case '.': 1569 Char = getCharAndSize(CurPtr, SizeTmp); 1570 if (Char >= '0' && Char <= '9') { 1571 // Notify MIOpt that we read a non-whitespace/non-comment token. 1572 MIOpt.ReadToken(); 1573 1574 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result)); 1575 } else if (Features.CPlusPlus && Char == '*') { 1576 Kind = tok::periodstar; 1577 CurPtr += SizeTmp; 1578 } else if (Char == '.' && 1579 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') { 1580 Kind = tok::ellipsis; 1581 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result), 1582 SizeTmp2, Result); 1583 } else { 1584 Kind = tok::period; 1585 } 1586 break; 1587 case '&': 1588 Char = getCharAndSize(CurPtr, SizeTmp); 1589 if (Char == '&') { 1590 Kind = tok::ampamp; 1591 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 1592 } else if (Char == '=') { 1593 Kind = tok::ampequal; 1594 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 1595 } else { 1596 Kind = tok::amp; 1597 } 1598 break; 1599 case '*': 1600 if (getCharAndSize(CurPtr, SizeTmp) == '=') { 1601 Kind = tok::starequal; 1602 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 1603 } else { 1604 Kind = tok::star; 1605 } 1606 break; 1607 case '+': 1608 Char = getCharAndSize(CurPtr, SizeTmp); 1609 if (Char == '+') { 1610 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 1611 Kind = tok::plusplus; 1612 } else if (Char == '=') { 1613 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 1614 Kind = tok::plusequal; 1615 } else { 1616 Kind = tok::plus; 1617 } 1618 break; 1619 case '-': 1620 Char = getCharAndSize(CurPtr, SizeTmp); 1621 if (Char == '-') { // -- 1622 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 1623 Kind = tok::minusminus; 1624 } else if (Char == '>' && Features.CPlusPlus && 1625 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->* 1626 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result), 1627 SizeTmp2, Result); 1628 Kind = tok::arrowstar; 1629 } else if (Char == '>') { // -> 1630 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 1631 Kind = tok::arrow; 1632 } else if (Char == '=') { // -= 1633 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 1634 Kind = tok::minusequal; 1635 } else { 1636 Kind = tok::minus; 1637 } 1638 break; 1639 case '~': 1640 Kind = tok::tilde; 1641 break; 1642 case '!': 1643 if (getCharAndSize(CurPtr, SizeTmp) == '=') { 1644 Kind = tok::exclaimequal; 1645 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 1646 } else { 1647 Kind = tok::exclaim; 1648 } 1649 break; 1650 case '/': 1651 // 6.4.9: Comments 1652 Char = getCharAndSize(CurPtr, SizeTmp); 1653 if (Char == '/') { // BCPL comment. 1654 // Even if BCPL comments are disabled (e.g. in C89 mode), we generally 1655 // want to lex this as a comment. There is one problem with this though, 1656 // that in one particular corner case, this can change the behavior of the 1657 // resultant program. For example, In "foo //**/ bar", C89 would lex 1658 // this as "foo / bar" and langauges with BCPL comments would lex it as 1659 // "foo". Check to see if the character after the second slash is a '*'. 1660 // If so, we will lex that as a "/" instead of the start of a comment. 1661 if (Features.BCPLComment || 1662 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*') { 1663 if (SkipBCPLComment(Result, ConsumeChar(CurPtr, SizeTmp, Result))) 1664 return; // KeepCommentMode 1665 1666 // It is common for the tokens immediately after a // comment to be 1667 // whitespace (indentation for the next line). Instead of going through 1668 // the big switch, handle it efficiently now. 1669 goto SkipIgnoredUnits; 1670 } 1671 } 1672 1673 if (Char == '*') { // /**/ comment. 1674 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result))) 1675 return; // KeepCommentMode 1676 goto LexNextToken; // GCC isn't tail call eliminating. 1677 } 1678 1679 if (Char == '=') { 1680 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 1681 Kind = tok::slashequal; 1682 } else { 1683 Kind = tok::slash; 1684 } 1685 break; 1686 case '%': 1687 Char = getCharAndSize(CurPtr, SizeTmp); 1688 if (Char == '=') { 1689 Kind = tok::percentequal; 1690 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 1691 } else if (Features.Digraphs && Char == '>') { 1692 Kind = tok::r_brace; // '%>' -> '}' 1693 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 1694 } else if (Features.Digraphs && Char == ':') { 1695 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 1696 Char = getCharAndSize(CurPtr, SizeTmp); 1697 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') { 1698 Kind = tok::hashhash; // '%:%:' -> '##' 1699 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result), 1700 SizeTmp2, Result); 1701 } else if (Char == '@' && Features.Microsoft) { // %:@ -> #@ -> Charize 1702 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 1703 if (!isLexingRawMode()) 1704 Diag(BufferPtr, diag::charize_microsoft_ext); 1705 Kind = tok::hashat; 1706 } else { // '%:' -> '#' 1707 // We parsed a # character. If this occurs at the start of the line, 1708 // it's actually the start of a preprocessing directive. Callback to 1709 // the preprocessor to handle it. 1710 // FIXME: -fpreprocessed mode?? 1711 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer) { 1712 FormTokenWithChars(Result, CurPtr, tok::hash); 1713 PP->HandleDirective(Result); 1714 1715 // As an optimization, if the preprocessor didn't switch lexers, tail 1716 // recurse. 1717 if (PP->isCurrentLexer(this)) { 1718 // Start a new token. If this is a #include or something, the PP may 1719 // want us starting at the beginning of the line again. If so, set 1720 // the StartOfLine flag. 1721 if (IsAtStartOfLine) { 1722 Result.setFlag(Token::StartOfLine); 1723 IsAtStartOfLine = false; 1724 } 1725 goto LexNextToken; // GCC isn't tail call eliminating. 1726 } 1727 1728 return PP->Lex(Result); 1729 } 1730 1731 Kind = tok::hash; 1732 } 1733 } else { 1734 Kind = tok::percent; 1735 } 1736 break; 1737 case '<': 1738 Char = getCharAndSize(CurPtr, SizeTmp); 1739 if (ParsingFilename) { 1740 return LexAngledStringLiteral(Result, CurPtr); 1741 } else if (Char == '<' && 1742 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '=') { 1743 Kind = tok::lesslessequal; 1744 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result), 1745 SizeTmp2, Result); 1746 } else if (Char == '<') { 1747 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 1748 Kind = tok::lessless; 1749 } else if (Char == '=') { 1750 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 1751 Kind = tok::lessequal; 1752 } else if (Features.Digraphs && Char == ':') { // '<:' -> '[' 1753 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 1754 Kind = tok::l_square; 1755 } else if (Features.Digraphs && Char == '%') { // '<%' -> '{' 1756 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 1757 Kind = tok::l_brace; 1758 } else { 1759 Kind = tok::less; 1760 } 1761 break; 1762 case '>': 1763 Char = getCharAndSize(CurPtr, SizeTmp); 1764 if (Char == '=') { 1765 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 1766 Kind = tok::greaterequal; 1767 } else if (Char == '>' && 1768 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '=') { 1769 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result), 1770 SizeTmp2, Result); 1771 Kind = tok::greatergreaterequal; 1772 } else if (Char == '>') { 1773 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 1774 Kind = tok::greatergreater; 1775 } else { 1776 Kind = tok::greater; 1777 } 1778 break; 1779 case '^': 1780 Char = getCharAndSize(CurPtr, SizeTmp); 1781 if (Char == '=') { 1782 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 1783 Kind = tok::caretequal; 1784 } else { 1785 Kind = tok::caret; 1786 } 1787 break; 1788 case '|': 1789 Char = getCharAndSize(CurPtr, SizeTmp); 1790 if (Char == '=') { 1791 Kind = tok::pipeequal; 1792 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 1793 } else if (Char == '|') { 1794 Kind = tok::pipepipe; 1795 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 1796 } else { 1797 Kind = tok::pipe; 1798 } 1799 break; 1800 case ':': 1801 Char = getCharAndSize(CurPtr, SizeTmp); 1802 if (Features.Digraphs && Char == '>') { 1803 Kind = tok::r_square; // ':>' -> ']' 1804 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 1805 } else if (Features.CPlusPlus && Char == ':') { 1806 Kind = tok::coloncolon; 1807 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 1808 } else { 1809 Kind = tok::colon; 1810 } 1811 break; 1812 case ';': 1813 Kind = tok::semi; 1814 break; 1815 case '=': 1816 Char = getCharAndSize(CurPtr, SizeTmp); 1817 if (Char == '=') { 1818 Kind = tok::equalequal; 1819 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 1820 } else { 1821 Kind = tok::equal; 1822 } 1823 break; 1824 case ',': 1825 Kind = tok::comma; 1826 break; 1827 case '#': 1828 Char = getCharAndSize(CurPtr, SizeTmp); 1829 if (Char == '#') { 1830 Kind = tok::hashhash; 1831 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 1832 } else if (Char == '@' && Features.Microsoft) { // #@ -> Charize 1833 Kind = tok::hashat; 1834 if (!isLexingRawMode()) 1835 Diag(BufferPtr, diag::charize_microsoft_ext); 1836 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 1837 } else { 1838 // We parsed a # character. If this occurs at the start of the line, 1839 // it's actually the start of a preprocessing directive. Callback to 1840 // the preprocessor to handle it. 1841 // FIXME: -fpreprocessed mode?? 1842 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer) { 1843 FormTokenWithChars(Result, CurPtr, tok::hash); 1844 PP->HandleDirective(Result); 1845 1846 // As an optimization, if the preprocessor didn't switch lexers, tail 1847 // recurse. 1848 if (PP->isCurrentLexer(this)) { 1849 // Start a new token. If this is a #include or something, the PP may 1850 // want us starting at the beginning of the line again. If so, set 1851 // the StartOfLine flag. 1852 if (IsAtStartOfLine) { 1853 Result.setFlag(Token::StartOfLine); 1854 IsAtStartOfLine = false; 1855 } 1856 goto LexNextToken; // GCC isn't tail call eliminating. 1857 } 1858 return PP->Lex(Result); 1859 } 1860 1861 Kind = tok::hash; 1862 } 1863 break; 1864 1865 case '@': 1866 // Objective C support. 1867 if (CurPtr[-1] == '@' && Features.ObjC1) 1868 Kind = tok::at; 1869 else 1870 Kind = tok::unknown; 1871 break; 1872 1873 case '\\': 1874 // FIXME: UCN's. 1875 // FALL THROUGH. 1876 default: 1877 Kind = tok::unknown; 1878 break; 1879 } 1880 1881 // Notify MIOpt that we read a non-whitespace/non-comment token. 1882 MIOpt.ReadToken(); 1883 1884 // Update the location of token as well as BufferPtr. 1885 FormTokenWithChars(Result, CurPtr, Kind); 1886 } 1887