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