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