blob: 3e688757681484c7aa4c97626141745b565b0442 [file] [log] [blame]
Chris Lattner22eb9722006-06-18 05:43:12 +00001//===--- Lexer.cpp - C Language Family Lexer ------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner22eb9722006-06-18 05:43:12 +00007//
8//===----------------------------------------------------------------------===//
9//
Chris Lattner146762e2007-07-20 16:59:19 +000010// This file implements the Lexer and Token interfaces.
Chris Lattner22eb9722006-06-18 05:43:12 +000011//
12//===----------------------------------------------------------------------===//
13//
14// TODO: GCC Diagnostics emitted by the lexer:
15// PEDWARN: (form feed|vertical tab) in preprocessing directive
16//
17// Universal characters, unicode, char mapping:
18// WARNING: `%.*s' is not in NFKC
19// WARNING: `%.*s' is not in NFC
20//
21// Other:
Chris Lattner22eb9722006-06-18 05:43:12 +000022// TODO: Options to support:
23// -fexec-charset,-fwide-exec-charset
24//
25//===----------------------------------------------------------------------===//
26
27#include "clang/Lex/Lexer.h"
28#include "clang/Lex/Preprocessor.h"
Chris Lattner60f36222009-01-29 05:15:15 +000029#include "clang/Lex/LexDiagnostic.h"
Douglas Gregor11583702010-08-25 17:04:25 +000030#include "clang/Lex/CodeCompletionHandler.h"
Chris Lattnerdc5c0552007-07-20 16:37:10 +000031#include "clang/Basic/SourceManager.h"
Douglas Gregoraf82e352010-07-20 20:18:03 +000032#include "llvm/ADT/StringSwitch.h"
Chris Lattner619c1742007-07-22 18:38:25 +000033#include "llvm/Support/Compiler.h"
Chris Lattner739e7392007-04-29 07:12:06 +000034#include "llvm/Support/MemoryBuffer.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000035#include <cctype>
Chris Lattner22eb9722006-06-18 05:43:12 +000036using namespace clang;
37
Chris Lattner3dfff972009-12-17 05:29:40 +000038static void InitCharacterInfo();
Chris Lattner22eb9722006-06-18 05:43:12 +000039
Chris Lattner4894f482007-10-07 08:47:24 +000040//===----------------------------------------------------------------------===//
41// Token Class Implementation
42//===----------------------------------------------------------------------===//
43
Mike Stump11289f42009-09-09 15:08:12 +000044/// isObjCAtKeyword - Return true if we have an ObjC keyword identifier.
Chris Lattner4894f482007-10-07 08:47:24 +000045bool Token::isObjCAtKeyword(tok::ObjCKeywordKind objcKey) const {
Douglas Gregor90abb6d2008-12-01 21:46:47 +000046 if (IdentifierInfo *II = getIdentifierInfo())
47 return II->getObjCKeywordID() == objcKey;
48 return false;
Chris Lattner4894f482007-10-07 08:47:24 +000049}
50
51/// getObjCKeywordID - Return the ObjC keyword kind.
52tok::ObjCKeywordKind Token::getObjCKeywordID() const {
53 IdentifierInfo *specId = getIdentifierInfo();
54 return specId ? specId->getObjCKeywordID() : tok::objc_not_keyword;
55}
56
Chris Lattner67671ed2007-12-13 01:59:49 +000057
Chris Lattner4894f482007-10-07 08:47:24 +000058//===----------------------------------------------------------------------===//
59// Lexer Class Implementation
60//===----------------------------------------------------------------------===//
61
Mike Stump11289f42009-09-09 15:08:12 +000062void Lexer::InitLexer(const char *BufStart, const char *BufPtr,
Chris Lattnerf76b9202009-01-17 06:55:17 +000063 const char *BufEnd) {
Chris Lattner3dfff972009-12-17 05:29:40 +000064 InitCharacterInfo();
Mike Stump11289f42009-09-09 15:08:12 +000065
Chris Lattnerf76b9202009-01-17 06:55:17 +000066 BufferStart = BufStart;
67 BufferPtr = BufPtr;
68 BufferEnd = BufEnd;
Mike Stump11289f42009-09-09 15:08:12 +000069
Chris Lattnerf76b9202009-01-17 06:55:17 +000070 assert(BufEnd[0] == 0 &&
71 "We assume that the input buffer has a null character at the end"
72 " to simplify lexing!");
Mike Stump11289f42009-09-09 15:08:12 +000073
Chris Lattnerf76b9202009-01-17 06:55:17 +000074 Is_PragmaLexer = false;
Chris Lattner7c027ee2009-12-14 06:16:57 +000075 IsInConflictMarker = false;
Douglas Gregor2436e712009-09-17 21:32:03 +000076
Chris Lattnerf76b9202009-01-17 06:55:17 +000077 // Start of the file is a start of line.
78 IsAtStartOfLine = true;
Mike Stump11289f42009-09-09 15:08:12 +000079
Chris Lattnerf76b9202009-01-17 06:55:17 +000080 // We are not after parsing a #.
81 ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +000082
Chris Lattnerf76b9202009-01-17 06:55:17 +000083 // We are not after parsing #include.
84 ParsingFilename = false;
Mike Stump11289f42009-09-09 15:08:12 +000085
Chris Lattnerf76b9202009-01-17 06:55:17 +000086 // We are not in raw mode. Raw mode disables diagnostics and interpretation
87 // of tokens (e.g. identifiers, thus disabling macro expansion). It is used
88 // to quickly lex the tokens of the buffer, e.g. when handling a "#if 0" block
89 // or otherwise skipping over tokens.
90 LexingRawMode = false;
Mike Stump11289f42009-09-09 15:08:12 +000091
Chris Lattnerf76b9202009-01-17 06:55:17 +000092 // Default to not keeping comments.
93 ExtendedTokenMode = 0;
94}
95
Chris Lattner5965a282009-01-17 07:56:59 +000096/// Lexer constructor - Create a new lexer object for the specified buffer
97/// with the specified preprocessor managing the lexing process. This lexer
98/// assumes that the associated file buffer and Preprocessor objects will
99/// outlive it, so it doesn't take ownership of either of them.
Chris Lattner710bb872009-11-30 04:18:44 +0000100Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *InputFile, Preprocessor &PP)
Chris Lattnerc8090892009-01-17 08:03:42 +0000101 : PreprocessorLexer(&PP, FID),
102 FileLoc(PP.getSourceManager().getLocForStartOfFile(FID)),
103 Features(PP.getLangOptions()) {
Mike Stump11289f42009-09-09 15:08:12 +0000104
Chris Lattner5965a282009-01-17 07:56:59 +0000105 InitLexer(InputFile->getBufferStart(), InputFile->getBufferStart(),
106 InputFile->getBufferEnd());
Mike Stump11289f42009-09-09 15:08:12 +0000107
Chris Lattner5965a282009-01-17 07:56:59 +0000108 // Default to keeping comments if the preprocessor wants them.
109 SetCommentRetentionState(PP.getCommentRetentionState());
110}
Chris Lattner4894f482007-10-07 08:47:24 +0000111
Chris Lattner02b436a2007-10-17 20:41:00 +0000112/// Lexer constructor - Create a new raw lexer object. This object is only
Chris Lattner50c90502008-10-12 01:15:46 +0000113/// suitable for calls to 'LexRawToken'. This lexer assumes that the text
114/// range will outlive it, so it doesn't take ownership of it.
Chris Lattner02b436a2007-10-17 20:41:00 +0000115Lexer::Lexer(SourceLocation fileloc, const LangOptions &features,
Chris Lattnerfcf64522009-01-17 07:42:27 +0000116 const char *BufStart, const char *BufPtr, const char *BufEnd)
Chris Lattner1abd2092009-01-17 03:48:08 +0000117 : FileLoc(fileloc), Features(features) {
Chris Lattnerf76b9202009-01-17 06:55:17 +0000118
Chris Lattnerf76b9202009-01-17 06:55:17 +0000119 InitLexer(BufStart, BufPtr, BufEnd);
Mike Stump11289f42009-09-09 15:08:12 +0000120
Chris Lattner02b436a2007-10-17 20:41:00 +0000121 // We *are* in raw mode.
122 LexingRawMode = true;
Chris Lattner02b436a2007-10-17 20:41:00 +0000123}
124
Chris Lattner08354fe2009-01-17 07:35:14 +0000125/// Lexer constructor - Create a new raw lexer object. This object is only
126/// suitable for calls to 'LexRawToken'. This lexer assumes that the text
127/// range will outlive it, so it doesn't take ownership of it.
Chris Lattner710bb872009-11-30 04:18:44 +0000128Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *FromFile,
129 const SourceManager &SM, const LangOptions &features)
Chris Lattner08354fe2009-01-17 07:35:14 +0000130 : FileLoc(SM.getLocForStartOfFile(FID)), Features(features) {
Chris Lattner08354fe2009-01-17 07:35:14 +0000131
Mike Stump11289f42009-09-09 15:08:12 +0000132 InitLexer(FromFile->getBufferStart(), FromFile->getBufferStart(),
Chris Lattner08354fe2009-01-17 07:35:14 +0000133 FromFile->getBufferEnd());
Mike Stump11289f42009-09-09 15:08:12 +0000134
Chris Lattner08354fe2009-01-17 07:35:14 +0000135 // We *are* in raw mode.
136 LexingRawMode = true;
137}
138
Chris Lattner757169b2009-01-17 08:27:52 +0000139/// Create_PragmaLexer: Lexer constructor - Create a new lexer object for
140/// _Pragma expansion. This has a variety of magic semantics that this method
141/// sets up. It returns a new'd Lexer that must be delete'd when done.
142///
143/// On entrance to this routine, TokStartLoc is a macro location which has a
144/// spelling loc that indicates the bytes to be lexed for the token and an
145/// instantiation location that indicates where all lexed tokens should be
146/// "expanded from".
147///
148/// FIXME: It would really be nice to make _Pragma just be a wrapper around a
149/// normal lexer that remaps tokens as they fly by. This would require making
150/// Preprocessor::Lex virtual. Given that, we could just dump in a magic lexer
151/// interface that could handle this stuff. This would pull GetMappedTokenLoc
152/// out of the critical path of the lexer!
153///
Mike Stump11289f42009-09-09 15:08:12 +0000154Lexer *Lexer::Create_PragmaLexer(SourceLocation SpellingLoc,
Chris Lattner9dc9c202009-02-15 20:52:18 +0000155 SourceLocation InstantiationLocStart,
156 SourceLocation InstantiationLocEnd,
Chris Lattner29a2a192009-01-19 06:46:35 +0000157 unsigned TokLen, Preprocessor &PP) {
Chris Lattner757169b2009-01-17 08:27:52 +0000158 SourceManager &SM = PP.getSourceManager();
Chris Lattner757169b2009-01-17 08:27:52 +0000159
160 // Create the lexer as if we were going to lex the file normally.
Chris Lattnercbc35ecb2009-01-19 07:46:45 +0000161 FileID SpellingFID = SM.getFileID(SpellingLoc);
Chris Lattner710bb872009-11-30 04:18:44 +0000162 const llvm::MemoryBuffer *InputFile = SM.getBuffer(SpellingFID);
163 Lexer *L = new Lexer(SpellingFID, InputFile, PP);
Mike Stump11289f42009-09-09 15:08:12 +0000164
Chris Lattner757169b2009-01-17 08:27:52 +0000165 // Now that the lexer is created, change the start/end locations so that we
166 // just lex the subsection of the file that we want. This is lexing from a
167 // scratch buffer.
168 const char *StrData = SM.getCharacterData(SpellingLoc);
Mike Stump11289f42009-09-09 15:08:12 +0000169
Chris Lattner757169b2009-01-17 08:27:52 +0000170 L->BufferPtr = StrData;
171 L->BufferEnd = StrData+TokLen;
Chris Lattnerfa217bd2009-03-08 08:08:45 +0000172 assert(L->BufferEnd[0] == 0 && "Buffer is not nul terminated!");
Chris Lattner757169b2009-01-17 08:27:52 +0000173
174 // Set the SourceLocation with the remapping information. This ensures that
175 // GetMappedTokenLoc will remap the tokens as they are lexed.
Chris Lattner4fa23622009-01-26 00:43:02 +0000176 L->FileLoc = SM.createInstantiationLoc(SM.getLocForStartOfFile(SpellingFID),
Chris Lattner9dc9c202009-02-15 20:52:18 +0000177 InstantiationLocStart,
178 InstantiationLocEnd, TokLen);
Mike Stump11289f42009-09-09 15:08:12 +0000179
Chris Lattner757169b2009-01-17 08:27:52 +0000180 // Ensure that the lexer thinks it is inside a directive, so that end \n will
181 // return an EOM token.
182 L->ParsingPreprocessorDirective = true;
Mike Stump11289f42009-09-09 15:08:12 +0000183
Chris Lattner757169b2009-01-17 08:27:52 +0000184 // This lexer really is for _Pragma.
185 L->Is_PragmaLexer = true;
186 return L;
187}
188
Chris Lattner02b436a2007-10-17 20:41:00 +0000189
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000190/// Stringify - Convert the specified string into a C string, with surrounding
191/// ""'s, and with escaped \ and " characters.
Chris Lattnerecc39e92006-07-15 05:23:31 +0000192std::string Lexer::Stringify(const std::string &Str, bool Charify) {
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000193 std::string Result = Str;
Chris Lattnerecc39e92006-07-15 05:23:31 +0000194 char Quote = Charify ? '\'' : '"';
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000195 for (unsigned i = 0, e = Result.size(); i != e; ++i) {
Chris Lattnerecc39e92006-07-15 05:23:31 +0000196 if (Result[i] == '\\' || Result[i] == Quote) {
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000197 Result.insert(Result.begin()+i, '\\');
198 ++i; ++e;
199 }
200 }
Chris Lattnerecc39e92006-07-15 05:23:31 +0000201 return Result;
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000202}
203
Chris Lattner4c4a2452007-07-24 06:57:14 +0000204/// Stringify - Convert the specified string into a C string by escaping '\'
205/// and " characters. This does not add surrounding ""'s to the string.
206void Lexer::Stringify(llvm::SmallVectorImpl<char> &Str) {
207 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
208 if (Str[i] == '\\' || Str[i] == '"') {
209 Str.insert(Str.begin()+i, '\\');
210 ++i; ++e;
211 }
212 }
213}
214
Douglas Gregor562c1f92010-01-22 19:49:59 +0000215static bool isWhitespace(unsigned char c);
Chris Lattner22eb9722006-06-18 05:43:12 +0000216
Chris Lattner8e129c22007-10-17 21:18:47 +0000217/// MeasureTokenLength - Relex the token at the specified location and return
218/// its length in bytes in the input file. If the token needs cleaning (e.g.
219/// includes a trigraph or an escaped newline) then this count includes bytes
220/// that are part of that.
221unsigned Lexer::MeasureTokenLength(SourceLocation Loc,
Chris Lattner184e65d2009-04-14 23:22:57 +0000222 const SourceManager &SM,
223 const LangOptions &LangOpts) {
Chris Lattner8e129c22007-10-17 21:18:47 +0000224 // TODO: this could be special cased for common tokens like identifiers, ')',
225 // etc to make this faster, if it mattered. Just look at StrData[0] to handle
Mike Stump11289f42009-09-09 15:08:12 +0000226 // all obviously single-char tokens. This could use
Chris Lattner8e129c22007-10-17 21:18:47 +0000227 // Lexer::isObviouslySimpleCharacter for example to handle identifiers or
228 // something.
Chris Lattner4fa23622009-01-26 00:43:02 +0000229
230 // If this comes from a macro expansion, we really do want the macro name, not
231 // the token this macro expanded to.
Chris Lattnerd3817212009-01-26 22:24:27 +0000232 Loc = SM.getInstantiationLoc(Loc);
233 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
Douglas Gregore0fbb832010-03-16 00:06:06 +0000234 bool Invalid = false;
Benjamin Kramereb92dc02010-03-16 14:14:31 +0000235 llvm::StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Douglas Gregore0fbb832010-03-16 00:06:06 +0000236 if (Invalid)
Douglas Gregor802b7762010-03-15 22:54:52 +0000237 return 0;
Benjamin Kramereb92dc02010-03-16 14:14:31 +0000238
239 const char *StrData = Buffer.data()+LocInfo.second;
Chris Lattner5509d532009-01-17 08:30:10 +0000240
Douglas Gregor562c1f92010-01-22 19:49:59 +0000241 if (isWhitespace(StrData[0]))
242 return 0;
243
Chris Lattner8e129c22007-10-17 21:18:47 +0000244 // Create a lexer starting at the beginning of this token.
Sebastian Redl51752302010-09-30 01:03:03 +0000245 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts,
246 Buffer.begin(), StrData, Buffer.end());
Chris Lattnera3d4f162009-10-14 15:04:18 +0000247 TheLexer.SetCommentRetentionState(true);
Chris Lattner8e129c22007-10-17 21:18:47 +0000248 Token TheTok;
Chris Lattner50c90502008-10-12 01:15:46 +0000249 TheLexer.LexFromRawLexer(TheTok);
Chris Lattner8e129c22007-10-17 21:18:47 +0000250 return TheTok.getLength();
251}
252
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000253SourceLocation Lexer::GetBeginningOfToken(SourceLocation Loc,
254 const SourceManager &SM,
255 const LangOptions &LangOpts) {
256 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
257 bool Invalid = false;
258 llvm::StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
259 if (Invalid)
260 return Loc;
261
262 // Back up from the current location until we hit the beginning of a line
263 // (or the buffer). We'll relex from that point.
264 const char *BufStart = Buffer.data();
265 const char *StrData = BufStart+LocInfo.second;
266 if (StrData[0] == '\n' || StrData[0] == '\r')
267 return Loc;
268
269 const char *LexStart = StrData;
270 while (LexStart != BufStart) {
271 if (LexStart[0] == '\n' || LexStart[0] == '\r') {
272 ++LexStart;
273 break;
274 }
275
276 --LexStart;
277 }
278
279 // Create a lexer starting at the beginning of this token.
280 SourceLocation LexerStartLoc = Loc.getFileLocWithOffset(-LocInfo.second);
281 Lexer TheLexer(LexerStartLoc, LangOpts, BufStart, LexStart, Buffer.end());
282 TheLexer.SetCommentRetentionState(true);
283
284 // Lex tokens until we find the token that contains the source location.
285 Token TheTok;
286 do {
287 TheLexer.LexFromRawLexer(TheTok);
288
289 if (TheLexer.getBufferLocation() > StrData) {
290 // Lexing this token has taken the lexer past the source location we're
291 // looking for. If the current token encompasses our source location,
292 // return the beginning of that token.
293 if (TheLexer.getBufferLocation() - TheTok.getLength() <= StrData)
294 return TheTok.getLocation();
295
296 // We ended up skipping over the source location entirely, which means
297 // that it points into whitespace. We're done here.
298 break;
299 }
300 } while (TheTok.getKind() != tok::eof);
301
302 // We've passed our source location; just return the original source location.
303 return Loc;
304}
305
Douglas Gregoraf82e352010-07-20 20:18:03 +0000306namespace {
307 enum PreambleDirectiveKind {
308 PDK_Skipped,
309 PDK_StartIf,
310 PDK_EndIf,
311 PDK_Unknown
312 };
313}
314
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000315std::pair<unsigned, bool>
Douglas Gregor028d3e42010-08-09 20:45:32 +0000316Lexer::ComputePreamble(const llvm::MemoryBuffer *Buffer, unsigned MaxLines) {
Douglas Gregoraf82e352010-07-20 20:18:03 +0000317 // Create a lexer starting at the beginning of the file. Note that we use a
318 // "fake" file source location at offset 1 so that the lexer will track our
319 // position within the file.
320 const unsigned StartOffset = 1;
321 SourceLocation StartLoc = SourceLocation::getFromRawEncoding(StartOffset);
322 LangOptions LangOpts;
323 Lexer TheLexer(StartLoc, LangOpts, Buffer->getBufferStart(),
324 Buffer->getBufferStart(), Buffer->getBufferEnd());
325
326 bool InPreprocessorDirective = false;
327 Token TheTok;
328 Token IfStartTok;
329 unsigned IfCount = 0;
Douglas Gregor028d3e42010-08-09 20:45:32 +0000330 unsigned Line = 0;
331
Douglas Gregoraf82e352010-07-20 20:18:03 +0000332 do {
333 TheLexer.LexFromRawLexer(TheTok);
334
335 if (InPreprocessorDirective) {
336 // If we've hit the end of the file, we're done.
337 if (TheTok.getKind() == tok::eof) {
338 InPreprocessorDirective = false;
339 break;
340 }
341
342 // If we haven't hit the end of the preprocessor directive, skip this
343 // token.
344 if (!TheTok.isAtStartOfLine())
345 continue;
346
347 // We've passed the end of the preprocessor directive, and will look
348 // at this token again below.
349 InPreprocessorDirective = false;
350 }
351
Douglas Gregor028d3e42010-08-09 20:45:32 +0000352 // Keep track of the # of lines in the preamble.
353 if (TheTok.isAtStartOfLine()) {
354 ++Line;
355
356 // If we were asked to limit the number of lines in the preamble,
357 // and we're about to exceed that limit, we're done.
358 if (MaxLines && Line >= MaxLines)
359 break;
360 }
361
Douglas Gregoraf82e352010-07-20 20:18:03 +0000362 // Comments are okay; skip over them.
363 if (TheTok.getKind() == tok::comment)
364 continue;
365
366 if (TheTok.isAtStartOfLine() && TheTok.getKind() == tok::hash) {
367 // This is the start of a preprocessor directive.
368 Token HashTok = TheTok;
369 InPreprocessorDirective = true;
370
371 // Figure out which direective this is. Since we're lexing raw tokens,
372 // we don't have an identifier table available. Instead, just look at
373 // the raw identifier to recognize and categorize preprocessor directives.
374 TheLexer.LexFromRawLexer(TheTok);
375 if (TheTok.getKind() == tok::identifier && !TheTok.needsCleaning()) {
376 const char *IdStart = Buffer->getBufferStart()
377 + TheTok.getLocation().getRawEncoding() - 1;
378 llvm::StringRef Keyword(IdStart, TheTok.getLength());
379 PreambleDirectiveKind PDK
380 = llvm::StringSwitch<PreambleDirectiveKind>(Keyword)
381 .Case("include", PDK_Skipped)
382 .Case("__include_macros", PDK_Skipped)
383 .Case("define", PDK_Skipped)
384 .Case("undef", PDK_Skipped)
385 .Case("line", PDK_Skipped)
386 .Case("error", PDK_Skipped)
387 .Case("pragma", PDK_Skipped)
388 .Case("import", PDK_Skipped)
389 .Case("include_next", PDK_Skipped)
390 .Case("warning", PDK_Skipped)
391 .Case("ident", PDK_Skipped)
392 .Case("sccs", PDK_Skipped)
393 .Case("assert", PDK_Skipped)
394 .Case("unassert", PDK_Skipped)
395 .Case("if", PDK_StartIf)
396 .Case("ifdef", PDK_StartIf)
397 .Case("ifndef", PDK_StartIf)
398 .Case("elif", PDK_Skipped)
399 .Case("else", PDK_Skipped)
400 .Case("endif", PDK_EndIf)
401 .Default(PDK_Unknown);
402
403 switch (PDK) {
404 case PDK_Skipped:
405 continue;
406
407 case PDK_StartIf:
408 if (IfCount == 0)
409 IfStartTok = HashTok;
410
411 ++IfCount;
412 continue;
413
414 case PDK_EndIf:
415 // Mismatched #endif. The preamble ends here.
416 if (IfCount == 0)
417 break;
418
419 --IfCount;
420 continue;
421
422 case PDK_Unknown:
423 // We don't know what this directive is; stop at the '#'.
424 break;
425 }
426 }
427
428 // We only end up here if we didn't recognize the preprocessor
429 // directive or it was one that can't occur in the preamble at this
430 // point. Roll back the current token to the location of the '#'.
431 InPreprocessorDirective = false;
432 TheTok = HashTok;
433 }
434
Douglas Gregor028d3e42010-08-09 20:45:32 +0000435 // We hit a token that we don't recognize as being in the
436 // "preprocessing only" part of the file, so we're no longer in
437 // the preamble.
Douglas Gregoraf82e352010-07-20 20:18:03 +0000438 break;
439 } while (true);
440
441 SourceLocation End = IfCount? IfStartTok.getLocation() : TheTok.getLocation();
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000442 return std::make_pair(End.getRawEncoding() - StartLoc.getRawEncoding(),
443 IfCount? IfStartTok.isAtStartOfLine()
444 : TheTok.isAtStartOfLine());
Douglas Gregoraf82e352010-07-20 20:18:03 +0000445}
446
Chris Lattner2a6ee912010-11-17 07:05:50 +0000447
448/// AdvanceToTokenCharacter - Given a location that specifies the start of a
449/// token, return a new location that specifies a character within the token.
450SourceLocation Lexer::AdvanceToTokenCharacter(SourceLocation TokStart,
451 unsigned CharNo,
452 const SourceManager &SM,
453 const LangOptions &Features) {
454 // Figure out how many physical characters away the specified instantiation
455 // character is. This needs to take into consideration newlines and
456 // trigraphs.
457 bool Invalid = false;
458 const char *TokPtr = SM.getCharacterData(TokStart, &Invalid);
459
460 // If they request the first char of the token, we're trivially done.
461 if (Invalid || (CharNo == 0 && Lexer::isObviouslySimpleCharacter(*TokPtr)))
462 return TokStart;
463
464 unsigned PhysOffset = 0;
465
466 // The usual case is that tokens don't contain anything interesting. Skip
467 // over the uninteresting characters. If a token only consists of simple
468 // chars, this method is extremely fast.
469 while (Lexer::isObviouslySimpleCharacter(*TokPtr)) {
470 if (CharNo == 0)
471 return TokStart.getFileLocWithOffset(PhysOffset);
472 ++TokPtr, --CharNo, ++PhysOffset;
473 }
474
475 // If we have a character that may be a trigraph or escaped newline, use a
476 // lexer to parse it correctly.
477 for (; CharNo; --CharNo) {
478 unsigned Size;
479 Lexer::getCharAndSizeNoWarn(TokPtr, Size, Features);
480 TokPtr += Size;
481 PhysOffset += Size;
482 }
483
484 // Final detail: if we end up on an escaped newline, we want to return the
485 // location of the actual byte of the token. For example foo\<newline>bar
486 // advanced by 3 should return the location of b, not of \\. One compounding
487 // detail of this is that the escape may be made by a trigraph.
488 if (!Lexer::isObviouslySimpleCharacter(*TokPtr))
489 PhysOffset += Lexer::SkipEscapedNewLines(TokPtr)-TokPtr;
490
491 return TokStart.getFileLocWithOffset(PhysOffset);
492}
493
494/// \brief Computes the source location just past the end of the
495/// token at this source location.
496///
497/// This routine can be used to produce a source location that
498/// points just past the end of the token referenced by \p Loc, and
499/// is generally used when a diagnostic needs to point just after a
500/// token where it expected something different that it received. If
501/// the returned source location would not be meaningful (e.g., if
502/// it points into a macro), this routine returns an invalid
503/// source location.
504///
505/// \param Offset an offset from the end of the token, where the source
506/// location should refer to. The default offset (0) produces a source
507/// location pointing just past the end of the token; an offset of 1 produces
508/// a source location pointing to the last character in the token, etc.
509SourceLocation Lexer::getLocForEndOfToken(SourceLocation Loc, unsigned Offset,
510 const SourceManager &SM,
511 const LangOptions &Features) {
512 if (Loc.isInvalid() || !Loc.isFileID())
513 return SourceLocation();
514
515 unsigned Len = Lexer::MeasureTokenLength(Loc, SM, Features);
516 if (Len > Offset)
517 Len = Len - Offset;
518 else
519 return Loc;
520
521 return AdvanceToTokenCharacter(Loc, Len, SM, Features);
522}
523
Chris Lattner22eb9722006-06-18 05:43:12 +0000524//===----------------------------------------------------------------------===//
525// Character information.
526//===----------------------------------------------------------------------===//
527
Chris Lattner22eb9722006-06-18 05:43:12 +0000528enum {
529 CHAR_HORZ_WS = 0x01, // ' ', '\t', '\f', '\v'. Note, no '\0'
530 CHAR_VERT_WS = 0x02, // '\r', '\n'
531 CHAR_LETTER = 0x04, // a-z,A-Z
532 CHAR_NUMBER = 0x08, // 0-9
533 CHAR_UNDER = 0x10, // _
534 CHAR_PERIOD = 0x20 // .
535};
536
Chris Lattnerde50a0c2009-07-07 17:09:54 +0000537// Statically initialize CharInfo table based on ASCII character set
538// Reference: FreeBSD 7.2 /usr/share/misc/ascii
Chris Lattner3dfff972009-12-17 05:29:40 +0000539static const unsigned char CharInfo[256] =
Chris Lattnerde50a0c2009-07-07 17:09:54 +0000540{
541// 0 NUL 1 SOH 2 STX 3 ETX
542// 4 EOT 5 ENQ 6 ACK 7 BEL
543 0 , 0 , 0 , 0 ,
544 0 , 0 , 0 , 0 ,
545// 8 BS 9 HT 10 NL 11 VT
546//12 NP 13 CR 14 SO 15 SI
547 0 , CHAR_HORZ_WS, CHAR_VERT_WS, CHAR_HORZ_WS,
548 CHAR_HORZ_WS, CHAR_VERT_WS, 0 , 0 ,
549//16 DLE 17 DC1 18 DC2 19 DC3
550//20 DC4 21 NAK 22 SYN 23 ETB
551 0 , 0 , 0 , 0 ,
552 0 , 0 , 0 , 0 ,
553//24 CAN 25 EM 26 SUB 27 ESC
554//28 FS 29 GS 30 RS 31 US
555 0 , 0 , 0 , 0 ,
556 0 , 0 , 0 , 0 ,
557//32 SP 33 ! 34 " 35 #
558//36 $ 37 % 38 & 39 '
559 CHAR_HORZ_WS, 0 , 0 , 0 ,
560 0 , 0 , 0 , 0 ,
561//40 ( 41 ) 42 * 43 +
562//44 , 45 - 46 . 47 /
563 0 , 0 , 0 , 0 ,
564 0 , 0 , CHAR_PERIOD , 0 ,
565//48 0 49 1 50 2 51 3
566//52 4 53 5 54 6 55 7
567 CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER ,
568 CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER ,
569//56 8 57 9 58 : 59 ;
570//60 < 61 = 62 > 63 ?
571 CHAR_NUMBER , CHAR_NUMBER , 0 , 0 ,
572 0 , 0 , 0 , 0 ,
573//64 @ 65 A 66 B 67 C
574//68 D 69 E 70 F 71 G
575 0 , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
576 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
577//72 H 73 I 74 J 75 K
578//76 L 77 M 78 N 79 O
579 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
580 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
581//80 P 81 Q 82 R 83 S
582//84 T 85 U 86 V 87 W
583 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
584 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
585//88 X 89 Y 90 Z 91 [
586//92 \ 93 ] 94 ^ 95 _
587 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , 0 ,
588 0 , 0 , 0 , CHAR_UNDER ,
589//96 ` 97 a 98 b 99 c
590//100 d 101 e 102 f 103 g
591 0 , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
592 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
593//104 h 105 i 106 j 107 k
594//108 l 109 m 110 n 111 o
595 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
596 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
597//112 p 113 q 114 r 115 s
598//116 t 117 u 118 v 119 w
599 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
600 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
601//120 x 121 y 122 z 123 {
602//124 | 125 } 126 ~ 127 DEL
603 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , 0 ,
604 0 , 0 , 0 , 0
605};
606
Chris Lattner3dfff972009-12-17 05:29:40 +0000607static void InitCharacterInfo() {
Chris Lattner22eb9722006-06-18 05:43:12 +0000608 static bool isInited = false;
609 if (isInited) return;
Chris Lattnerde50a0c2009-07-07 17:09:54 +0000610 // check the statically-initialized CharInfo table
611 assert(CHAR_HORZ_WS == CharInfo[(int)' ']);
612 assert(CHAR_HORZ_WS == CharInfo[(int)'\t']);
613 assert(CHAR_HORZ_WS == CharInfo[(int)'\f']);
614 assert(CHAR_HORZ_WS == CharInfo[(int)'\v']);
615 assert(CHAR_VERT_WS == CharInfo[(int)'\n']);
616 assert(CHAR_VERT_WS == CharInfo[(int)'\r']);
617 assert(CHAR_UNDER == CharInfo[(int)'_']);
618 assert(CHAR_PERIOD == CharInfo[(int)'.']);
619 for (unsigned i = 'a'; i <= 'z'; ++i) {
620 assert(CHAR_LETTER == CharInfo[i]);
621 assert(CHAR_LETTER == CharInfo[i+'A'-'a']);
622 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000623 for (unsigned i = '0'; i <= '9'; ++i)
Chris Lattnerde50a0c2009-07-07 17:09:54 +0000624 assert(CHAR_NUMBER == CharInfo[i]);
Steve Naroff04bc0182009-12-08 16:38:12 +0000625
Chris Lattnerde50a0c2009-07-07 17:09:54 +0000626 isInited = true;
Chris Lattner22eb9722006-06-18 05:43:12 +0000627}
628
Chris Lattnerde50a0c2009-07-07 17:09:54 +0000629
Chris Lattner22eb9722006-06-18 05:43:12 +0000630/// isIdentifierBody - Return true if this is the body character of an
631/// identifier, which is [a-zA-Z0-9_].
632static inline bool isIdentifierBody(unsigned char c) {
Hartmut Kaiserc8107e52007-10-18 12:47:01 +0000633 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER)) ? true : false;
Chris Lattner22eb9722006-06-18 05:43:12 +0000634}
635
636/// isHorizontalWhitespace - Return true if this character is horizontal
637/// whitespace: ' ', '\t', '\f', '\v'. Note that this returns false for '\0'.
638static inline bool isHorizontalWhitespace(unsigned char c) {
Hartmut Kaiserc8107e52007-10-18 12:47:01 +0000639 return (CharInfo[c] & CHAR_HORZ_WS) ? true : false;
Chris Lattner22eb9722006-06-18 05:43:12 +0000640}
641
642/// isWhitespace - Return true if this character is horizontal or vertical
643/// whitespace: ' ', '\t', '\f', '\v', '\n', '\r'. Note that this returns false
644/// for '\0'.
645static inline bool isWhitespace(unsigned char c) {
Hartmut Kaiserc8107e52007-10-18 12:47:01 +0000646 return (CharInfo[c] & (CHAR_HORZ_WS|CHAR_VERT_WS)) ? true : false;
Chris Lattner22eb9722006-06-18 05:43:12 +0000647}
648
649/// isNumberBody - Return true if this is the body character of an
650/// preprocessing number, which is [a-zA-Z0-9_.].
651static inline bool isNumberBody(unsigned char c) {
Mike Stump11289f42009-09-09 15:08:12 +0000652 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER|CHAR_PERIOD)) ?
Hartmut Kaiserc8107e52007-10-18 12:47:01 +0000653 true : false;
Chris Lattner22eb9722006-06-18 05:43:12 +0000654}
655
Chris Lattnerd01e2912006-06-18 16:22:51 +0000656
Chris Lattner22eb9722006-06-18 05:43:12 +0000657//===----------------------------------------------------------------------===//
658// Diagnostics forwarding code.
659//===----------------------------------------------------------------------===//
660
Chris Lattner619c1742007-07-22 18:38:25 +0000661/// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
662/// lexer buffer was all instantiated at a single point, perform the mapping.
663/// This is currently only used for _Pragma implementation, so it is the slow
664/// path of the hot getSourceLocation method. Do not allow it to be inlined.
Chandler Carruthc3ce5842010-10-23 08:44:57 +0000665static LLVM_ATTRIBUTE_NOINLINE SourceLocation GetMappedTokenLoc(
666 Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen);
Chris Lattner619c1742007-07-22 18:38:25 +0000667static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
668 SourceLocation FileLoc,
Chris Lattner4fa23622009-01-26 00:43:02 +0000669 unsigned CharNo, unsigned TokLen) {
Chris Lattner9dc9c202009-02-15 20:52:18 +0000670 assert(FileLoc.isMacroID() && "Must be an instantiation");
Mike Stump11289f42009-09-09 15:08:12 +0000671
Chris Lattner619c1742007-07-22 18:38:25 +0000672 // Otherwise, we're lexing "mapped tokens". This is used for things like
673 // _Pragma handling. Combine the instantiation location of FileLoc with the
Chris Lattner53e384f2009-01-16 07:00:02 +0000674 // spelling location.
Chris Lattner9dc9c202009-02-15 20:52:18 +0000675 SourceManager &SM = PP.getSourceManager();
Mike Stump11289f42009-09-09 15:08:12 +0000676
Chris Lattner8a425862009-01-16 07:36:28 +0000677 // Create a new SLoc which is expanded from Instantiation(FileLoc) but whose
Chris Lattner53e384f2009-01-16 07:00:02 +0000678 // characters come from spelling(FileLoc)+Offset.
Chris Lattner9dc9c202009-02-15 20:52:18 +0000679 SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc);
Chris Lattner29a2a192009-01-19 06:46:35 +0000680 SpellingLoc = SpellingLoc.getFileLocWithOffset(CharNo);
Mike Stump11289f42009-09-09 15:08:12 +0000681
Chris Lattner9dc9c202009-02-15 20:52:18 +0000682 // Figure out the expansion loc range, which is the range covered by the
683 // original _Pragma(...) sequence.
684 std::pair<SourceLocation,SourceLocation> II =
685 SM.getImmediateInstantiationRange(FileLoc);
Mike Stump11289f42009-09-09 15:08:12 +0000686
Chris Lattner9dc9c202009-02-15 20:52:18 +0000687 return SM.createInstantiationLoc(SpellingLoc, II.first, II.second, TokLen);
Chris Lattner619c1742007-07-22 18:38:25 +0000688}
689
Chris Lattner22eb9722006-06-18 05:43:12 +0000690/// getSourceLocation - Return a source location identifier for the specified
691/// offset in the current file.
Chris Lattner4fa23622009-01-26 00:43:02 +0000692SourceLocation Lexer::getSourceLocation(const char *Loc,
693 unsigned TokLen) const {
Chris Lattner5d1c0272007-07-22 18:44:36 +0000694 assert(Loc >= BufferStart && Loc <= BufferEnd &&
Chris Lattner4cca5ba2006-07-02 20:05:54 +0000695 "Location out of range for this buffer!");
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000696
697 // In the normal case, we're just lexing from a simple file buffer, return
698 // the file id from FileLoc with the offset specified.
Chris Lattner5d1c0272007-07-22 18:44:36 +0000699 unsigned CharNo = Loc-BufferStart;
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000700 if (FileLoc.isFileID())
Chris Lattner29a2a192009-01-19 06:46:35 +0000701 return FileLoc.getFileLocWithOffset(CharNo);
Mike Stump11289f42009-09-09 15:08:12 +0000702
Chris Lattnerd32480d2009-01-17 06:22:33 +0000703 // Otherwise, this is the _Pragma lexer case, which pretends that all of the
704 // tokens are lexed from where the _Pragma was defined.
Chris Lattner02b436a2007-10-17 20:41:00 +0000705 assert(PP && "This doesn't work on raw lexers");
Chris Lattner4fa23622009-01-26 00:43:02 +0000706 return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen);
Chris Lattner22eb9722006-06-18 05:43:12 +0000707}
708
Chris Lattner22eb9722006-06-18 05:43:12 +0000709/// Diag - Forwarding function for diagnostics. This translate a source
710/// position in the current buffer into a SourceLocation object for rendering.
Chris Lattner427c9c12008-11-22 00:59:29 +0000711DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
Chris Lattner907dfe92008-11-18 07:59:24 +0000712 return PP->Diag(getSourceLocation(Loc), DiagID);
Chris Lattner22eb9722006-06-18 05:43:12 +0000713}
714
715//===----------------------------------------------------------------------===//
716// Trigraph and Escaped Newline Handling Code.
717//===----------------------------------------------------------------------===//
718
719/// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
720/// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
721static char GetTrigraphCharForLetter(char Letter) {
722 switch (Letter) {
723 default: return 0;
724 case '=': return '#';
725 case ')': return ']';
726 case '(': return '[';
727 case '!': return '|';
728 case '\'': return '^';
729 case '>': return '}';
730 case '/': return '\\';
731 case '<': return '{';
732 case '-': return '~';
733 }
734}
735
736/// DecodeTrigraphChar - If the specified character is a legal trigraph when
737/// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
738/// return the result character. Finally, emit a warning about trigraph use
739/// whether trigraphs are enabled or not.
740static char DecodeTrigraphChar(const char *CP, Lexer *L) {
741 char Res = GetTrigraphCharForLetter(*CP);
Chris Lattner907dfe92008-11-18 07:59:24 +0000742 if (!Res || !L) return Res;
Mike Stump11289f42009-09-09 15:08:12 +0000743
Chris Lattner907dfe92008-11-18 07:59:24 +0000744 if (!L->getFeatures().Trigraphs) {
Chris Lattner6d27a162008-11-22 02:02:22 +0000745 if (!L->isLexingRawMode())
746 L->Diag(CP-2, diag::trigraph_ignored);
Chris Lattner907dfe92008-11-18 07:59:24 +0000747 return 0;
Chris Lattner22eb9722006-06-18 05:43:12 +0000748 }
Mike Stump11289f42009-09-09 15:08:12 +0000749
Chris Lattner6d27a162008-11-22 02:02:22 +0000750 if (!L->isLexingRawMode())
Benjamin Kramere8394df2010-08-11 14:47:12 +0000751 L->Diag(CP-2, diag::trigraph_converted) << llvm::StringRef(&Res, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +0000752 return Res;
753}
754
Chris Lattnerfbce7aa2009-04-18 22:05:41 +0000755/// getEscapedNewLineSize - Return the size of the specified escaped newline,
756/// or 0 if it is not an escaped newline. P[-1] is known to be a "\" or a
Mike Stump11289f42009-09-09 15:08:12 +0000757/// trigraph equivalent on entry to this function.
Chris Lattnerfbce7aa2009-04-18 22:05:41 +0000758unsigned Lexer::getEscapedNewLineSize(const char *Ptr) {
759 unsigned Size = 0;
760 while (isWhitespace(Ptr[Size])) {
761 ++Size;
Mike Stump11289f42009-09-09 15:08:12 +0000762
Chris Lattnerfbce7aa2009-04-18 22:05:41 +0000763 if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r')
764 continue;
765
766 // If this is a \r\n or \n\r, skip the other half.
767 if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') &&
768 Ptr[Size-1] != Ptr[Size])
769 ++Size;
Mike Stump11289f42009-09-09 15:08:12 +0000770
Chris Lattnerfbce7aa2009-04-18 22:05:41 +0000771 return Size;
Mike Stump11289f42009-09-09 15:08:12 +0000772 }
773
Chris Lattnerfbce7aa2009-04-18 22:05:41 +0000774 // Not an escaped newline, must be a \t or something else.
775 return 0;
776}
777
Chris Lattner38b2cde2009-04-18 22:27:02 +0000778/// SkipEscapedNewLines - If P points to an escaped newline (or a series of
779/// them), skip over them and return the first non-escaped-newline found,
780/// otherwise return P.
781const char *Lexer::SkipEscapedNewLines(const char *P) {
782 while (1) {
783 const char *AfterEscape;
784 if (*P == '\\') {
785 AfterEscape = P+1;
786 } else if (*P == '?') {
787 // If not a trigraph for escape, bail out.
788 if (P[1] != '?' || P[2] != '/')
789 return P;
790 AfterEscape = P+3;
791 } else {
792 return P;
793 }
Mike Stump11289f42009-09-09 15:08:12 +0000794
Chris Lattner38b2cde2009-04-18 22:27:02 +0000795 unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape);
796 if (NewLineSize == 0) return P;
797 P = AfterEscape+NewLineSize;
798 }
799}
800
Chris Lattnerfbce7aa2009-04-18 22:05:41 +0000801
Chris Lattner22eb9722006-06-18 05:43:12 +0000802/// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
803/// get its size, and return it. This is tricky in several cases:
804/// 1. If currently at the start of a trigraph, we warn about the trigraph,
805/// then either return the trigraph (skipping 3 chars) or the '?',
806/// depending on whether trigraphs are enabled or not.
807/// 2. If this is an escaped newline (potentially with whitespace between
808/// the backslash and newline), implicitly skip the newline and return
809/// the char after it.
Chris Lattner505c5472006-07-03 00:55:48 +0000810/// 3. If this is a UCN, return it. FIXME: C++ UCN's?
Chris Lattner22eb9722006-06-18 05:43:12 +0000811///
812/// This handles the slow/uncommon case of the getCharAndSize method. Here we
813/// know that we can accumulate into Size, and that we have already incremented
814/// Ptr by Size bytes.
815///
Chris Lattnerd01e2912006-06-18 16:22:51 +0000816/// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
817/// be updated to match.
Chris Lattner22eb9722006-06-18 05:43:12 +0000818///
819char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
Chris Lattner146762e2007-07-20 16:59:19 +0000820 Token *Tok) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000821 // If we have a slash, look for an escaped newline.
822 if (Ptr[0] == '\\') {
823 ++Size;
824 ++Ptr;
825Slash:
826 // Common case, backslash-char where the char is not whitespace.
827 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump11289f42009-09-09 15:08:12 +0000828
Chris Lattnerc1835952009-06-23 05:15:06 +0000829 // See if we have optional whitespace characters between the slash and
830 // newline.
Chris Lattnerfbce7aa2009-04-18 22:05:41 +0000831 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
832 // Remember that this token needs to be cleaned.
833 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Chris Lattner22eb9722006-06-18 05:43:12 +0000834
Chris Lattnerfbce7aa2009-04-18 22:05:41 +0000835 // Warn if there was whitespace between the backslash and newline.
Chris Lattnerc1835952009-06-23 05:15:06 +0000836 if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode())
Chris Lattnerfbce7aa2009-04-18 22:05:41 +0000837 Diag(Ptr, diag::backslash_newline_space);
Mike Stump11289f42009-09-09 15:08:12 +0000838
Chris Lattnerfbce7aa2009-04-18 22:05:41 +0000839 // Found backslash<whitespace><newline>. Parse the char after it.
840 Size += EscapedNewLineSize;
841 Ptr += EscapedNewLineSize;
842 // Use slow version to accumulate a correct size field.
843 return getCharAndSizeSlow(Ptr, Size, Tok);
844 }
Mike Stump11289f42009-09-09 15:08:12 +0000845
Chris Lattner22eb9722006-06-18 05:43:12 +0000846 // Otherwise, this is not an escaped newline, just return the slash.
847 return '\\';
848 }
Mike Stump11289f42009-09-09 15:08:12 +0000849
Chris Lattner22eb9722006-06-18 05:43:12 +0000850 // If this is a trigraph, process it.
851 if (Ptr[0] == '?' && Ptr[1] == '?') {
852 // If this is actually a legal trigraph (not something like "??x"), emit
853 // a trigraph warning. If so, and if trigraphs are enabled, return it.
854 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : 0)) {
855 // Remember that this token needs to be cleaned.
Chris Lattner146762e2007-07-20 16:59:19 +0000856 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Chris Lattner22eb9722006-06-18 05:43:12 +0000857
858 Ptr += 3;
859 Size += 3;
860 if (C == '\\') goto Slash;
861 return C;
862 }
863 }
Mike Stump11289f42009-09-09 15:08:12 +0000864
Chris Lattner22eb9722006-06-18 05:43:12 +0000865 // If this is neither, return a single character.
866 ++Size;
867 return *Ptr;
868}
869
Chris Lattnerd01e2912006-06-18 16:22:51 +0000870
Chris Lattner22eb9722006-06-18 05:43:12 +0000871/// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
872/// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
873/// and that we have already incremented Ptr by Size bytes.
874///
Chris Lattnerd01e2912006-06-18 16:22:51 +0000875/// NOTE: When this method is updated, getCharAndSizeSlow (above) should
876/// be updated to match.
877char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
Chris Lattner22eb9722006-06-18 05:43:12 +0000878 const LangOptions &Features) {
879 // If we have a slash, look for an escaped newline.
880 if (Ptr[0] == '\\') {
881 ++Size;
882 ++Ptr;
883Slash:
884 // Common case, backslash-char where the char is not whitespace.
885 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump11289f42009-09-09 15:08:12 +0000886
Chris Lattner22eb9722006-06-18 05:43:12 +0000887 // See if we have optional whitespace characters followed by a newline.
Chris Lattnerfbce7aa2009-04-18 22:05:41 +0000888 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
889 // Found backslash<whitespace><newline>. Parse the char after it.
890 Size += EscapedNewLineSize;
891 Ptr += EscapedNewLineSize;
Mike Stump11289f42009-09-09 15:08:12 +0000892
Chris Lattnerfbce7aa2009-04-18 22:05:41 +0000893 // Use slow version to accumulate a correct size field.
894 return getCharAndSizeSlowNoWarn(Ptr, Size, Features);
895 }
Mike Stump11289f42009-09-09 15:08:12 +0000896
Chris Lattner22eb9722006-06-18 05:43:12 +0000897 // Otherwise, this is not an escaped newline, just return the slash.
898 return '\\';
899 }
Mike Stump11289f42009-09-09 15:08:12 +0000900
Chris Lattner22eb9722006-06-18 05:43:12 +0000901 // If this is a trigraph, process it.
902 if (Features.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
903 // If this is actually a legal trigraph (not something like "??x"), return
904 // it.
905 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
906 Ptr += 3;
907 Size += 3;
908 if (C == '\\') goto Slash;
909 return C;
910 }
911 }
Mike Stump11289f42009-09-09 15:08:12 +0000912
Chris Lattner22eb9722006-06-18 05:43:12 +0000913 // If this is neither, return a single character.
914 ++Size;
915 return *Ptr;
916}
917
Chris Lattner22eb9722006-06-18 05:43:12 +0000918//===----------------------------------------------------------------------===//
919// Helper methods for lexing.
920//===----------------------------------------------------------------------===//
921
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000922/// \brief Routine that indiscriminately skips bytes in the source file.
923void Lexer::SkipBytes(unsigned Bytes, bool StartOfLine) {
924 BufferPtr += Bytes;
925 if (BufferPtr > BufferEnd)
926 BufferPtr = BufferEnd;
927 IsAtStartOfLine = StartOfLine;
928}
929
Chris Lattner146762e2007-07-20 16:59:19 +0000930void Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000931 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
932 unsigned Size;
933 unsigned char C = *CurPtr++;
Chris Lattner21d9b9a2010-01-11 02:38:50 +0000934 while (isIdentifierBody(C))
Chris Lattner22eb9722006-06-18 05:43:12 +0000935 C = *CurPtr++;
Chris Lattner21d9b9a2010-01-11 02:38:50 +0000936
Chris Lattner22eb9722006-06-18 05:43:12 +0000937 --CurPtr; // Back up over the skipped character.
938
939 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
940 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
Chris Lattner505c5472006-07-03 00:55:48 +0000941 // FIXME: UCNs.
Chris Lattner21d9b9a2010-01-11 02:38:50 +0000942 //
943 // TODO: Could merge these checks into a CharInfo flag to make the comparison
944 // cheaper
Chris Lattner22eb9722006-06-18 05:43:12 +0000945 if (C != '\\' && C != '?' && (C != '$' || !Features.DollarIdents)) {
946FinishIdentifier:
Chris Lattnercefc7682006-07-08 08:28:12 +0000947 const char *IdStart = BufferPtr;
Chris Lattnerb11c3232008-10-12 04:51:35 +0000948 FormTokenWithChars(Result, CurPtr, tok::identifier);
Mike Stump11289f42009-09-09 15:08:12 +0000949
Chris Lattner0f1f5052006-07-20 04:16:23 +0000950 // If we are in raw mode, return this identifier raw. There is no need to
951 // look up identifier information or attempt to macro expand it.
952 if (LexingRawMode) return;
Mike Stump11289f42009-09-09 15:08:12 +0000953
Chris Lattnercefc7682006-07-08 08:28:12 +0000954 // Fill in Result.IdentifierInfo, looking up the identifier in the
955 // identifier table.
Chris Lattner8256b972009-01-21 07:45:14 +0000956 IdentifierInfo *II = PP->LookUpIdentifierInfo(Result, IdStart);
Mike Stump11289f42009-09-09 15:08:12 +0000957
Chris Lattner1f6c7fe2009-01-23 18:35:48 +0000958 // Change the kind of this identifier to the appropriate token kind, e.g.
959 // turning "for" into a keyword.
960 Result.setKind(II->getTokenID());
Mike Stump11289f42009-09-09 15:08:12 +0000961
Chris Lattnerc5a00062006-06-18 16:41:01 +0000962 // Finally, now that we know we have an identifier, pass this off to the
963 // preprocessor, which may macro expand it or something.
Chris Lattner8256b972009-01-21 07:45:14 +0000964 if (II->isHandleIdentifierCase())
Chris Lattnerad89ec02009-01-21 07:43:11 +0000965 PP->HandleIdentifier(Result);
966 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000967 }
Mike Stump11289f42009-09-09 15:08:12 +0000968
Chris Lattner22eb9722006-06-18 05:43:12 +0000969 // Otherwise, $,\,? in identifier found. Enter slower path.
Mike Stump11289f42009-09-09 15:08:12 +0000970
Chris Lattner22eb9722006-06-18 05:43:12 +0000971 C = getCharAndSize(CurPtr, Size);
972 while (1) {
973 if (C == '$') {
974 // If we hit a $ and they are not supported in identifiers, we are done.
975 if (!Features.DollarIdents) goto FinishIdentifier;
Mike Stump11289f42009-09-09 15:08:12 +0000976
Chris Lattner22eb9722006-06-18 05:43:12 +0000977 // Otherwise, emit a diagnostic and continue.
Chris Lattner6d27a162008-11-22 02:02:22 +0000978 if (!isLexingRawMode())
979 Diag(CurPtr, diag::ext_dollar_in_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +0000980 CurPtr = ConsumeChar(CurPtr, Size, Result);
981 C = getCharAndSize(CurPtr, Size);
982 continue;
Chris Lattner505c5472006-07-03 00:55:48 +0000983 } else if (!isIdentifierBody(C)) { // FIXME: UCNs.
Chris Lattner22eb9722006-06-18 05:43:12 +0000984 // Found end of identifier.
985 goto FinishIdentifier;
986 }
987
988 // Otherwise, this character is good, consume it.
989 CurPtr = ConsumeChar(CurPtr, Size, Result);
990
991 C = getCharAndSize(CurPtr, Size);
Chris Lattner505c5472006-07-03 00:55:48 +0000992 while (isIdentifierBody(C)) { // FIXME: UCNs.
Chris Lattner22eb9722006-06-18 05:43:12 +0000993 CurPtr = ConsumeChar(CurPtr, Size, Result);
994 C = getCharAndSize(CurPtr, Size);
995 }
996 }
997}
998
Douglas Gregor759ef232010-08-30 14:50:47 +0000999/// isHexaLiteral - Return true if Start points to a hex constant.
Chris Lattner5f183aa2010-08-30 17:11:14 +00001000/// in microsoft mode (where this is supposed to be several different tokens).
Chris Lattner0f0492e2010-08-31 16:42:00 +00001001static bool isHexaLiteral(const char *Start, const LangOptions &Features) {
1002 unsigned Size;
1003 char C1 = Lexer::getCharAndSizeNoWarn(Start, Size, Features);
1004 if (C1 != '0')
1005 return false;
1006 char C2 = Lexer::getCharAndSizeNoWarn(Start + Size, Size, Features);
1007 return (C2 == 'x' || C2 == 'X');
Douglas Gregor759ef232010-08-30 14:50:47 +00001008}
Chris Lattner22eb9722006-06-18 05:43:12 +00001009
Nate Begeman5eee9332008-04-14 02:26:39 +00001010/// LexNumericConstant - Lex the remainder of a integer or floating point
Chris Lattner22eb9722006-06-18 05:43:12 +00001011/// constant. From[-1] is the first character lexed. Return the end of the
1012/// constant.
Chris Lattner146762e2007-07-20 16:59:19 +00001013void Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001014 unsigned Size;
1015 char C = getCharAndSize(CurPtr, Size);
1016 char PrevCh = 0;
Chris Lattner505c5472006-07-03 00:55:48 +00001017 while (isNumberBody(C)) { // FIXME: UCNs?
Chris Lattner22eb9722006-06-18 05:43:12 +00001018 CurPtr = ConsumeChar(CurPtr, Size, Result);
1019 PrevCh = C;
1020 C = getCharAndSize(CurPtr, Size);
1021 }
Mike Stump11289f42009-09-09 15:08:12 +00001022
Chris Lattner22eb9722006-06-18 05:43:12 +00001023 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
Chris Lattner7a9e9e72010-08-30 17:09:08 +00001024 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) {
1025 // If we are in Microsoft mode, don't continue if the constant is hex.
1026 // For example, MSVC will accept the following as 3 tokens: 0x1234567e+1
Chris Lattner0f0492e2010-08-31 16:42:00 +00001027 if (!Features.Microsoft || !isHexaLiteral(BufferPtr, Features))
Chris Lattner7a9e9e72010-08-30 17:09:08 +00001028 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1029 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001030
1031 // If we have a hex FP constant, continue.
Alexis Hunt91b78382010-01-10 23:37:56 +00001032 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p') &&
Chris Lattner7a9e9e72010-08-30 17:09:08 +00001033 !Features.CPlusPlus0x)
Chris Lattner22eb9722006-06-18 05:43:12 +00001034 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
Mike Stump11289f42009-09-09 15:08:12 +00001035
Chris Lattnerd01e2912006-06-18 16:22:51 +00001036 // Update the location of token as well as BufferPtr.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001037 const char *TokStart = BufferPtr;
Chris Lattnerb11c3232008-10-12 04:51:35 +00001038 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001039 Result.setLiteralData(TokStart);
Chris Lattner22eb9722006-06-18 05:43:12 +00001040}
1041
1042/// LexStringLiteral - Lex the remainder of a string literal, after having lexed
1043/// either " or L".
Chris Lattner4d963442008-10-12 04:05:48 +00001044void Lexer::LexStringLiteral(Token &Result, const char *CurPtr, bool Wide) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001045 const char *NulCharacter = 0; // Does this string contain the \0 character?
Mike Stump11289f42009-09-09 15:08:12 +00001046
Chris Lattner22eb9722006-06-18 05:43:12 +00001047 char C = getAndAdvanceChar(CurPtr, Result);
1048 while (C != '"') {
Chris Lattner52d96ac2010-05-30 23:27:38 +00001049 // Skip escaped characters. Escaped newlines will already be processed by
1050 // getAndAdvanceChar.
1051 if (C == '\\')
Chris Lattner22eb9722006-06-18 05:43:12 +00001052 C = getAndAdvanceChar(CurPtr, Result);
Douglas Gregorfe4a4102010-05-30 22:59:50 +00001053
Chris Lattner52d96ac2010-05-30 23:27:38 +00001054 if (C == '\n' || C == '\r' || // Newline.
Douglas Gregorfe4a4102010-05-30 22:59:50 +00001055 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Douglas Gregor11583702010-08-25 17:04:25 +00001056 if (C == 0 && PP && PP->isCodeCompletionFile(FileLoc))
1057 PP->CodeCompleteNaturalLanguage();
1058 else if (!isLexingRawMode() && !Features.AsmPreprocessor)
Chris Lattner6d27a162008-11-22 02:02:22 +00001059 Diag(BufferPtr, diag::err_unterminated_string);
Chris Lattnerb11c3232008-10-12 04:51:35 +00001060 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Chris Lattner5a78a022006-07-20 06:02:19 +00001061 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001062 }
Chris Lattner52d96ac2010-05-30 23:27:38 +00001063
1064 if (C == 0)
1065 NulCharacter = CurPtr-1;
Chris Lattner22eb9722006-06-18 05:43:12 +00001066 C = getAndAdvanceChar(CurPtr, Result);
1067 }
Mike Stump11289f42009-09-09 15:08:12 +00001068
Chris Lattner5a78a022006-07-20 06:02:19 +00001069 // If a nul character existed in the string, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00001070 if (NulCharacter && !isLexingRawMode())
1071 Diag(NulCharacter, diag::null_in_string);
Chris Lattner22eb9722006-06-18 05:43:12 +00001072
Chris Lattnerd01e2912006-06-18 16:22:51 +00001073 // Update the location of the token as well as the BufferPtr instance var.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001074 const char *TokStart = BufferPtr;
Alexis Hunt3b791862010-08-30 17:47:05 +00001075 FormTokenWithChars(Result, CurPtr,
1076 Wide ? tok::wide_string_literal : tok::string_literal);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001077 Result.setLiteralData(TokStart);
Chris Lattner22eb9722006-06-18 05:43:12 +00001078}
1079
1080/// LexAngledStringLiteral - Lex the remainder of an angled string literal,
1081/// after having lexed the '<' character. This is used for #include filenames.
Chris Lattner146762e2007-07-20 16:59:19 +00001082void Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001083 const char *NulCharacter = 0; // Does this string contain the \0 character?
Chris Lattnerb40289b2009-04-17 23:56:52 +00001084 const char *AfterLessPos = CurPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00001085 char C = getAndAdvanceChar(CurPtr, Result);
1086 while (C != '>') {
1087 // Skip escaped characters.
1088 if (C == '\\') {
1089 // Skip the escaped character.
1090 C = getAndAdvanceChar(CurPtr, Result);
1091 } else if (C == '\n' || C == '\r' || // Newline.
1092 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Chris Lattnerb40289b2009-04-17 23:56:52 +00001093 // If the filename is unterminated, then it must just be a lone <
1094 // character. Return this as such.
1095 FormTokenWithChars(Result, AfterLessPos, tok::less);
Chris Lattner5a78a022006-07-20 06:02:19 +00001096 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001097 } else if (C == 0) {
1098 NulCharacter = CurPtr-1;
1099 }
1100 C = getAndAdvanceChar(CurPtr, Result);
1101 }
Mike Stump11289f42009-09-09 15:08:12 +00001102
Chris Lattner5a78a022006-07-20 06:02:19 +00001103 // If a nul character existed in the string, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00001104 if (NulCharacter && !isLexingRawMode())
1105 Diag(NulCharacter, diag::null_in_string);
Mike Stump11289f42009-09-09 15:08:12 +00001106
Chris Lattnerd01e2912006-06-18 16:22:51 +00001107 // Update the location of token as well as BufferPtr.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001108 const char *TokStart = BufferPtr;
Chris Lattnerb11c3232008-10-12 04:51:35 +00001109 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001110 Result.setLiteralData(TokStart);
Chris Lattner22eb9722006-06-18 05:43:12 +00001111}
1112
1113
1114/// LexCharConstant - Lex the remainder of a character constant, after having
1115/// lexed either ' or L'.
Chris Lattner146762e2007-07-20 16:59:19 +00001116void Lexer::LexCharConstant(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001117 const char *NulCharacter = 0; // Does this character contain the \0 character?
1118
Chris Lattner22eb9722006-06-18 05:43:12 +00001119 char C = getAndAdvanceChar(CurPtr, Result);
1120 if (C == '\'') {
Chris Lattnerd14705b2009-03-18 21:10:12 +00001121 if (!isLexingRawMode() && !Features.AsmPreprocessor)
Chris Lattner6d27a162008-11-22 02:02:22 +00001122 Diag(BufferPtr, diag::err_empty_character);
Chris Lattnerb11c3232008-10-12 04:51:35 +00001123 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner5a78a022006-07-20 06:02:19 +00001124 return;
Chris Lattner86851b82010-07-07 23:24:27 +00001125 }
1126
1127 while (C != '\'') {
1128 // Skip escaped characters.
1129 if (C == '\\') {
1130 // Skip the escaped character.
1131 // FIXME: UCN's
1132 C = getAndAdvanceChar(CurPtr, Result);
1133 } else if (C == '\n' || C == '\r' || // Newline.
1134 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Douglas Gregor11583702010-08-25 17:04:25 +00001135 if (C == 0 && PP && PP->isCodeCompletionFile(FileLoc))
1136 PP->CodeCompleteNaturalLanguage();
1137 else if (!isLexingRawMode() && !Features.AsmPreprocessor)
Chris Lattner86851b82010-07-07 23:24:27 +00001138 Diag(BufferPtr, diag::err_unterminated_char);
1139 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1140 return;
1141 } else if (C == 0) {
1142 NulCharacter = CurPtr-1;
1143 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001144 C = getAndAdvanceChar(CurPtr, Result);
1145 }
Mike Stump11289f42009-09-09 15:08:12 +00001146
Chris Lattner86851b82010-07-07 23:24:27 +00001147 // If a nul character existed in the character, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00001148 if (NulCharacter && !isLexingRawMode())
1149 Diag(NulCharacter, diag::null_in_char);
Chris Lattner22eb9722006-06-18 05:43:12 +00001150
Chris Lattnerd01e2912006-06-18 16:22:51 +00001151 // Update the location of token as well as BufferPtr.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001152 const char *TokStart = BufferPtr;
Chris Lattnerb11c3232008-10-12 04:51:35 +00001153 FormTokenWithChars(Result, CurPtr, tok::char_constant);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001154 Result.setLiteralData(TokStart);
Chris Lattner22eb9722006-06-18 05:43:12 +00001155}
1156
1157/// SkipWhitespace - Efficiently skip over a series of whitespace characters.
1158/// Update BufferPtr to point to the next non-whitespace character and return.
Chris Lattner4d963442008-10-12 04:05:48 +00001159///
1160/// This method forms a token and returns true if KeepWhitespaceMode is enabled.
1161///
1162bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001163 // Whitespace - Skip it, then return the token after the whitespace.
1164 unsigned char Char = *CurPtr; // Skip consequtive spaces efficiently.
1165 while (1) {
1166 // Skip horizontal whitespace very aggressively.
1167 while (isHorizontalWhitespace(Char))
1168 Char = *++CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00001169
Daniel Dunbar5c4cc092008-11-25 00:20:22 +00001170 // Otherwise if we have something other than whitespace, we're done.
Chris Lattner22eb9722006-06-18 05:43:12 +00001171 if (Char != '\n' && Char != '\r')
1172 break;
Mike Stump11289f42009-09-09 15:08:12 +00001173
Chris Lattner22eb9722006-06-18 05:43:12 +00001174 if (ParsingPreprocessorDirective) {
1175 // End of preprocessor directive line, let LexTokenInternal handle this.
1176 BufferPtr = CurPtr;
Chris Lattner4d963442008-10-12 04:05:48 +00001177 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001178 }
Mike Stump11289f42009-09-09 15:08:12 +00001179
Chris Lattner22eb9722006-06-18 05:43:12 +00001180 // ok, but handle newline.
1181 // The returned token is at the start of the line.
Chris Lattner146762e2007-07-20 16:59:19 +00001182 Result.setFlag(Token::StartOfLine);
Chris Lattner22eb9722006-06-18 05:43:12 +00001183 // No leading whitespace seen so far.
Chris Lattner146762e2007-07-20 16:59:19 +00001184 Result.clearFlag(Token::LeadingSpace);
Chris Lattner22eb9722006-06-18 05:43:12 +00001185 Char = *++CurPtr;
1186 }
1187
1188 // If this isn't immediately after a newline, there is leading space.
1189 char PrevChar = CurPtr[-1];
1190 if (PrevChar != '\n' && PrevChar != '\r')
Chris Lattner146762e2007-07-20 16:59:19 +00001191 Result.setFlag(Token::LeadingSpace);
Chris Lattner22eb9722006-06-18 05:43:12 +00001192
Chris Lattner4d963442008-10-12 04:05:48 +00001193 // If the client wants us to return whitespace, return it now.
1194 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00001195 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner4d963442008-10-12 04:05:48 +00001196 return true;
1197 }
Mike Stump11289f42009-09-09 15:08:12 +00001198
Chris Lattner22eb9722006-06-18 05:43:12 +00001199 BufferPtr = CurPtr;
Chris Lattner4d963442008-10-12 04:05:48 +00001200 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001201}
1202
1203// SkipBCPLComment - We have just read the // characters from input. Skip until
1204// we find the newline character thats terminate the comment. Then update
Chris Lattner87d02082010-01-18 22:35:47 +00001205/// BufferPtr and return.
1206///
1207/// If we're in KeepCommentMode or any CommentHandler has inserted
1208/// some tokens, this will store the first token and return true.
Chris Lattner146762e2007-07-20 16:59:19 +00001209bool Lexer::SkipBCPLComment(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001210 // If BCPL comments aren't explicitly enabled for this language, emit an
1211 // extension warning.
Chris Lattner6d27a162008-11-22 02:02:22 +00001212 if (!Features.BCPLComment && !isLexingRawMode()) {
Chris Lattnerd01e2912006-06-18 16:22:51 +00001213 Diag(BufferPtr, diag::ext_bcpl_comment);
Mike Stump11289f42009-09-09 15:08:12 +00001214
Chris Lattner22eb9722006-06-18 05:43:12 +00001215 // Mark them enabled so we only emit one warning for this translation
1216 // unit.
1217 Features.BCPLComment = true;
1218 }
Mike Stump11289f42009-09-09 15:08:12 +00001219
Chris Lattner22eb9722006-06-18 05:43:12 +00001220 // Scan over the body of the comment. The common case, when scanning, is that
1221 // the comment contains normal ascii characters with nothing interesting in
1222 // them. As such, optimize for this case with the inner loop.
1223 char C;
1224 do {
1225 C = *CurPtr;
Chris Lattner505c5472006-07-03 00:55:48 +00001226 // FIXME: Speedup BCPL comment lexing. Just scan for a \n or \r character.
1227 // If we find a \n character, scan backwards, checking to see if it's an
1228 // escaped newline, like we do for block comments.
Mike Stump11289f42009-09-09 15:08:12 +00001229
Chris Lattner22eb9722006-06-18 05:43:12 +00001230 // Skip over characters in the fast loop.
1231 while (C != 0 && // Potentially EOF.
1232 C != '\\' && // Potentially escaped newline.
1233 C != '?' && // Potentially trigraph.
1234 C != '\n' && C != '\r') // Newline or DOS-style newline.
1235 C = *++CurPtr;
1236
1237 // If this is a newline, we're done.
1238 if (C == '\n' || C == '\r')
1239 break; // Found the newline? Break out!
Mike Stump11289f42009-09-09 15:08:12 +00001240
Chris Lattner22eb9722006-06-18 05:43:12 +00001241 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
Chris Lattnere141a9e2008-12-12 07:34:39 +00001242 // properly decode the character. Read it in raw mode to avoid emitting
1243 // diagnostics about things like trigraphs. If we see an escaped newline,
1244 // we'll handle it below.
Chris Lattner22eb9722006-06-18 05:43:12 +00001245 const char *OldPtr = CurPtr;
Chris Lattnere141a9e2008-12-12 07:34:39 +00001246 bool OldRawMode = isLexingRawMode();
1247 LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001248 C = getAndAdvanceChar(CurPtr, Result);
Chris Lattnere141a9e2008-12-12 07:34:39 +00001249 LexingRawMode = OldRawMode;
Chris Lattnerecdaf402009-04-05 00:26:41 +00001250
1251 // If the char that we finally got was a \n, then we must have had something
1252 // like \<newline><newline>. We don't want to have consumed the second
1253 // newline, we want CurPtr, to end up pointing to it down below.
1254 if (C == '\n' || C == '\r') {
1255 --CurPtr;
1256 C = 'x'; // doesn't matter what this is.
1257 }
Mike Stump11289f42009-09-09 15:08:12 +00001258
Chris Lattner22eb9722006-06-18 05:43:12 +00001259 // If we read multiple characters, and one of those characters was a \r or
Chris Lattnerff591e22007-06-09 06:07:22 +00001260 // \n, then we had an escaped newline within the comment. Emit diagnostic
1261 // unless the next line is also a // comment.
1262 if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') {
Chris Lattner22eb9722006-06-18 05:43:12 +00001263 for (; OldPtr != CurPtr; ++OldPtr)
1264 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
Chris Lattnerff591e22007-06-09 06:07:22 +00001265 // Okay, we found a // comment that ends in a newline, if the next
1266 // line is also a // comment, but has spaces, don't emit a diagnostic.
1267 if (isspace(C)) {
1268 const char *ForwardPtr = CurPtr;
1269 while (isspace(*ForwardPtr)) // Skip whitespace.
1270 ++ForwardPtr;
1271 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
1272 break;
1273 }
Mike Stump11289f42009-09-09 15:08:12 +00001274
Chris Lattner6d27a162008-11-22 02:02:22 +00001275 if (!isLexingRawMode())
1276 Diag(OldPtr-1, diag::ext_multi_line_bcpl_comment);
Chris Lattnercb283342006-06-18 06:48:37 +00001277 break;
Chris Lattner22eb9722006-06-18 05:43:12 +00001278 }
1279 }
Mike Stump11289f42009-09-09 15:08:12 +00001280
Douglas Gregor11583702010-08-25 17:04:25 +00001281 if (CurPtr == BufferEnd+1) {
1282 if (PP && PP->isCodeCompletionFile(FileLoc))
1283 PP->CodeCompleteNaturalLanguage();
1284
1285 --CurPtr;
1286 break;
1287 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001288 } while (C != '\n' && C != '\r');
1289
Chris Lattner93ddf802010-02-03 21:06:21 +00001290 // Found but did not consume the newline. Notify comment handlers about the
1291 // comment unless we're in a #if 0 block.
1292 if (PP && !isLexingRawMode() &&
1293 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
1294 getSourceLocation(CurPtr)))) {
Chris Lattner87d02082010-01-18 22:35:47 +00001295 BufferPtr = CurPtr;
1296 return true; // A token has to be returned.
1297 }
Mike Stump11289f42009-09-09 15:08:12 +00001298
Chris Lattner457fc152006-07-29 06:30:25 +00001299 // If we are returning comments as tokens, return this comment as a token.
Chris Lattner8637abd2008-10-12 03:22:02 +00001300 if (inKeepCommentMode())
Chris Lattner457fc152006-07-29 06:30:25 +00001301 return SaveBCPLComment(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +00001302
1303 // If we are inside a preprocessor directive and we see the end of line,
1304 // return immediately, so that the lexer can return this as an EOM token.
Chris Lattner457fc152006-07-29 06:30:25 +00001305 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001306 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00001307 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001308 }
Mike Stump11289f42009-09-09 15:08:12 +00001309
Chris Lattner22eb9722006-06-18 05:43:12 +00001310 // Otherwise, eat the \n character. We don't care if this is a \n\r or
Chris Lattner87e97ea2008-10-12 00:23:07 +00001311 // \r\n sequence. This is an efficiency hack (because we know the \n can't
Chris Lattner4d963442008-10-12 04:05:48 +00001312 // contribute to another token), it isn't needed for correctness. Note that
1313 // this is ok even in KeepWhitespaceMode, because we would have returned the
1314 /// comment above in that mode.
Chris Lattner22eb9722006-06-18 05:43:12 +00001315 ++CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00001316
Chris Lattner22eb9722006-06-18 05:43:12 +00001317 // The next returned token is at the start of the line.
Chris Lattner146762e2007-07-20 16:59:19 +00001318 Result.setFlag(Token::StartOfLine);
Chris Lattner22eb9722006-06-18 05:43:12 +00001319 // No leading whitespace seen so far.
Chris Lattner146762e2007-07-20 16:59:19 +00001320 Result.clearFlag(Token::LeadingSpace);
Chris Lattner22eb9722006-06-18 05:43:12 +00001321 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00001322 return false;
Chris Lattner457fc152006-07-29 06:30:25 +00001323}
Chris Lattner22eb9722006-06-18 05:43:12 +00001324
Chris Lattner457fc152006-07-29 06:30:25 +00001325/// SaveBCPLComment - If in save-comment mode, package up this BCPL comment in
1326/// an appropriate way and return it.
Chris Lattner146762e2007-07-20 16:59:19 +00001327bool Lexer::SaveBCPLComment(Token &Result, const char *CurPtr) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00001328 // If we're not in a preprocessor directive, just return the // comment
1329 // directly.
1330 FormTokenWithChars(Result, CurPtr, tok::comment);
Mike Stump11289f42009-09-09 15:08:12 +00001331
Chris Lattnerb11c3232008-10-12 04:51:35 +00001332 if (!ParsingPreprocessorDirective)
1333 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001334
Chris Lattnerb11c3232008-10-12 04:51:35 +00001335 // If this BCPL-style comment is in a macro definition, transmogrify it into
1336 // a C-style block comment.
Douglas Gregordc970f02010-03-16 22:30:13 +00001337 bool Invalid = false;
1338 std::string Spelling = PP->getSpelling(Result, &Invalid);
1339 if (Invalid)
1340 return true;
1341
Chris Lattnerb11c3232008-10-12 04:51:35 +00001342 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not bcpl comment?");
1343 Spelling[1] = '*'; // Change prefix to "/*".
1344 Spelling += "*/"; // add suffix.
Mike Stump11289f42009-09-09 15:08:12 +00001345
Chris Lattnerb11c3232008-10-12 04:51:35 +00001346 Result.setKind(tok::comment);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001347 PP->CreateString(&Spelling[0], Spelling.size(), Result,
1348 Result.getLocation());
Chris Lattnere01e7582008-10-12 04:15:42 +00001349 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001350}
1351
Chris Lattnercb283342006-06-18 06:48:37 +00001352/// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
1353/// character (either \n or \r) is part of an escaped newline sequence. Issue a
Chris Lattner89770572008-12-12 07:14:34 +00001354/// diagnostic if so. We know that the newline is inside of a block comment.
Mike Stump11289f42009-09-09 15:08:12 +00001355static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
Chris Lattner1f583052006-06-18 06:53:56 +00001356 Lexer *L) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001357 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
Mike Stump11289f42009-09-09 15:08:12 +00001358
Chris Lattner22eb9722006-06-18 05:43:12 +00001359 // Back up off the newline.
1360 --CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00001361
Chris Lattner22eb9722006-06-18 05:43:12 +00001362 // If this is a two-character newline sequence, skip the other character.
1363 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
1364 // \n\n or \r\r -> not escaped newline.
1365 if (CurPtr[0] == CurPtr[1])
1366 return false;
1367 // \n\r or \r\n -> skip the newline.
1368 --CurPtr;
1369 }
Mike Stump11289f42009-09-09 15:08:12 +00001370
Chris Lattner22eb9722006-06-18 05:43:12 +00001371 // If we have horizontal whitespace, skip over it. We allow whitespace
1372 // between the slash and newline.
1373 bool HasSpace = false;
1374 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
1375 --CurPtr;
1376 HasSpace = true;
1377 }
Mike Stump11289f42009-09-09 15:08:12 +00001378
Chris Lattner22eb9722006-06-18 05:43:12 +00001379 // If we have a slash, we know this is an escaped newline.
1380 if (*CurPtr == '\\') {
Chris Lattnercb283342006-06-18 06:48:37 +00001381 if (CurPtr[-1] != '*') return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001382 } else {
1383 // It isn't a slash, is it the ?? / trigraph?
Chris Lattnercb283342006-06-18 06:48:37 +00001384 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
1385 CurPtr[-3] != '*')
Chris Lattner22eb9722006-06-18 05:43:12 +00001386 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001387
Chris Lattnercb283342006-06-18 06:48:37 +00001388 // This is the trigraph ending the comment. Emit a stern warning!
Chris Lattner22eb9722006-06-18 05:43:12 +00001389 CurPtr -= 2;
1390
1391 // If no trigraphs are enabled, warn that we ignored this trigraph and
1392 // ignore this * character.
Chris Lattner1f583052006-06-18 06:53:56 +00001393 if (!L->getFeatures().Trigraphs) {
Chris Lattner6d27a162008-11-22 02:02:22 +00001394 if (!L->isLexingRawMode())
1395 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
Chris Lattnercb283342006-06-18 06:48:37 +00001396 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001397 }
Chris Lattner6d27a162008-11-22 02:02:22 +00001398 if (!L->isLexingRawMode())
1399 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +00001400 }
Mike Stump11289f42009-09-09 15:08:12 +00001401
Chris Lattner22eb9722006-06-18 05:43:12 +00001402 // Warn about having an escaped newline between the */ characters.
Chris Lattner6d27a162008-11-22 02:02:22 +00001403 if (!L->isLexingRawMode())
1404 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
Mike Stump11289f42009-09-09 15:08:12 +00001405
Chris Lattner22eb9722006-06-18 05:43:12 +00001406 // If there was space between the backslash and newline, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00001407 if (HasSpace && !L->isLexingRawMode())
1408 L->Diag(CurPtr, diag::backslash_newline_space);
Mike Stump11289f42009-09-09 15:08:12 +00001409
Chris Lattnercb283342006-06-18 06:48:37 +00001410 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001411}
1412
Chris Lattneraded4a92006-10-27 04:42:31 +00001413#ifdef __SSE2__
1414#include <emmintrin.h>
Chris Lattner9f6604f2006-10-30 20:01:22 +00001415#elif __ALTIVEC__
1416#include <altivec.h>
1417#undef bool
Chris Lattneraded4a92006-10-27 04:42:31 +00001418#endif
1419
Chris Lattner22eb9722006-06-18 05:43:12 +00001420/// SkipBlockComment - We have just read the /* characters from input. Read
1421/// until we find the */ characters that terminate the comment. Note that we
1422/// don't bother decoding trigraphs or escaped newlines in block comments,
1423/// because they cannot cause the comment to end. The only thing that can
1424/// happen is the comment could end with an escaped newline between the */ end
1425/// of comment.
Chris Lattnere01e7582008-10-12 04:15:42 +00001426///
Chris Lattner87d02082010-01-18 22:35:47 +00001427/// If we're in KeepCommentMode or any CommentHandler has inserted
1428/// some tokens, this will store the first token and return true.
Chris Lattner146762e2007-07-20 16:59:19 +00001429bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001430 // Scan one character past where we should, looking for a '/' character. Once
1431 // we find it, check to see if it was preceeded by a *. This common
1432 // optimization helps people who like to put a lot of * characters in their
1433 // comments.
Chris Lattnerc850ad62007-07-21 23:43:37 +00001434
1435 // The first character we get with newlines and trigraphs skipped to handle
1436 // the degenerate /*/ case below correctly if the * has an escaped newline
1437 // after it.
1438 unsigned CharSize;
1439 unsigned char C = getCharAndSize(CurPtr, CharSize);
1440 CurPtr += CharSize;
Chris Lattner22eb9722006-06-18 05:43:12 +00001441 if (C == 0 && CurPtr == BufferEnd+1) {
Chris Lattner561aabd2010-05-16 19:54:05 +00001442 if (!isLexingRawMode() &&
1443 !PP->isCodeCompletionFile(FileLoc))
Chris Lattner7c2e9802008-10-12 01:31:51 +00001444 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner99e7d232008-10-12 04:19:49 +00001445 --CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00001446
Chris Lattner99e7d232008-10-12 04:19:49 +00001447 // KeepWhitespaceMode should return this broken comment as a token. Since
1448 // it isn't a well formed comment, just return it as an 'unknown' token.
1449 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00001450 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner99e7d232008-10-12 04:19:49 +00001451 return true;
1452 }
Mike Stump11289f42009-09-09 15:08:12 +00001453
Chris Lattner99e7d232008-10-12 04:19:49 +00001454 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00001455 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001456 }
Mike Stump11289f42009-09-09 15:08:12 +00001457
Chris Lattnerc850ad62007-07-21 23:43:37 +00001458 // Check to see if the first character after the '/*' is another /. If so,
1459 // then this slash does not end the block comment, it is part of it.
1460 if (C == '/')
1461 C = *CurPtr++;
Mike Stump11289f42009-09-09 15:08:12 +00001462
Chris Lattner22eb9722006-06-18 05:43:12 +00001463 while (1) {
Chris Lattner6cc3e362006-10-27 04:12:35 +00001464 // Skip over all non-interesting characters until we find end of buffer or a
1465 // (probably ending) '/' character.
Chris Lattner6cc3e362006-10-27 04:12:35 +00001466 if (CurPtr + 24 < BufferEnd) {
1467 // While not aligned to a 16-byte boundary.
1468 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
1469 C = *CurPtr++;
Mike Stump11289f42009-09-09 15:08:12 +00001470
Chris Lattner6cc3e362006-10-27 04:12:35 +00001471 if (C == '/') goto FoundSlash;
Chris Lattneraded4a92006-10-27 04:42:31 +00001472
1473#ifdef __SSE2__
1474 __m128i Slashes = _mm_set_epi8('/', '/', '/', '/', '/', '/', '/', '/',
1475 '/', '/', '/', '/', '/', '/', '/', '/');
1476 while (CurPtr+16 <= BufferEnd &&
1477 _mm_movemask_epi8(_mm_cmpeq_epi8(*(__m128i*)CurPtr, Slashes)) == 0)
1478 CurPtr += 16;
Chris Lattner9f6604f2006-10-30 20:01:22 +00001479#elif __ALTIVEC__
1480 __vector unsigned char Slashes = {
Mike Stump11289f42009-09-09 15:08:12 +00001481 '/', '/', '/', '/', '/', '/', '/', '/',
Chris Lattner9f6604f2006-10-30 20:01:22 +00001482 '/', '/', '/', '/', '/', '/', '/', '/'
1483 };
1484 while (CurPtr+16 <= BufferEnd &&
1485 !vec_any_eq(*(vector unsigned char*)CurPtr, Slashes))
1486 CurPtr += 16;
Mike Stump11289f42009-09-09 15:08:12 +00001487#else
Chris Lattneraded4a92006-10-27 04:42:31 +00001488 // Scan for '/' quickly. Many block comments are very large.
Chris Lattner6cc3e362006-10-27 04:12:35 +00001489 while (CurPtr[0] != '/' &&
1490 CurPtr[1] != '/' &&
1491 CurPtr[2] != '/' &&
1492 CurPtr[3] != '/' &&
1493 CurPtr+4 < BufferEnd) {
1494 CurPtr += 4;
1495 }
Chris Lattneraded4a92006-10-27 04:42:31 +00001496#endif
Mike Stump11289f42009-09-09 15:08:12 +00001497
Chris Lattneraded4a92006-10-27 04:42:31 +00001498 // It has to be one of the bytes scanned, increment to it and read one.
Chris Lattner6cc3e362006-10-27 04:12:35 +00001499 C = *CurPtr++;
1500 }
Mike Stump11289f42009-09-09 15:08:12 +00001501
Chris Lattneraded4a92006-10-27 04:42:31 +00001502 // Loop to scan the remainder.
Chris Lattner22eb9722006-06-18 05:43:12 +00001503 while (C != '/' && C != '\0')
1504 C = *CurPtr++;
Mike Stump11289f42009-09-09 15:08:12 +00001505
Chris Lattner6cc3e362006-10-27 04:12:35 +00001506 FoundSlash:
Chris Lattner22eb9722006-06-18 05:43:12 +00001507 if (C == '/') {
Chris Lattner22eb9722006-06-18 05:43:12 +00001508 if (CurPtr[-2] == '*') // We found the final */. We're done!
1509 break;
Mike Stump11289f42009-09-09 15:08:12 +00001510
Chris Lattner22eb9722006-06-18 05:43:12 +00001511 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
Chris Lattner1f583052006-06-18 06:53:56 +00001512 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001513 // We found the final */, though it had an escaped newline between the
1514 // * and /. We're done!
1515 break;
1516 }
1517 }
1518 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
1519 // If this is a /* inside of the comment, emit a warning. Don't do this
1520 // if this is a /*/, which will end the comment. This misses cases with
1521 // embedded escaped newlines, but oh well.
Chris Lattner6d27a162008-11-22 02:02:22 +00001522 if (!isLexingRawMode())
1523 Diag(CurPtr-1, diag::warn_nested_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +00001524 }
1525 } else if (C == 0 && CurPtr == BufferEnd+1) {
Douglas Gregor11583702010-08-25 17:04:25 +00001526 if (PP && PP->isCodeCompletionFile(FileLoc))
1527 PP->CodeCompleteNaturalLanguage();
1528 else if (!isLexingRawMode())
Chris Lattner6d27a162008-11-22 02:02:22 +00001529 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +00001530 // Note: the user probably forgot a */. We could continue immediately
1531 // after the /*, but this would involve lexing a lot of what really is the
1532 // comment, which surely would confuse the parser.
Chris Lattner99e7d232008-10-12 04:19:49 +00001533 --CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00001534
Chris Lattner99e7d232008-10-12 04:19:49 +00001535 // KeepWhitespaceMode should return this broken comment as a token. Since
1536 // it isn't a well formed comment, just return it as an 'unknown' token.
1537 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00001538 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner99e7d232008-10-12 04:19:49 +00001539 return true;
1540 }
Mike Stump11289f42009-09-09 15:08:12 +00001541
Chris Lattner99e7d232008-10-12 04:19:49 +00001542 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00001543 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001544 }
1545 C = *CurPtr++;
1546 }
Mike Stump11289f42009-09-09 15:08:12 +00001547
Chris Lattner93ddf802010-02-03 21:06:21 +00001548 // Notify comment handlers about the comment unless we're in a #if 0 block.
1549 if (PP && !isLexingRawMode() &&
1550 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
1551 getSourceLocation(CurPtr)))) {
Chris Lattner87d02082010-01-18 22:35:47 +00001552 BufferPtr = CurPtr;
1553 return true; // A token has to be returned.
1554 }
Douglas Gregorc6d5edd2009-07-02 17:08:52 +00001555
Chris Lattner457fc152006-07-29 06:30:25 +00001556 // If we are returning comments as tokens, return this comment as a token.
Chris Lattner8637abd2008-10-12 03:22:02 +00001557 if (inKeepCommentMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00001558 FormTokenWithChars(Result, CurPtr, tok::comment);
Chris Lattnere01e7582008-10-12 04:15:42 +00001559 return true;
Chris Lattner457fc152006-07-29 06:30:25 +00001560 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001561
1562 // It is common for the tokens immediately after a /**/ comment to be
1563 // whitespace. Instead of going through the big switch, handle it
Chris Lattner4d963442008-10-12 04:05:48 +00001564 // efficiently now. This is safe even in KeepWhitespaceMode because we would
1565 // have already returned above with the comment as a token.
Chris Lattner22eb9722006-06-18 05:43:12 +00001566 if (isHorizontalWhitespace(*CurPtr)) {
Chris Lattner146762e2007-07-20 16:59:19 +00001567 Result.setFlag(Token::LeadingSpace);
Chris Lattner457fc152006-07-29 06:30:25 +00001568 SkipWhitespace(Result, CurPtr+1);
Chris Lattnere01e7582008-10-12 04:15:42 +00001569 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001570 }
1571
1572 // Otherwise, just return so that the next character will be lexed as a token.
1573 BufferPtr = CurPtr;
Chris Lattner146762e2007-07-20 16:59:19 +00001574 Result.setFlag(Token::LeadingSpace);
Chris Lattnere01e7582008-10-12 04:15:42 +00001575 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001576}
1577
1578//===----------------------------------------------------------------------===//
1579// Primary Lexing Entry Points
1580//===----------------------------------------------------------------------===//
1581
Chris Lattner22eb9722006-06-18 05:43:12 +00001582/// ReadToEndOfLine - Read the rest of the current preprocessor line as an
1583/// uninterpreted string. This switches the lexer out of directive mode.
1584std::string Lexer::ReadToEndOfLine() {
1585 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
1586 "Must be in a preprocessing directive!");
1587 std::string Result;
Chris Lattner146762e2007-07-20 16:59:19 +00001588 Token Tmp;
Chris Lattner22eb9722006-06-18 05:43:12 +00001589
1590 // CurPtr - Cache BufferPtr in an automatic variable.
1591 const char *CurPtr = BufferPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00001592 while (1) {
1593 char Char = getAndAdvanceChar(CurPtr, Tmp);
1594 switch (Char) {
1595 default:
1596 Result += Char;
1597 break;
1598 case 0: // Null.
1599 // Found end of file?
1600 if (CurPtr-1 != BufferEnd) {
1601 // Nope, normal character, continue.
1602 Result += Char;
1603 break;
1604 }
1605 // FALL THROUGH.
1606 case '\r':
1607 case '\n':
1608 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
1609 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
1610 BufferPtr = CurPtr-1;
Mike Stump11289f42009-09-09 15:08:12 +00001611
Chris Lattner22eb9722006-06-18 05:43:12 +00001612 // Next, lex the character, which should handle the EOM transition.
Chris Lattnercb283342006-06-18 06:48:37 +00001613 Lex(Tmp);
Douglas Gregor11583702010-08-25 17:04:25 +00001614 if (Tmp.is(tok::code_completion)) {
1615 if (PP && PP->getCodeCompletionHandler())
1616 PP->getCodeCompletionHandler()->CodeCompleteNaturalLanguage();
1617 Lex(Tmp);
1618 }
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001619 assert(Tmp.is(tok::eom) && "Unexpected token!");
Mike Stump11289f42009-09-09 15:08:12 +00001620
Chris Lattner22eb9722006-06-18 05:43:12 +00001621 // Finally, we're done, return the string we found.
1622 return Result;
1623 }
1624 }
1625}
1626
1627/// LexEndOfFile - CurPtr points to the end of this file. Handle this
1628/// condition, reporting diagnostics and handling other edge cases as required.
Chris Lattner2183a6e2006-07-18 06:36:12 +00001629/// This returns true if Result contains a token, false if PP.Lex should be
1630/// called again.
Chris Lattner146762e2007-07-20 16:59:19 +00001631bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
Douglas Gregor3a7ad252010-08-24 19:08:16 +00001632 // Check if we are performing code completion.
1633 if (PP && PP->isCodeCompletionFile(FileLoc)) {
1634 // We're at the end of the file, but we've been asked to consider the
1635 // end of the file to be a code-completion token. Return the
1636 // code-completion token.
1637 Result.startToken();
1638 FormTokenWithChars(Result, CurPtr, tok::code_completion);
1639
1640 // Only do the eof -> code_completion translation once.
1641 PP->SetCodeCompletionPoint(0, 0, 0);
1642
1643 // Silence any diagnostics that occur once we hit the code-completion point.
1644 PP->getDiagnostics().setSuppressAllDiagnostics(true);
1645 return true;
1646 }
1647
Chris Lattner22eb9722006-06-18 05:43:12 +00001648 // If we hit the end of the file while parsing a preprocessor directive,
1649 // end the preprocessor directive first. The next token returned will
1650 // then be the end of file.
1651 if (ParsingPreprocessorDirective) {
1652 // Done parsing the "line".
1653 ParsingPreprocessorDirective = false;
Chris Lattnerd01e2912006-06-18 16:22:51 +00001654 // Update the location of token as well as BufferPtr.
Chris Lattnerb11c3232008-10-12 04:51:35 +00001655 FormTokenWithChars(Result, CurPtr, tok::eom);
Mike Stump11289f42009-09-09 15:08:12 +00001656
Chris Lattner457fc152006-07-29 06:30:25 +00001657 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattner097a8b82008-10-12 03:27:19 +00001658 SetCommentRetentionState(PP->getCommentRetentionState());
Chris Lattner2183a6e2006-07-18 06:36:12 +00001659 return true; // Have a token.
Mike Stump11289f42009-09-09 15:08:12 +00001660 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00001661
Chris Lattner30a2fa12006-07-19 06:31:49 +00001662 // If we are in raw mode, return this event as an EOF token. Let the caller
1663 // that put us in raw mode handle the event.
Chris Lattner6d27a162008-11-22 02:02:22 +00001664 if (isLexingRawMode()) {
Chris Lattner8c204872006-10-14 05:19:21 +00001665 Result.startToken();
Chris Lattner30a2fa12006-07-19 06:31:49 +00001666 BufferPtr = BufferEnd;
Chris Lattnerb11c3232008-10-12 04:51:35 +00001667 FormTokenWithChars(Result, BufferEnd, tok::eof);
Chris Lattner30a2fa12006-07-19 06:31:49 +00001668 return true;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00001669 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00001670
Douglas Gregor3a7ad252010-08-24 19:08:16 +00001671 // Issue diagnostics for unterminated #if and missing newline.
1672
Chris Lattner30a2fa12006-07-19 06:31:49 +00001673 // If we are in a #if directive, emit an error.
1674 while (!ConditionalStack.empty()) {
Douglas Gregor02690ba2010-08-12 17:04:55 +00001675 if (!PP->isCodeCompletionFile(FileLoc))
1676 PP->Diag(ConditionalStack.back().IfLoc,
1677 diag::err_pp_unterminated_conditional);
Chris Lattner30a2fa12006-07-19 06:31:49 +00001678 ConditionalStack.pop_back();
1679 }
Mike Stump11289f42009-09-09 15:08:12 +00001680
Chris Lattner8f96d042008-04-12 05:54:25 +00001681 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
1682 // a pedwarn.
1683 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r'))
Mike Stump0be88752009-04-02 02:29:42 +00001684 Diag(BufferEnd, diag::ext_no_newline_eof)
Douglas Gregora771f462010-03-31 17:46:05 +00001685 << FixItHint::CreateInsertion(getSourceLocation(BufferEnd), "\n");
Mike Stump11289f42009-09-09 15:08:12 +00001686
Chris Lattner22eb9722006-06-18 05:43:12 +00001687 BufferPtr = CurPtr;
Chris Lattner30a2fa12006-07-19 06:31:49 +00001688
1689 // Finally, let the preprocessor handle this.
Chris Lattner02b436a2007-10-17 20:41:00 +00001690 return PP->HandleEndOfFile(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001691}
1692
Chris Lattner678c8802006-07-11 05:46:12 +00001693/// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
1694/// the specified lexer will return a tok::l_paren token, 0 if it is something
1695/// else and 2 if there are no more tokens in the buffer controlled by the
1696/// lexer.
1697unsigned Lexer::isNextPPTokenLParen() {
1698 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
Mike Stump11289f42009-09-09 15:08:12 +00001699
Chris Lattner678c8802006-07-11 05:46:12 +00001700 // Switch to 'skipping' mode. This will ensure that we can lex a token
1701 // without emitting diagnostics, disables macro expansion, and will cause EOF
1702 // to return an EOF token instead of popping the include stack.
1703 LexingRawMode = true;
Mike Stump11289f42009-09-09 15:08:12 +00001704
Chris Lattner678c8802006-07-11 05:46:12 +00001705 // Save state that can be changed while lexing so that we can restore it.
1706 const char *TmpBufferPtr = BufferPtr;
Chris Lattner40493eb2009-04-24 07:15:46 +00001707 bool inPPDirectiveMode = ParsingPreprocessorDirective;
Mike Stump11289f42009-09-09 15:08:12 +00001708
Chris Lattner146762e2007-07-20 16:59:19 +00001709 Token Tok;
Chris Lattner8c204872006-10-14 05:19:21 +00001710 Tok.startToken();
Chris Lattner678c8802006-07-11 05:46:12 +00001711 LexTokenInternal(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001712
Chris Lattner678c8802006-07-11 05:46:12 +00001713 // Restore state that may have changed.
1714 BufferPtr = TmpBufferPtr;
Chris Lattner40493eb2009-04-24 07:15:46 +00001715 ParsingPreprocessorDirective = inPPDirectiveMode;
Mike Stump11289f42009-09-09 15:08:12 +00001716
Chris Lattner678c8802006-07-11 05:46:12 +00001717 // Restore the lexer back to non-skipping mode.
1718 LexingRawMode = false;
Mike Stump11289f42009-09-09 15:08:12 +00001719
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001720 if (Tok.is(tok::eof))
Chris Lattner678c8802006-07-11 05:46:12 +00001721 return 2;
Chris Lattner98c1f7c2007-10-09 18:02:16 +00001722 return Tok.is(tok::l_paren);
Chris Lattner678c8802006-07-11 05:46:12 +00001723}
1724
Chris Lattner7c027ee2009-12-14 06:16:57 +00001725/// FindConflictEnd - Find the end of a version control conflict marker.
1726static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd) {
1727 llvm::StringRef RestOfBuffer(CurPtr+7, BufferEnd-CurPtr-7);
1728 size_t Pos = RestOfBuffer.find(">>>>>>>");
1729 while (Pos != llvm::StringRef::npos) {
1730 // Must occur at start of line.
1731 if (RestOfBuffer[Pos-1] != '\r' &&
1732 RestOfBuffer[Pos-1] != '\n') {
1733 RestOfBuffer = RestOfBuffer.substr(Pos+7);
Chris Lattner467f6bc2010-05-17 20:27:25 +00001734 Pos = RestOfBuffer.find(">>>>>>>");
Chris Lattner7c027ee2009-12-14 06:16:57 +00001735 continue;
1736 }
1737 return RestOfBuffer.data()+Pos;
1738 }
1739 return 0;
1740}
1741
1742/// IsStartOfConflictMarker - If the specified pointer is the start of a version
1743/// control conflict marker like '<<<<<<<', recognize it as such, emit an error
1744/// and recover nicely. This returns true if it is a conflict marker and false
1745/// if not.
1746bool Lexer::IsStartOfConflictMarker(const char *CurPtr) {
1747 // Only a conflict marker if it starts at the beginning of a line.
1748 if (CurPtr != BufferStart &&
1749 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
1750 return false;
1751
1752 // Check to see if we have <<<<<<<.
1753 if (BufferEnd-CurPtr < 8 ||
1754 llvm::StringRef(CurPtr, 7) != "<<<<<<<")
1755 return false;
1756
1757 // If we have a situation where we don't care about conflict markers, ignore
1758 // it.
1759 if (IsInConflictMarker || isLexingRawMode())
1760 return false;
1761
1762 // Check to see if there is a >>>>>>> somewhere in the buffer at the start of
1763 // a line to terminate this conflict marker.
Chris Lattner467f6bc2010-05-17 20:27:25 +00001764 if (FindConflictEnd(CurPtr, BufferEnd)) {
Chris Lattner7c027ee2009-12-14 06:16:57 +00001765 // We found a match. We are really in a conflict marker.
1766 // Diagnose this, and ignore to the end of line.
1767 Diag(CurPtr, diag::err_conflict_marker);
1768 IsInConflictMarker = true;
1769
1770 // Skip ahead to the end of line. We know this exists because the
1771 // end-of-conflict marker starts with \r or \n.
1772 while (*CurPtr != '\r' && *CurPtr != '\n') {
1773 assert(CurPtr != BufferEnd && "Didn't find end of line");
1774 ++CurPtr;
1775 }
1776 BufferPtr = CurPtr;
1777 return true;
1778 }
1779
1780 // No end of conflict marker found.
1781 return false;
1782}
1783
1784
1785/// HandleEndOfConflictMarker - If this is a '=======' or '|||||||' or '>>>>>>>'
1786/// marker, then it is the end of a conflict marker. Handle it by ignoring up
1787/// until the end of the line. This returns true if it is a conflict marker and
1788/// false if not.
1789bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) {
1790 // Only a conflict marker if it starts at the beginning of a line.
1791 if (CurPtr != BufferStart &&
1792 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
1793 return false;
1794
1795 // If we have a situation where we don't care about conflict markers, ignore
1796 // it.
1797 if (!IsInConflictMarker || isLexingRawMode())
1798 return false;
1799
1800 // Check to see if we have the marker (7 characters in a row).
1801 for (unsigned i = 1; i != 7; ++i)
1802 if (CurPtr[i] != CurPtr[0])
1803 return false;
1804
1805 // If we do have it, search for the end of the conflict marker. This could
1806 // fail if it got skipped with a '#if 0' or something. Note that CurPtr might
1807 // be the end of conflict marker.
1808 if (const char *End = FindConflictEnd(CurPtr, BufferEnd)) {
1809 CurPtr = End;
1810
1811 // Skip ahead to the end of line.
1812 while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n')
1813 ++CurPtr;
1814
1815 BufferPtr = CurPtr;
1816
1817 // No longer in the conflict marker.
1818 IsInConflictMarker = false;
1819 return true;
1820 }
1821
1822 return false;
1823}
1824
Chris Lattner22eb9722006-06-18 05:43:12 +00001825
1826/// LexTokenInternal - This implements a simple C family lexer. It is an
1827/// extremely performance critical piece of code. This assumes that the buffer
Chris Lattner5c349382009-07-07 05:05:42 +00001828/// has a null character at the end of the file. This returns a preprocessing
1829/// token, not a normal token, as such, it is an internal interface. It assumes
1830/// that the Flags of result have been cleared before calling this.
Chris Lattner146762e2007-07-20 16:59:19 +00001831void Lexer::LexTokenInternal(Token &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001832LexNextToken:
1833 // New token, can't need cleaning yet.
Chris Lattner146762e2007-07-20 16:59:19 +00001834 Result.clearFlag(Token::NeedsCleaning);
Chris Lattner8c204872006-10-14 05:19:21 +00001835 Result.setIdentifierInfo(0);
Mike Stump11289f42009-09-09 15:08:12 +00001836
Chris Lattner22eb9722006-06-18 05:43:12 +00001837 // CurPtr - Cache BufferPtr in an automatic variable.
1838 const char *CurPtr = BufferPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00001839
Chris Lattnereb54b592006-07-10 06:34:27 +00001840 // Small amounts of horizontal whitespace is very common between tokens.
1841 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
1842 ++CurPtr;
1843 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
1844 ++CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00001845
Chris Lattner4d963442008-10-12 04:05:48 +00001846 // If we are keeping whitespace and other tokens, just return what we just
1847 // skipped. The next lexer invocation will return the token after the
1848 // whitespace.
1849 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00001850 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner4d963442008-10-12 04:05:48 +00001851 return;
1852 }
Mike Stump11289f42009-09-09 15:08:12 +00001853
Chris Lattnereb54b592006-07-10 06:34:27 +00001854 BufferPtr = CurPtr;
Chris Lattner146762e2007-07-20 16:59:19 +00001855 Result.setFlag(Token::LeadingSpace);
Chris Lattnereb54b592006-07-10 06:34:27 +00001856 }
Mike Stump11289f42009-09-09 15:08:12 +00001857
Chris Lattner22eb9722006-06-18 05:43:12 +00001858 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
Mike Stump11289f42009-09-09 15:08:12 +00001859
Chris Lattner22eb9722006-06-18 05:43:12 +00001860 // Read a character, advancing over it.
1861 char Char = getAndAdvanceChar(CurPtr, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00001862 tok::TokenKind Kind;
Mike Stump11289f42009-09-09 15:08:12 +00001863
Chris Lattner22eb9722006-06-18 05:43:12 +00001864 switch (Char) {
1865 case 0: // Null.
1866 // Found end of file?
Chris Lattner2183a6e2006-07-18 06:36:12 +00001867 if (CurPtr-1 == BufferEnd) {
1868 // Read the PP instance variable into an automatic variable, because
1869 // LexEndOfFile will often delete 'this'.
Chris Lattner02b436a2007-10-17 20:41:00 +00001870 Preprocessor *PPCache = PP;
Chris Lattner2183a6e2006-07-18 06:36:12 +00001871 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
1872 return; // Got a token to return.
Chris Lattner02b436a2007-10-17 20:41:00 +00001873 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
1874 return PPCache->Lex(Result);
Chris Lattner2183a6e2006-07-18 06:36:12 +00001875 }
Mike Stump11289f42009-09-09 15:08:12 +00001876
Chris Lattner6d27a162008-11-22 02:02:22 +00001877 if (!isLexingRawMode())
1878 Diag(CurPtr-1, diag::null_in_file);
Chris Lattner146762e2007-07-20 16:59:19 +00001879 Result.setFlag(Token::LeadingSpace);
Chris Lattner4d963442008-10-12 04:05:48 +00001880 if (SkipWhitespace(Result, CurPtr))
1881 return; // KeepWhitespaceMode
Mike Stump11289f42009-09-09 15:08:12 +00001882
Chris Lattner22eb9722006-06-18 05:43:12 +00001883 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattner3dfff972009-12-17 05:29:40 +00001884
1885 case 26: // DOS & CP/M EOF: "^Z".
1886 // If we're in Microsoft extensions mode, treat this as end of file.
1887 if (Features.Microsoft) {
1888 // Read the PP instance variable into an automatic variable, because
1889 // LexEndOfFile will often delete 'this'.
1890 Preprocessor *PPCache = PP;
1891 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
1892 return; // Got a token to return.
1893 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
1894 return PPCache->Lex(Result);
1895 }
1896 // If Microsoft extensions are disabled, this is just random garbage.
1897 Kind = tok::unknown;
1898 break;
1899
Chris Lattner22eb9722006-06-18 05:43:12 +00001900 case '\n':
1901 case '\r':
1902 // If we are inside a preprocessor directive and we see the end of line,
1903 // we know we are done with the directive, so return an EOM token.
1904 if (ParsingPreprocessorDirective) {
1905 // Done parsing the "line".
1906 ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +00001907
Chris Lattner457fc152006-07-29 06:30:25 +00001908 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattner097a8b82008-10-12 03:27:19 +00001909 SetCommentRetentionState(PP->getCommentRetentionState());
Mike Stump11289f42009-09-09 15:08:12 +00001910
Chris Lattner22eb9722006-06-18 05:43:12 +00001911 // Since we consumed a newline, we are back at the start of a line.
1912 IsAtStartOfLine = true;
Mike Stump11289f42009-09-09 15:08:12 +00001913
Chris Lattnerb11c3232008-10-12 04:51:35 +00001914 Kind = tok::eom;
Chris Lattner22eb9722006-06-18 05:43:12 +00001915 break;
1916 }
1917 // The returned token is at the start of the line.
Chris Lattner146762e2007-07-20 16:59:19 +00001918 Result.setFlag(Token::StartOfLine);
Chris Lattner22eb9722006-06-18 05:43:12 +00001919 // No leading whitespace seen so far.
Chris Lattner146762e2007-07-20 16:59:19 +00001920 Result.clearFlag(Token::LeadingSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001921
Chris Lattner4d963442008-10-12 04:05:48 +00001922 if (SkipWhitespace(Result, CurPtr))
1923 return; // KeepWhitespaceMode
Chris Lattner22eb9722006-06-18 05:43:12 +00001924 goto LexNextToken; // GCC isn't tail call eliminating.
1925 case ' ':
1926 case '\t':
1927 case '\f':
1928 case '\v':
Chris Lattnerb9b85972007-07-22 06:29:05 +00001929 SkipHorizontalWhitespace:
Chris Lattner146762e2007-07-20 16:59:19 +00001930 Result.setFlag(Token::LeadingSpace);
Chris Lattner4d963442008-10-12 04:05:48 +00001931 if (SkipWhitespace(Result, CurPtr))
1932 return; // KeepWhitespaceMode
Chris Lattnerb9b85972007-07-22 06:29:05 +00001933
1934 SkipIgnoredUnits:
1935 CurPtr = BufferPtr;
Mike Stump11289f42009-09-09 15:08:12 +00001936
Chris Lattnerb9b85972007-07-22 06:29:05 +00001937 // If the next token is obviously a // or /* */ comment, skip it efficiently
1938 // too (without going through the big switch stmt).
Chris Lattner58827712009-01-16 22:39:25 +00001939 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
1940 Features.BCPLComment) {
Chris Lattner87d02082010-01-18 22:35:47 +00001941 if (SkipBCPLComment(Result, CurPtr+2))
1942 return; // There is a token to return.
Chris Lattnerb9b85972007-07-22 06:29:05 +00001943 goto SkipIgnoredUnits;
Chris Lattner8637abd2008-10-12 03:22:02 +00001944 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
Chris Lattner87d02082010-01-18 22:35:47 +00001945 if (SkipBlockComment(Result, CurPtr+2))
1946 return; // There is a token to return.
Chris Lattnerb9b85972007-07-22 06:29:05 +00001947 goto SkipIgnoredUnits;
1948 } else if (isHorizontalWhitespace(*CurPtr)) {
1949 goto SkipHorizontalWhitespace;
1950 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001951 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattner3dfff972009-12-17 05:29:40 +00001952
Chris Lattner2b15cf72008-01-03 17:58:54 +00001953 // C99 6.4.4.1: Integer Constants.
1954 // C99 6.4.4.2: Floating Constants.
1955 case '0': case '1': case '2': case '3': case '4':
1956 case '5': case '6': case '7': case '8': case '9':
1957 // Notify MIOpt that we read a non-whitespace/non-comment token.
1958 MIOpt.ReadToken();
1959 return LexNumericConstant(Result, CurPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001960
Chris Lattner2b15cf72008-01-03 17:58:54 +00001961 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
Chris Lattner371ac8a2006-07-04 07:11:10 +00001962 // Notify MIOpt that we read a non-whitespace/non-comment token.
1963 MIOpt.ReadToken();
Chris Lattner22eb9722006-06-18 05:43:12 +00001964 Char = getCharAndSize(CurPtr, SizeTmp);
1965
1966 // Wide string literal.
1967 if (Char == '"')
Chris Lattnerd3e98952006-10-06 05:22:26 +00001968 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
1969 true);
Chris Lattner22eb9722006-06-18 05:43:12 +00001970
1971 // Wide character constant.
1972 if (Char == '\'')
1973 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
1974 // FALL THROUGH, treating L like the start of an identifier.
Mike Stump11289f42009-09-09 15:08:12 +00001975
Chris Lattner22eb9722006-06-18 05:43:12 +00001976 // C99 6.4.2: Identifiers.
1977 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
1978 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
1979 case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U':
1980 case 'V': case 'W': case 'X': case 'Y': case 'Z':
1981 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
1982 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
1983 case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u':
1984 case 'v': case 'w': case 'x': case 'y': case 'z':
1985 case '_':
Chris Lattner371ac8a2006-07-04 07:11:10 +00001986 // Notify MIOpt that we read a non-whitespace/non-comment token.
1987 MIOpt.ReadToken();
Chris Lattner22eb9722006-06-18 05:43:12 +00001988 return LexIdentifier(Result, CurPtr);
Chris Lattner2b15cf72008-01-03 17:58:54 +00001989
1990 case '$': // $ in identifiers.
1991 if (Features.DollarIdents) {
Chris Lattner6d27a162008-11-22 02:02:22 +00001992 if (!isLexingRawMode())
1993 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
Chris Lattner2b15cf72008-01-03 17:58:54 +00001994 // Notify MIOpt that we read a non-whitespace/non-comment token.
1995 MIOpt.ReadToken();
1996 return LexIdentifier(Result, CurPtr);
1997 }
Mike Stump11289f42009-09-09 15:08:12 +00001998
Chris Lattnerb11c3232008-10-12 04:51:35 +00001999 Kind = tok::unknown;
Chris Lattner2b15cf72008-01-03 17:58:54 +00002000 break;
Mike Stump11289f42009-09-09 15:08:12 +00002001
Chris Lattner22eb9722006-06-18 05:43:12 +00002002 // C99 6.4.4: Character Constants.
2003 case '\'':
Chris Lattner371ac8a2006-07-04 07:11:10 +00002004 // Notify MIOpt that we read a non-whitespace/non-comment token.
2005 MIOpt.ReadToken();
Chris Lattner22eb9722006-06-18 05:43:12 +00002006 return LexCharConstant(Result, CurPtr);
2007
2008 // C99 6.4.5: String Literals.
2009 case '"':
Chris Lattner371ac8a2006-07-04 07:11:10 +00002010 // Notify MIOpt that we read a non-whitespace/non-comment token.
2011 MIOpt.ReadToken();
Chris Lattnerd3e98952006-10-06 05:22:26 +00002012 return LexStringLiteral(Result, CurPtr, false);
Chris Lattner22eb9722006-06-18 05:43:12 +00002013
2014 // C99 6.4.6: Punctuators.
2015 case '?':
Chris Lattnerb11c3232008-10-12 04:51:35 +00002016 Kind = tok::question;
Chris Lattner22eb9722006-06-18 05:43:12 +00002017 break;
2018 case '[':
Chris Lattnerb11c3232008-10-12 04:51:35 +00002019 Kind = tok::l_square;
Chris Lattner22eb9722006-06-18 05:43:12 +00002020 break;
2021 case ']':
Chris Lattnerb11c3232008-10-12 04:51:35 +00002022 Kind = tok::r_square;
Chris Lattner22eb9722006-06-18 05:43:12 +00002023 break;
2024 case '(':
Chris Lattnerb11c3232008-10-12 04:51:35 +00002025 Kind = tok::l_paren;
Chris Lattner22eb9722006-06-18 05:43:12 +00002026 break;
2027 case ')':
Chris Lattnerb11c3232008-10-12 04:51:35 +00002028 Kind = tok::r_paren;
Chris Lattner22eb9722006-06-18 05:43:12 +00002029 break;
2030 case '{':
Chris Lattnerb11c3232008-10-12 04:51:35 +00002031 Kind = tok::l_brace;
Chris Lattner22eb9722006-06-18 05:43:12 +00002032 break;
2033 case '}':
Chris Lattnerb11c3232008-10-12 04:51:35 +00002034 Kind = tok::r_brace;
Chris Lattner22eb9722006-06-18 05:43:12 +00002035 break;
2036 case '.':
2037 Char = getCharAndSize(CurPtr, SizeTmp);
2038 if (Char >= '0' && Char <= '9') {
Chris Lattner371ac8a2006-07-04 07:11:10 +00002039 // Notify MIOpt that we read a non-whitespace/non-comment token.
2040 MIOpt.ReadToken();
2041
Chris Lattner22eb9722006-06-18 05:43:12 +00002042 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
2043 } else if (Features.CPlusPlus && Char == '*') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002044 Kind = tok::periodstar;
Chris Lattner22eb9722006-06-18 05:43:12 +00002045 CurPtr += SizeTmp;
2046 } else if (Char == '.' &&
2047 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002048 Kind = tok::ellipsis;
Chris Lattner22eb9722006-06-18 05:43:12 +00002049 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2050 SizeTmp2, Result);
2051 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002052 Kind = tok::period;
Chris Lattner22eb9722006-06-18 05:43:12 +00002053 }
2054 break;
2055 case '&':
2056 Char = getCharAndSize(CurPtr, SizeTmp);
2057 if (Char == '&') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002058 Kind = tok::ampamp;
Chris Lattner22eb9722006-06-18 05:43:12 +00002059 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2060 } else if (Char == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002061 Kind = tok::ampequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00002062 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2063 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002064 Kind = tok::amp;
Chris Lattner22eb9722006-06-18 05:43:12 +00002065 }
2066 break;
Mike Stump11289f42009-09-09 15:08:12 +00002067 case '*':
Chris Lattner22eb9722006-06-18 05:43:12 +00002068 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002069 Kind = tok::starequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00002070 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2071 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002072 Kind = tok::star;
Chris Lattner22eb9722006-06-18 05:43:12 +00002073 }
2074 break;
2075 case '+':
2076 Char = getCharAndSize(CurPtr, SizeTmp);
2077 if (Char == '+') {
Chris Lattner22eb9722006-06-18 05:43:12 +00002078 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00002079 Kind = tok::plusplus;
Chris Lattner22eb9722006-06-18 05:43:12 +00002080 } else if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00002081 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00002082 Kind = tok::plusequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00002083 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002084 Kind = tok::plus;
Chris Lattner22eb9722006-06-18 05:43:12 +00002085 }
2086 break;
2087 case '-':
2088 Char = getCharAndSize(CurPtr, SizeTmp);
Chris Lattnerb11c3232008-10-12 04:51:35 +00002089 if (Char == '-') { // --
Chris Lattner22eb9722006-06-18 05:43:12 +00002090 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00002091 Kind = tok::minusminus;
Mike Stump11289f42009-09-09 15:08:12 +00002092 } else if (Char == '>' && Features.CPlusPlus &&
Chris Lattnerb11c3232008-10-12 04:51:35 +00002093 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
Chris Lattner22eb9722006-06-18 05:43:12 +00002094 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2095 SizeTmp2, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00002096 Kind = tok::arrowstar;
2097 } else if (Char == '>') { // ->
Chris Lattner22eb9722006-06-18 05:43:12 +00002098 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00002099 Kind = tok::arrow;
2100 } else if (Char == '=') { // -=
Chris Lattner22eb9722006-06-18 05:43:12 +00002101 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00002102 Kind = tok::minusequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00002103 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002104 Kind = tok::minus;
Chris Lattner22eb9722006-06-18 05:43:12 +00002105 }
2106 break;
2107 case '~':
Chris Lattnerb11c3232008-10-12 04:51:35 +00002108 Kind = tok::tilde;
Chris Lattner22eb9722006-06-18 05:43:12 +00002109 break;
2110 case '!':
2111 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002112 Kind = tok::exclaimequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00002113 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2114 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002115 Kind = tok::exclaim;
Chris Lattner22eb9722006-06-18 05:43:12 +00002116 }
2117 break;
2118 case '/':
2119 // 6.4.9: Comments
2120 Char = getCharAndSize(CurPtr, SizeTmp);
2121 if (Char == '/') { // BCPL comment.
Chris Lattner58827712009-01-16 22:39:25 +00002122 // Even if BCPL comments are disabled (e.g. in C89 mode), we generally
2123 // want to lex this as a comment. There is one problem with this though,
2124 // that in one particular corner case, this can change the behavior of the
2125 // resultant program. For example, In "foo //**/ bar", C89 would lex
2126 // this as "foo / bar" and langauges with BCPL comments would lex it as
2127 // "foo". Check to see if the character after the second slash is a '*'.
2128 // If so, we will lex that as a "/" instead of the start of a comment.
2129 if (Features.BCPLComment ||
2130 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*') {
2131 if (SkipBCPLComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattner87d02082010-01-18 22:35:47 +00002132 return; // There is a token to return.
Mike Stump11289f42009-09-09 15:08:12 +00002133
Chris Lattner58827712009-01-16 22:39:25 +00002134 // It is common for the tokens immediately after a // comment to be
2135 // whitespace (indentation for the next line). Instead of going through
2136 // the big switch, handle it efficiently now.
2137 goto SkipIgnoredUnits;
2138 }
2139 }
Mike Stump11289f42009-09-09 15:08:12 +00002140
Chris Lattner58827712009-01-16 22:39:25 +00002141 if (Char == '*') { // /**/ comment.
Chris Lattner457fc152006-07-29 06:30:25 +00002142 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattner87d02082010-01-18 22:35:47 +00002143 return; // There is a token to return.
Chris Lattnere01e7582008-10-12 04:15:42 +00002144 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattner58827712009-01-16 22:39:25 +00002145 }
Mike Stump11289f42009-09-09 15:08:12 +00002146
Chris Lattner58827712009-01-16 22:39:25 +00002147 if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00002148 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00002149 Kind = tok::slashequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00002150 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002151 Kind = tok::slash;
Chris Lattner22eb9722006-06-18 05:43:12 +00002152 }
2153 break;
2154 case '%':
2155 Char = getCharAndSize(CurPtr, SizeTmp);
2156 if (Char == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002157 Kind = tok::percentequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00002158 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2159 } else if (Features.Digraphs && Char == '>') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002160 Kind = tok::r_brace; // '%>' -> '}'
Chris Lattner22eb9722006-06-18 05:43:12 +00002161 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2162 } else if (Features.Digraphs && Char == ':') {
2163 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner2b271db2006-07-15 05:41:09 +00002164 Char = getCharAndSize(CurPtr, SizeTmp);
2165 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002166 Kind = tok::hashhash; // '%:%:' -> '##'
Chris Lattner22eb9722006-06-18 05:43:12 +00002167 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2168 SizeTmp2, Result);
Chris Lattner2b271db2006-07-15 05:41:09 +00002169 } else if (Char == '@' && Features.Microsoft) { // %:@ -> #@ -> Charize
Chris Lattner2b271db2006-07-15 05:41:09 +00002170 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner6d27a162008-11-22 02:02:22 +00002171 if (!isLexingRawMode())
2172 Diag(BufferPtr, diag::charize_microsoft_ext);
Chris Lattnerb11c3232008-10-12 04:51:35 +00002173 Kind = tok::hashat;
Chris Lattner2534324a2009-03-18 20:58:27 +00002174 } else { // '%:' -> '#'
Chris Lattner22eb9722006-06-18 05:43:12 +00002175 // We parsed a # character. If this occurs at the start of the line,
2176 // it's actually the start of a preprocessing directive. Callback to
2177 // the preprocessor to handle it.
2178 // FIXME: -fpreprocessed mode??
Chris Lattnerff96dd02009-05-13 06:10:29 +00002179 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer) {
Chris Lattner2534324a2009-03-18 20:58:27 +00002180 FormTokenWithChars(Result, CurPtr, tok::hash);
Chris Lattner02b436a2007-10-17 20:41:00 +00002181 PP->HandleDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +00002182
Chris Lattner22eb9722006-06-18 05:43:12 +00002183 // As an optimization, if the preprocessor didn't switch lexers, tail
2184 // recurse.
Chris Lattner02b436a2007-10-17 20:41:00 +00002185 if (PP->isCurrentLexer(this)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002186 // Start a new token. If this is a #include or something, the PP may
2187 // want us starting at the beginning of the line again. If so, set
Chris Lattner1a9e8732010-04-12 23:04:41 +00002188 // the StartOfLine flag and clear LeadingSpace.
Chris Lattner22eb9722006-06-18 05:43:12 +00002189 if (IsAtStartOfLine) {
Chris Lattner146762e2007-07-20 16:59:19 +00002190 Result.setFlag(Token::StartOfLine);
Chris Lattner1a9e8732010-04-12 23:04:41 +00002191 Result.clearFlag(Token::LeadingSpace);
Chris Lattner22eb9722006-06-18 05:43:12 +00002192 IsAtStartOfLine = false;
2193 }
2194 goto LexNextToken; // GCC isn't tail call eliminating.
2195 }
Mike Stump11289f42009-09-09 15:08:12 +00002196
Chris Lattner02b436a2007-10-17 20:41:00 +00002197 return PP->Lex(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00002198 }
Mike Stump11289f42009-09-09 15:08:12 +00002199
Chris Lattner2534324a2009-03-18 20:58:27 +00002200 Kind = tok::hash;
Chris Lattner22eb9722006-06-18 05:43:12 +00002201 }
2202 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002203 Kind = tok::percent;
Chris Lattner22eb9722006-06-18 05:43:12 +00002204 }
2205 break;
2206 case '<':
2207 Char = getCharAndSize(CurPtr, SizeTmp);
2208 if (ParsingFilename) {
Chris Lattnerb40289b2009-04-17 23:56:52 +00002209 return LexAngledStringLiteral(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +00002210 } else if (Char == '<') {
Chris Lattner7c027ee2009-12-14 06:16:57 +00002211 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
2212 if (After == '=') {
2213 Kind = tok::lesslessequal;
2214 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2215 SizeTmp2, Result);
2216 } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) {
2217 // If this is actually a '<<<<<<<' version control conflict marker,
2218 // recognize it as such and recover nicely.
2219 goto LexNextToken;
2220 } else {
2221 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2222 Kind = tok::lessless;
2223 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002224 } else if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00002225 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00002226 Kind = tok::lessequal;
2227 } else if (Features.Digraphs && Char == ':') { // '<:' -> '['
Chris Lattner22eb9722006-06-18 05:43:12 +00002228 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00002229 Kind = tok::l_square;
2230 } else if (Features.Digraphs && Char == '%') { // '<%' -> '{'
Chris Lattner22eb9722006-06-18 05:43:12 +00002231 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00002232 Kind = tok::l_brace;
Chris Lattner22eb9722006-06-18 05:43:12 +00002233 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002234 Kind = tok::less;
Chris Lattner22eb9722006-06-18 05:43:12 +00002235 }
2236 break;
2237 case '>':
2238 Char = getCharAndSize(CurPtr, SizeTmp);
2239 if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00002240 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00002241 Kind = tok::greaterequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00002242 } else if (Char == '>') {
Chris Lattner7c027ee2009-12-14 06:16:57 +00002243 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
2244 if (After == '=') {
2245 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2246 SizeTmp2, Result);
2247 Kind = tok::greatergreaterequal;
2248 } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) {
2249 // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
2250 goto LexNextToken;
2251 } else {
2252 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2253 Kind = tok::greatergreater;
2254 }
2255
Chris Lattner22eb9722006-06-18 05:43:12 +00002256 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002257 Kind = tok::greater;
Chris Lattner22eb9722006-06-18 05:43:12 +00002258 }
2259 break;
2260 case '^':
2261 Char = getCharAndSize(CurPtr, SizeTmp);
2262 if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00002263 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00002264 Kind = tok::caretequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00002265 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002266 Kind = tok::caret;
Chris Lattner22eb9722006-06-18 05:43:12 +00002267 }
2268 break;
2269 case '|':
2270 Char = getCharAndSize(CurPtr, SizeTmp);
2271 if (Char == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002272 Kind = tok::pipeequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00002273 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2274 } else if (Char == '|') {
Chris Lattner7c027ee2009-12-14 06:16:57 +00002275 // If this is '|||||||' and we're in a conflict marker, ignore it.
2276 if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
2277 goto LexNextToken;
Chris Lattnerb11c3232008-10-12 04:51:35 +00002278 Kind = tok::pipepipe;
Chris Lattner22eb9722006-06-18 05:43:12 +00002279 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2280 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002281 Kind = tok::pipe;
Chris Lattner22eb9722006-06-18 05:43:12 +00002282 }
2283 break;
2284 case ':':
2285 Char = getCharAndSize(CurPtr, SizeTmp);
2286 if (Features.Digraphs && Char == '>') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002287 Kind = tok::r_square; // ':>' -> ']'
Chris Lattner22eb9722006-06-18 05:43:12 +00002288 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2289 } else if (Features.CPlusPlus && Char == ':') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002290 Kind = tok::coloncolon;
Chris Lattner22eb9722006-06-18 05:43:12 +00002291 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump11289f42009-09-09 15:08:12 +00002292 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002293 Kind = tok::colon;
Chris Lattner22eb9722006-06-18 05:43:12 +00002294 }
2295 break;
2296 case ';':
Chris Lattnerb11c3232008-10-12 04:51:35 +00002297 Kind = tok::semi;
Chris Lattner22eb9722006-06-18 05:43:12 +00002298 break;
2299 case '=':
2300 Char = getCharAndSize(CurPtr, SizeTmp);
2301 if (Char == '=') {
Chris Lattner7c027ee2009-12-14 06:16:57 +00002302 // If this is '=======' and we're in a conflict marker, ignore it.
2303 if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
2304 goto LexNextToken;
2305
Chris Lattnerb11c3232008-10-12 04:51:35 +00002306 Kind = tok::equalequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00002307 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump11289f42009-09-09 15:08:12 +00002308 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002309 Kind = tok::equal;
Chris Lattner22eb9722006-06-18 05:43:12 +00002310 }
2311 break;
2312 case ',':
Chris Lattnerb11c3232008-10-12 04:51:35 +00002313 Kind = tok::comma;
Chris Lattner22eb9722006-06-18 05:43:12 +00002314 break;
2315 case '#':
2316 Char = getCharAndSize(CurPtr, SizeTmp);
2317 if (Char == '#') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002318 Kind = tok::hashhash;
Chris Lattner22eb9722006-06-18 05:43:12 +00002319 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner2b271db2006-07-15 05:41:09 +00002320 } else if (Char == '@' && Features.Microsoft) { // #@ -> Charize
Chris Lattnerb11c3232008-10-12 04:51:35 +00002321 Kind = tok::hashat;
Chris Lattner6d27a162008-11-22 02:02:22 +00002322 if (!isLexingRawMode())
2323 Diag(BufferPtr, diag::charize_microsoft_ext);
Chris Lattner2b271db2006-07-15 05:41:09 +00002324 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00002325 } else {
Chris Lattner22eb9722006-06-18 05:43:12 +00002326 // We parsed a # character. If this occurs at the start of the line,
2327 // it's actually the start of a preprocessing directive. Callback to
2328 // the preprocessor to handle it.
Chris Lattner505c5472006-07-03 00:55:48 +00002329 // FIXME: -fpreprocessed mode??
Chris Lattnerff96dd02009-05-13 06:10:29 +00002330 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer) {
Chris Lattner2534324a2009-03-18 20:58:27 +00002331 FormTokenWithChars(Result, CurPtr, tok::hash);
Chris Lattner02b436a2007-10-17 20:41:00 +00002332 PP->HandleDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +00002333
Chris Lattner22eb9722006-06-18 05:43:12 +00002334 // As an optimization, if the preprocessor didn't switch lexers, tail
2335 // recurse.
Chris Lattner02b436a2007-10-17 20:41:00 +00002336 if (PP->isCurrentLexer(this)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002337 // Start a new token. If this is a #include or something, the PP may
2338 // want us starting at the beginning of the line again. If so, set
Chris Lattner1a9e8732010-04-12 23:04:41 +00002339 // the StartOfLine flag and clear LeadingSpace.
Chris Lattner22eb9722006-06-18 05:43:12 +00002340 if (IsAtStartOfLine) {
Chris Lattner146762e2007-07-20 16:59:19 +00002341 Result.setFlag(Token::StartOfLine);
Chris Lattner1a9e8732010-04-12 23:04:41 +00002342 Result.clearFlag(Token::LeadingSpace);
Chris Lattner22eb9722006-06-18 05:43:12 +00002343 IsAtStartOfLine = false;
2344 }
2345 goto LexNextToken; // GCC isn't tail call eliminating.
2346 }
Chris Lattner02b436a2007-10-17 20:41:00 +00002347 return PP->Lex(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00002348 }
Mike Stump11289f42009-09-09 15:08:12 +00002349
Chris Lattner2534324a2009-03-18 20:58:27 +00002350 Kind = tok::hash;
Chris Lattner22eb9722006-06-18 05:43:12 +00002351 }
2352 break;
2353
Chris Lattner2b15cf72008-01-03 17:58:54 +00002354 case '@':
2355 // Objective C support.
2356 if (CurPtr[-1] == '@' && Features.ObjC1)
Chris Lattnerb11c3232008-10-12 04:51:35 +00002357 Kind = tok::at;
Chris Lattner2b15cf72008-01-03 17:58:54 +00002358 else
Chris Lattnerb11c3232008-10-12 04:51:35 +00002359 Kind = tok::unknown;
Chris Lattner2b15cf72008-01-03 17:58:54 +00002360 break;
Mike Stump11289f42009-09-09 15:08:12 +00002361
Chris Lattner22eb9722006-06-18 05:43:12 +00002362 case '\\':
Chris Lattner505c5472006-07-03 00:55:48 +00002363 // FIXME: UCN's.
Chris Lattner22eb9722006-06-18 05:43:12 +00002364 // FALL THROUGH.
2365 default:
Chris Lattnerb11c3232008-10-12 04:51:35 +00002366 Kind = tok::unknown;
Chris Lattner041bef82006-07-11 05:52:53 +00002367 break;
Chris Lattner22eb9722006-06-18 05:43:12 +00002368 }
Mike Stump11289f42009-09-09 15:08:12 +00002369
Chris Lattner371ac8a2006-07-04 07:11:10 +00002370 // Notify MIOpt that we read a non-whitespace/non-comment token.
2371 MIOpt.ReadToken();
2372
Chris Lattnerd01e2912006-06-18 16:22:51 +00002373 // Update the location of token as well as BufferPtr.
Chris Lattnerb11c3232008-10-12 04:51:35 +00002374 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner22eb9722006-06-18 05:43:12 +00002375}