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