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