blob: cc45e1224a68a95bbe4b08c4ac9137adf1e888f9 [file] [log] [blame]
Chris Lattner22eb9722006-06-18 05:43:12 +00001//===--- Lexer.cpp - C Language Family Lexer ------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Lexer and LexerToken interfaces.
11//
12//===----------------------------------------------------------------------===//
13//
14// TODO: GCC Diagnostics emitted by the lexer:
15// PEDWARN: (form feed|vertical tab) in preprocessing directive
16//
17// Universal characters, unicode, char mapping:
18// WARNING: `%.*s' is not in NFKC
19// WARNING: `%.*s' is not in NFC
20//
21// Other:
Chris Lattner22eb9722006-06-18 05:43:12 +000022// TODO: Options to support:
23// -fexec-charset,-fwide-exec-charset
24//
25//===----------------------------------------------------------------------===//
26
27#include "clang/Lex/Lexer.h"
28#include "clang/Lex/Preprocessor.h"
29#include "clang/Basic/Diagnostic.h"
30#include "clang/Basic/SourceBuffer.h"
31#include "clang/Basic/SourceLocation.h"
32#include "llvm/Config/alloca.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000033#include <cctype>
34#include <iostream>
35using namespace llvm;
36using namespace clang;
37
38static void InitCharacterInfo();
39
Chris Lattner4cca5ba2006-07-02 20:05:54 +000040Lexer::Lexer(const SourceBuffer *File, unsigned fileid, Preprocessor &pp,
41 const char *BufStart, const char *BufEnd)
Chris Lattner678c8802006-07-11 05:46:12 +000042 : BufferEnd(BufEnd ? BufEnd : File->getBufferEnd()),
Chris Lattner4cca5ba2006-07-02 20:05:54 +000043 InputFile(File), CurFileID(fileid), PP(pp), Features(PP.getLangOptions()) {
Chris Lattnerecfeafe2006-07-02 21:26:45 +000044 Is_PragmaLexer = false;
Chris Lattner4ec473f2006-07-03 05:16:05 +000045 IsMainFile = false;
Chris Lattner22eb9722006-06-18 05:43:12 +000046 InitCharacterInfo();
47
48 assert(BufferEnd[0] == 0 &&
49 "We assume that the input buffer has a null character at the end"
50 " to simplify lexing!");
Chris Lattner678c8802006-07-11 05:46:12 +000051
52 BufferPtr = BufStart ? BufStart : File->getBufferStart();
53
Chris Lattner22eb9722006-06-18 05:43:12 +000054 // Start of the file is a start of line.
55 IsAtStartOfLine = true;
56
57 // We are not after parsing a #.
58 ParsingPreprocessorDirective = false;
59
60 // We are not after parsing #include.
61 ParsingFilename = false;
Chris Lattner3ebcf4e2006-07-11 05:39:23 +000062
63 // We are not in raw mode. Raw mode disables diagnostics and interpretation
64 // of tokens (e.g. identifiers, thus disabling macro expansion). It is used
65 // to quickly lex the tokens of the buffer, e.g. when handling a "#if 0" block
66 // or otherwise skipping over tokens.
67 LexingRawMode = false;
Chris Lattner22eb9722006-06-18 05:43:12 +000068}
69
Chris Lattnere3e81ea2006-07-03 01:13:26 +000070/// Stringify - Convert the specified string into a C string, with surrounding
71/// ""'s, and with escaped \ and " characters.
72std::string Lexer::Stringify(const std::string &Str) {
73 std::string Result = Str;
74 for (unsigned i = 0, e = Result.size(); i != e; ++i) {
75 if (Result[i] == '\\' || Result[i] == '"') {
76 Result.insert(Result.begin()+i, '\\');
77 ++i; ++e;
78 }
79 }
80
81 // Add quotes.
82 return '"' + Result + '"';
83}
84
Chris Lattner22eb9722006-06-18 05:43:12 +000085
Chris Lattner22eb9722006-06-18 05:43:12 +000086//===----------------------------------------------------------------------===//
87// Character information.
88//===----------------------------------------------------------------------===//
89
90static unsigned char CharInfo[256];
91
92enum {
93 CHAR_HORZ_WS = 0x01, // ' ', '\t', '\f', '\v'. Note, no '\0'
94 CHAR_VERT_WS = 0x02, // '\r', '\n'
95 CHAR_LETTER = 0x04, // a-z,A-Z
96 CHAR_NUMBER = 0x08, // 0-9
97 CHAR_UNDER = 0x10, // _
98 CHAR_PERIOD = 0x20 // .
99};
100
101static void InitCharacterInfo() {
102 static bool isInited = false;
103 if (isInited) return;
104 isInited = true;
105
106 // Intiialize the CharInfo table.
107 // TODO: statically initialize this.
108 CharInfo[(int)' '] = CharInfo[(int)'\t'] =
109 CharInfo[(int)'\f'] = CharInfo[(int)'\v'] = CHAR_HORZ_WS;
110 CharInfo[(int)'\n'] = CharInfo[(int)'\r'] = CHAR_VERT_WS;
111
112 CharInfo[(int)'_'] = CHAR_UNDER;
113 for (unsigned i = 'a'; i <= 'z'; ++i)
114 CharInfo[i] = CharInfo[i+'A'-'a'] = CHAR_LETTER;
115 for (unsigned i = '0'; i <= '9'; ++i)
116 CharInfo[i] = CHAR_NUMBER;
117}
118
119/// isIdentifierBody - Return true if this is the body character of an
120/// identifier, which is [a-zA-Z0-9_].
121static inline bool isIdentifierBody(unsigned char c) {
122 return CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER);
123}
124
125/// isHorizontalWhitespace - Return true if this character is horizontal
126/// whitespace: ' ', '\t', '\f', '\v'. Note that this returns false for '\0'.
127static inline bool isHorizontalWhitespace(unsigned char c) {
128 return CharInfo[c] & CHAR_HORZ_WS;
129}
130
131/// isWhitespace - Return true if this character is horizontal or vertical
132/// whitespace: ' ', '\t', '\f', '\v', '\n', '\r'. Note that this returns false
133/// for '\0'.
134static inline bool isWhitespace(unsigned char c) {
135 return CharInfo[c] & (CHAR_HORZ_WS|CHAR_VERT_WS);
136}
137
138/// isNumberBody - Return true if this is the body character of an
139/// preprocessing number, which is [a-zA-Z0-9_.].
140static inline bool isNumberBody(unsigned char c) {
141 return CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER|CHAR_PERIOD);
142}
143
Chris Lattnerd01e2912006-06-18 16:22:51 +0000144
Chris Lattner22eb9722006-06-18 05:43:12 +0000145//===----------------------------------------------------------------------===//
146// Diagnostics forwarding code.
147//===----------------------------------------------------------------------===//
148
149/// getSourceLocation - Return a source location identifier for the specified
150/// offset in the current file.
151SourceLocation Lexer::getSourceLocation(const char *Loc) const {
Chris Lattner8bbfe462006-07-02 22:27:49 +0000152 assert(Loc >= InputFile->getBufferStart() && Loc <= BufferEnd &&
Chris Lattner4cca5ba2006-07-02 20:05:54 +0000153 "Location out of range for this buffer!");
Chris Lattner8bbfe462006-07-02 22:27:49 +0000154 return SourceLocation(CurFileID, Loc-InputFile->getBufferStart());
Chris Lattner22eb9722006-06-18 05:43:12 +0000155}
156
157
158/// Diag - Forwarding function for diagnostics. This translate a source
159/// position in the current buffer into a SourceLocation object for rendering.
Chris Lattnercb283342006-06-18 06:48:37 +0000160void Lexer::Diag(const char *Loc, unsigned DiagID,
Chris Lattner22eb9722006-06-18 05:43:12 +0000161 const std::string &Msg) const {
Chris Lattnercb283342006-06-18 06:48:37 +0000162 PP.Diag(getSourceLocation(Loc), DiagID, Msg);
Chris Lattner22eb9722006-06-18 05:43:12 +0000163}
164
165//===----------------------------------------------------------------------===//
166// Trigraph and Escaped Newline Handling Code.
167//===----------------------------------------------------------------------===//
168
169/// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
170/// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
171static char GetTrigraphCharForLetter(char Letter) {
172 switch (Letter) {
173 default: return 0;
174 case '=': return '#';
175 case ')': return ']';
176 case '(': return '[';
177 case '!': return '|';
178 case '\'': return '^';
179 case '>': return '}';
180 case '/': return '\\';
181 case '<': return '{';
182 case '-': return '~';
183 }
184}
185
186/// DecodeTrigraphChar - If the specified character is a legal trigraph when
187/// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
188/// return the result character. Finally, emit a warning about trigraph use
189/// whether trigraphs are enabled or not.
190static char DecodeTrigraphChar(const char *CP, Lexer *L) {
191 char Res = GetTrigraphCharForLetter(*CP);
192 if (Res && L) {
193 if (!L->getFeatures().Trigraphs) {
194 L->Diag(CP-2, diag::trigraph_ignored);
195 return 0;
196 } else {
197 L->Diag(CP-2, diag::trigraph_converted, std::string()+Res);
198 }
199 }
200 return Res;
201}
202
203/// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
204/// get its size, and return it. This is tricky in several cases:
205/// 1. If currently at the start of a trigraph, we warn about the trigraph,
206/// then either return the trigraph (skipping 3 chars) or the '?',
207/// depending on whether trigraphs are enabled or not.
208/// 2. If this is an escaped newline (potentially with whitespace between
209/// the backslash and newline), implicitly skip the newline and return
210/// the char after it.
Chris Lattner505c5472006-07-03 00:55:48 +0000211/// 3. If this is a UCN, return it. FIXME: C++ UCN's?
Chris Lattner22eb9722006-06-18 05:43:12 +0000212///
213/// This handles the slow/uncommon case of the getCharAndSize method. Here we
214/// know that we can accumulate into Size, and that we have already incremented
215/// Ptr by Size bytes.
216///
Chris Lattnerd01e2912006-06-18 16:22:51 +0000217/// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
218/// be updated to match.
Chris Lattner22eb9722006-06-18 05:43:12 +0000219///
220char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
221 LexerToken *Tok) {
222 // If we have a slash, look for an escaped newline.
223 if (Ptr[0] == '\\') {
224 ++Size;
225 ++Ptr;
226Slash:
227 // Common case, backslash-char where the char is not whitespace.
228 if (!isWhitespace(Ptr[0])) return '\\';
229
230 // See if we have optional whitespace characters followed by a newline.
231 {
232 unsigned SizeTmp = 0;
233 do {
234 ++SizeTmp;
235 if (Ptr[SizeTmp-1] == '\n' || Ptr[SizeTmp-1] == '\r') {
236 // Remember that this token needs to be cleaned.
237 if (Tok) Tok->SetFlag(LexerToken::NeedsCleaning);
238
239 // Warn if there was whitespace between the backslash and newline.
240 if (SizeTmp != 1 && Tok)
241 Diag(Ptr, diag::backslash_newline_space);
242
243 // If this is a \r\n or \n\r, skip the newlines.
244 if ((Ptr[SizeTmp] == '\r' || Ptr[SizeTmp] == '\n') &&
245 Ptr[SizeTmp-1] != Ptr[SizeTmp])
246 ++SizeTmp;
247
248 // Found backslash<whitespace><newline>. Parse the char after it.
249 Size += SizeTmp;
250 Ptr += SizeTmp;
251 // Use slow version to accumulate a correct size field.
252 return getCharAndSizeSlow(Ptr, Size, Tok);
253 }
254 } while (isWhitespace(Ptr[SizeTmp]));
255 }
256
257 // Otherwise, this is not an escaped newline, just return the slash.
258 return '\\';
259 }
260
261 // If this is a trigraph, process it.
262 if (Ptr[0] == '?' && Ptr[1] == '?') {
263 // If this is actually a legal trigraph (not something like "??x"), emit
264 // a trigraph warning. If so, and if trigraphs are enabled, return it.
265 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : 0)) {
266 // Remember that this token needs to be cleaned.
267 if (Tok) Tok->SetFlag(LexerToken::NeedsCleaning);
268
269 Ptr += 3;
270 Size += 3;
271 if (C == '\\') goto Slash;
272 return C;
273 }
274 }
275
276 // If this is neither, return a single character.
277 ++Size;
278 return *Ptr;
279}
280
Chris Lattnerd01e2912006-06-18 16:22:51 +0000281
Chris Lattner22eb9722006-06-18 05:43:12 +0000282/// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
283/// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
284/// and that we have already incremented Ptr by Size bytes.
285///
Chris Lattnerd01e2912006-06-18 16:22:51 +0000286/// NOTE: When this method is updated, getCharAndSizeSlow (above) should
287/// be updated to match.
288char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
Chris Lattner22eb9722006-06-18 05:43:12 +0000289 const LangOptions &Features) {
290 // If we have a slash, look for an escaped newline.
291 if (Ptr[0] == '\\') {
292 ++Size;
293 ++Ptr;
294Slash:
295 // Common case, backslash-char where the char is not whitespace.
296 if (!isWhitespace(Ptr[0])) return '\\';
297
298 // See if we have optional whitespace characters followed by a newline.
299 {
300 unsigned SizeTmp = 0;
301 do {
302 ++SizeTmp;
303 if (Ptr[SizeTmp-1] == '\n' || Ptr[SizeTmp-1] == '\r') {
304
305 // If this is a \r\n or \n\r, skip the newlines.
306 if ((Ptr[SizeTmp] == '\r' || Ptr[SizeTmp] == '\n') &&
307 Ptr[SizeTmp-1] != Ptr[SizeTmp])
308 ++SizeTmp;
309
310 // Found backslash<whitespace><newline>. Parse the char after it.
311 Size += SizeTmp;
312 Ptr += SizeTmp;
313
314 // Use slow version to accumulate a correct size field.
315 return getCharAndSizeSlowNoWarn(Ptr, Size, Features);
316 }
317 } while (isWhitespace(Ptr[SizeTmp]));
318 }
319
320 // Otherwise, this is not an escaped newline, just return the slash.
321 return '\\';
322 }
323
324 // If this is a trigraph, process it.
325 if (Features.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
326 // If this is actually a legal trigraph (not something like "??x"), return
327 // it.
328 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
329 Ptr += 3;
330 Size += 3;
331 if (C == '\\') goto Slash;
332 return C;
333 }
334 }
335
336 // If this is neither, return a single character.
337 ++Size;
338 return *Ptr;
339}
340
Chris Lattner22eb9722006-06-18 05:43:12 +0000341//===----------------------------------------------------------------------===//
342// Helper methods for lexing.
343//===----------------------------------------------------------------------===//
344
Chris Lattnercb283342006-06-18 06:48:37 +0000345void Lexer::LexIdentifier(LexerToken &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000346 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
347 unsigned Size;
348 unsigned char C = *CurPtr++;
349 while (isIdentifierBody(C)) {
350 C = *CurPtr++;
351 }
352 --CurPtr; // Back up over the skipped character.
353
354 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
355 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
Chris Lattner505c5472006-07-03 00:55:48 +0000356 // FIXME: UCNs.
Chris Lattner22eb9722006-06-18 05:43:12 +0000357 if (C != '\\' && C != '?' && (C != '$' || !Features.DollarIdents)) {
358FinishIdentifier:
Chris Lattnercefc7682006-07-08 08:28:12 +0000359 const char *IdStart = BufferPtr;
Chris Lattnerd01e2912006-06-18 16:22:51 +0000360 FormTokenWithChars(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +0000361 Result.SetKind(tok::identifier);
362
Chris Lattnercefc7682006-07-08 08:28:12 +0000363 // Fill in Result.IdentifierInfo, looking up the identifier in the
364 // identifier table.
365 PP.LookUpIdentifierInfo(Result, IdStart);
Chris Lattner22eb9722006-06-18 05:43:12 +0000366
Chris Lattnerc5a00062006-06-18 16:41:01 +0000367 // Finally, now that we know we have an identifier, pass this off to the
368 // preprocessor, which may macro expand it or something.
Chris Lattner22eb9722006-06-18 05:43:12 +0000369 return PP.HandleIdentifier(Result);
370 }
371
372 // Otherwise, $,\,? in identifier found. Enter slower path.
373
374 C = getCharAndSize(CurPtr, Size);
375 while (1) {
376 if (C == '$') {
377 // If we hit a $ and they are not supported in identifiers, we are done.
378 if (!Features.DollarIdents) goto FinishIdentifier;
379
380 // Otherwise, emit a diagnostic and continue.
Chris Lattnercb283342006-06-18 06:48:37 +0000381 Diag(CurPtr, diag::ext_dollar_in_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +0000382 CurPtr = ConsumeChar(CurPtr, Size, Result);
383 C = getCharAndSize(CurPtr, Size);
384 continue;
Chris Lattner505c5472006-07-03 00:55:48 +0000385 } else if (!isIdentifierBody(C)) { // FIXME: UCNs.
Chris Lattner22eb9722006-06-18 05:43:12 +0000386 // Found end of identifier.
387 goto FinishIdentifier;
388 }
389
390 // Otherwise, this character is good, consume it.
391 CurPtr = ConsumeChar(CurPtr, Size, Result);
392
393 C = getCharAndSize(CurPtr, Size);
Chris Lattner505c5472006-07-03 00:55:48 +0000394 while (isIdentifierBody(C)) { // FIXME: UCNs.
Chris Lattner22eb9722006-06-18 05:43:12 +0000395 CurPtr = ConsumeChar(CurPtr, Size, Result);
396 C = getCharAndSize(CurPtr, Size);
397 }
398 }
399}
400
401
402/// LexNumericConstant - Lex the remainer of a integer or floating point
403/// constant. From[-1] is the first character lexed. Return the end of the
404/// constant.
Chris Lattnercb283342006-06-18 06:48:37 +0000405void Lexer::LexNumericConstant(LexerToken &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000406 unsigned Size;
407 char C = getCharAndSize(CurPtr, Size);
408 char PrevCh = 0;
Chris Lattner505c5472006-07-03 00:55:48 +0000409 while (isNumberBody(C)) { // FIXME: UCNs?
Chris Lattner22eb9722006-06-18 05:43:12 +0000410 CurPtr = ConsumeChar(CurPtr, Size, Result);
411 PrevCh = C;
412 C = getCharAndSize(CurPtr, Size);
413 }
414
415 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
416 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e'))
417 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
418
419 // If we have a hex FP constant, continue.
420 if (Features.HexFloats &&
421 (C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p'))
422 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
423
424 Result.SetKind(tok::numeric_constant);
425
Chris Lattnerd01e2912006-06-18 16:22:51 +0000426 // Update the location of token as well as BufferPtr.
427 FormTokenWithChars(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +0000428}
429
430/// LexStringLiteral - Lex the remainder of a string literal, after having lexed
431/// either " or L".
Chris Lattnercb283342006-06-18 06:48:37 +0000432void Lexer::LexStringLiteral(LexerToken &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000433 const char *NulCharacter = 0; // Does this string contain the \0 character?
434
435 char C = getAndAdvanceChar(CurPtr, Result);
436 while (C != '"') {
437 // Skip escaped characters.
438 if (C == '\\') {
439 // Skip the escaped character.
440 C = getAndAdvanceChar(CurPtr, Result);
441 } else if (C == '\n' || C == '\r' || // Newline.
442 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000443 Diag(BufferPtr, diag::err_unterminated_string);
Chris Lattner22eb9722006-06-18 05:43:12 +0000444 BufferPtr = CurPtr-1;
445 return LexTokenInternal(Result);
446 } else if (C == 0) {
447 NulCharacter = CurPtr-1;
448 }
449 C = getAndAdvanceChar(CurPtr, Result);
450 }
451
Chris Lattnercb283342006-06-18 06:48:37 +0000452 if (NulCharacter) Diag(NulCharacter, diag::null_in_string);
Chris Lattner22eb9722006-06-18 05:43:12 +0000453
454 Result.SetKind(tok::string_literal);
455
Chris Lattnerd01e2912006-06-18 16:22:51 +0000456 // Update the location of the token as well as the BufferPtr instance var.
457 FormTokenWithChars(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +0000458}
459
460/// LexAngledStringLiteral - Lex the remainder of an angled string literal,
461/// after having lexed the '<' character. This is used for #include filenames.
Chris Lattnercb283342006-06-18 06:48:37 +0000462void Lexer::LexAngledStringLiteral(LexerToken &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000463 const char *NulCharacter = 0; // Does this string contain the \0 character?
464
465 char C = getAndAdvanceChar(CurPtr, Result);
466 while (C != '>') {
467 // Skip escaped characters.
468 if (C == '\\') {
469 // Skip the escaped character.
470 C = getAndAdvanceChar(CurPtr, Result);
471 } else if (C == '\n' || C == '\r' || // Newline.
472 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000473 Diag(BufferPtr, diag::err_unterminated_string);
Chris Lattner22eb9722006-06-18 05:43:12 +0000474 BufferPtr = CurPtr-1;
475 return LexTokenInternal(Result);
476 } else if (C == 0) {
477 NulCharacter = CurPtr-1;
478 }
479 C = getAndAdvanceChar(CurPtr, Result);
480 }
481
Chris Lattnercb283342006-06-18 06:48:37 +0000482 if (NulCharacter) Diag(NulCharacter, diag::null_in_string);
Chris Lattner22eb9722006-06-18 05:43:12 +0000483
484 Result.SetKind(tok::angle_string_literal);
485
Chris Lattnerd01e2912006-06-18 16:22:51 +0000486 // Update the location of token as well as BufferPtr.
487 FormTokenWithChars(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +0000488}
489
490
491/// LexCharConstant - Lex the remainder of a character constant, after having
492/// lexed either ' or L'.
Chris Lattnercb283342006-06-18 06:48:37 +0000493void Lexer::LexCharConstant(LexerToken &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000494 const char *NulCharacter = 0; // Does this character contain the \0 character?
495
496 // Handle the common case of 'x' and '\y' efficiently.
497 char C = getAndAdvanceChar(CurPtr, Result);
498 if (C == '\'') {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000499 Diag(BufferPtr, diag::err_empty_character);
Chris Lattner22eb9722006-06-18 05:43:12 +0000500 BufferPtr = CurPtr;
501 return LexTokenInternal(Result);
502 } else if (C == '\\') {
503 // Skip the escaped character.
504 // FIXME: UCN's.
505 C = getAndAdvanceChar(CurPtr, Result);
506 }
507
508 if (C && C != '\n' && C != '\r' && CurPtr[0] == '\'') {
509 ++CurPtr;
510 } else {
511 // Fall back on generic code for embedded nulls, newlines, wide chars.
512 do {
513 // Skip escaped characters.
514 if (C == '\\') {
515 // Skip the escaped character.
516 C = getAndAdvanceChar(CurPtr, Result);
517 } else if (C == '\n' || C == '\r' || // Newline.
518 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000519 Diag(BufferPtr, diag::err_unterminated_char);
Chris Lattner22eb9722006-06-18 05:43:12 +0000520 BufferPtr = CurPtr-1;
521 return LexTokenInternal(Result);
522 } else if (C == 0) {
523 NulCharacter = CurPtr-1;
524 }
525 C = getAndAdvanceChar(CurPtr, Result);
526 } while (C != '\'');
527 }
528
Chris Lattnercb283342006-06-18 06:48:37 +0000529 if (NulCharacter) Diag(NulCharacter, diag::null_in_char);
Chris Lattner22eb9722006-06-18 05:43:12 +0000530
531 Result.SetKind(tok::char_constant);
532
Chris Lattnerd01e2912006-06-18 16:22:51 +0000533 // Update the location of token as well as BufferPtr.
534 FormTokenWithChars(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +0000535}
536
537/// SkipWhitespace - Efficiently skip over a series of whitespace characters.
538/// Update BufferPtr to point to the next non-whitespace character and return.
Chris Lattnercb283342006-06-18 06:48:37 +0000539void Lexer::SkipWhitespace(LexerToken &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000540 // Whitespace - Skip it, then return the token after the whitespace.
541 unsigned char Char = *CurPtr; // Skip consequtive spaces efficiently.
542 while (1) {
543 // Skip horizontal whitespace very aggressively.
544 while (isHorizontalWhitespace(Char))
545 Char = *++CurPtr;
546
547 // Otherwise if we something other than whitespace, we're done.
548 if (Char != '\n' && Char != '\r')
549 break;
550
551 if (ParsingPreprocessorDirective) {
552 // End of preprocessor directive line, let LexTokenInternal handle this.
553 BufferPtr = CurPtr;
Chris Lattnercb283342006-06-18 06:48:37 +0000554 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000555 }
556
557 // ok, but handle newline.
558 // The returned token is at the start of the line.
559 Result.SetFlag(LexerToken::StartOfLine);
560 // No leading whitespace seen so far.
561 Result.ClearFlag(LexerToken::LeadingSpace);
562 Char = *++CurPtr;
563 }
564
565 // If this isn't immediately after a newline, there is leading space.
566 char PrevChar = CurPtr[-1];
567 if (PrevChar != '\n' && PrevChar != '\r')
568 Result.SetFlag(LexerToken::LeadingSpace);
569
570 // If the next token is obviously a // or /* */ comment, skip it efficiently
571 // too (without going through the big switch stmt).
572 if (Char == '/' && CurPtr[1] == '/') {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000573 BufferPtr = CurPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +0000574 return SkipBCPLComment(Result, CurPtr+1);
575 }
576 if (Char == '/' && CurPtr[1] == '*') {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000577 BufferPtr = CurPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +0000578 return SkipBlockComment(Result, CurPtr+2);
579 }
580 BufferPtr = CurPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +0000581}
582
583// SkipBCPLComment - We have just read the // characters from input. Skip until
584// we find the newline character thats terminate the comment. Then update
585/// BufferPtr and return.
Chris Lattnercb283342006-06-18 06:48:37 +0000586void Lexer::SkipBCPLComment(LexerToken &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000587 // If BCPL comments aren't explicitly enabled for this language, emit an
588 // extension warning.
589 if (!Features.BCPLComment) {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000590 Diag(BufferPtr, diag::ext_bcpl_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +0000591
592 // Mark them enabled so we only emit one warning for this translation
593 // unit.
594 Features.BCPLComment = true;
595 }
596
597 // Scan over the body of the comment. The common case, when scanning, is that
598 // the comment contains normal ascii characters with nothing interesting in
599 // them. As such, optimize for this case with the inner loop.
600 char C;
601 do {
602 C = *CurPtr;
Chris Lattner505c5472006-07-03 00:55:48 +0000603 // FIXME: Speedup BCPL comment lexing. Just scan for a \n or \r character.
604 // If we find a \n character, scan backwards, checking to see if it's an
605 // escaped newline, like we do for block comments.
Chris Lattner22eb9722006-06-18 05:43:12 +0000606
607 // Skip over characters in the fast loop.
608 while (C != 0 && // Potentially EOF.
609 C != '\\' && // Potentially escaped newline.
610 C != '?' && // Potentially trigraph.
611 C != '\n' && C != '\r') // Newline or DOS-style newline.
612 C = *++CurPtr;
613
614 // If this is a newline, we're done.
615 if (C == '\n' || C == '\r')
616 break; // Found the newline? Break out!
617
618 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
619 // properly decode the character.
620 const char *OldPtr = CurPtr;
621 C = getAndAdvanceChar(CurPtr, Result);
622
623 // If we read multiple characters, and one of those characters was a \r or
624 // \n, then we had an escaped newline within the comment. Emit diagnostic.
625 if (CurPtr != OldPtr+1) {
626 for (; OldPtr != CurPtr; ++OldPtr)
627 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
Chris Lattnercb283342006-06-18 06:48:37 +0000628 Diag(OldPtr-1, diag::ext_multi_line_bcpl_comment);
629 break;
Chris Lattner22eb9722006-06-18 05:43:12 +0000630 }
631 }
632
633 if (CurPtr == BufferEnd+1) goto FoundEOF;
634 } while (C != '\n' && C != '\r');
635
636 // Found and did not consume a newline.
637
638 // If we are inside a preprocessor directive and we see the end of line,
639 // return immediately, so that the lexer can return this as an EOM token.
640 if (ParsingPreprocessorDirective) {
641 BufferPtr = CurPtr;
Chris Lattnercb283342006-06-18 06:48:37 +0000642 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000643 }
644
645 // Otherwise, eat the \n character. We don't care if this is a \n\r or
646 // \r\n sequence.
647 ++CurPtr;
648
649 // The next returned token is at the start of the line.
650 Result.SetFlag(LexerToken::StartOfLine);
651 // No leading whitespace seen so far.
652 Result.ClearFlag(LexerToken::LeadingSpace);
653
654 // It is common for the tokens immediately after a // comment to be
655 // whitespace (indentation for the next line). Instead of going through the
656 // big switch, handle it efficiently now.
657 if (isWhitespace(*CurPtr)) {
658 Result.SetFlag(LexerToken::LeadingSpace);
659 return SkipWhitespace(Result, CurPtr+1);
660 }
661
662 BufferPtr = CurPtr;
Chris Lattnercb283342006-06-18 06:48:37 +0000663 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000664
665FoundEOF: // If we ran off the end of the buffer, return EOF.
666 BufferPtr = CurPtr-1;
Chris Lattnercb283342006-06-18 06:48:37 +0000667 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000668}
669
Chris Lattnercb283342006-06-18 06:48:37 +0000670/// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
671/// character (either \n or \r) is part of an escaped newline sequence. Issue a
Chris Lattner22eb9722006-06-18 05:43:12 +0000672/// diagnostic if so. We know that the is inside of a block comment.
Chris Lattner1f583052006-06-18 06:53:56 +0000673static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
674 Lexer *L) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000675 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
Chris Lattner22eb9722006-06-18 05:43:12 +0000676
677 // Back up off the newline.
678 --CurPtr;
679
680 // If this is a two-character newline sequence, skip the other character.
681 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
682 // \n\n or \r\r -> not escaped newline.
683 if (CurPtr[0] == CurPtr[1])
684 return false;
685 // \n\r or \r\n -> skip the newline.
686 --CurPtr;
687 }
688
689 // If we have horizontal whitespace, skip over it. We allow whitespace
690 // between the slash and newline.
691 bool HasSpace = false;
692 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
693 --CurPtr;
694 HasSpace = true;
695 }
696
697 // If we have a slash, we know this is an escaped newline.
698 if (*CurPtr == '\\') {
Chris Lattnercb283342006-06-18 06:48:37 +0000699 if (CurPtr[-1] != '*') return false;
Chris Lattner22eb9722006-06-18 05:43:12 +0000700 } else {
701 // It isn't a slash, is it the ?? / trigraph?
Chris Lattnercb283342006-06-18 06:48:37 +0000702 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
703 CurPtr[-3] != '*')
Chris Lattner22eb9722006-06-18 05:43:12 +0000704 return false;
Chris Lattnercb283342006-06-18 06:48:37 +0000705
706 // This is the trigraph ending the comment. Emit a stern warning!
Chris Lattner22eb9722006-06-18 05:43:12 +0000707 CurPtr -= 2;
708
709 // If no trigraphs are enabled, warn that we ignored this trigraph and
710 // ignore this * character.
Chris Lattner1f583052006-06-18 06:53:56 +0000711 if (!L->getFeatures().Trigraphs) {
712 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
Chris Lattnercb283342006-06-18 06:48:37 +0000713 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +0000714 }
Chris Lattner1f583052006-06-18 06:53:56 +0000715 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +0000716 }
717
718 // Warn about having an escaped newline between the */ characters.
Chris Lattner1f583052006-06-18 06:53:56 +0000719 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
Chris Lattner22eb9722006-06-18 05:43:12 +0000720
721 // If there was space between the backslash and newline, warn about it.
Chris Lattner1f583052006-06-18 06:53:56 +0000722 if (HasSpace) L->Diag(CurPtr, diag::backslash_newline_space);
Chris Lattner22eb9722006-06-18 05:43:12 +0000723
Chris Lattnercb283342006-06-18 06:48:37 +0000724 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +0000725}
726
727/// SkipBlockComment - We have just read the /* characters from input. Read
728/// until we find the */ characters that terminate the comment. Note that we
729/// don't bother decoding trigraphs or escaped newlines in block comments,
730/// because they cannot cause the comment to end. The only thing that can
731/// happen is the comment could end with an escaped newline between the */ end
732/// of comment.
Chris Lattnercb283342006-06-18 06:48:37 +0000733void Lexer::SkipBlockComment(LexerToken &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000734 // Scan one character past where we should, looking for a '/' character. Once
735 // we find it, check to see if it was preceeded by a *. This common
736 // optimization helps people who like to put a lot of * characters in their
737 // comments.
738 unsigned char C = *CurPtr++;
739 if (C == 0 && CurPtr == BufferEnd+1) {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000740 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +0000741 BufferPtr = CurPtr-1;
Chris Lattnercb283342006-06-18 06:48:37 +0000742 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000743 }
744
745 while (1) {
746 // Skip over all non-interesting characters.
747 // TODO: Vectorize this. Note: memchr on Darwin is slower than this loop.
748 while (C != '/' && C != '\0')
749 C = *CurPtr++;
750
751 if (C == '/') {
Chris Lattner22eb9722006-06-18 05:43:12 +0000752 if (CurPtr[-2] == '*') // We found the final */. We're done!
753 break;
754
755 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
Chris Lattner1f583052006-06-18 06:53:56 +0000756 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000757 // We found the final */, though it had an escaped newline between the
758 // * and /. We're done!
759 break;
760 }
761 }
762 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
763 // If this is a /* inside of the comment, emit a warning. Don't do this
764 // if this is a /*/, which will end the comment. This misses cases with
765 // embedded escaped newlines, but oh well.
Chris Lattnercb283342006-06-18 06:48:37 +0000766 Diag(CurPtr-1, diag::nested_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +0000767 }
768 } else if (C == 0 && CurPtr == BufferEnd+1) {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000769 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +0000770 // Note: the user probably forgot a */. We could continue immediately
771 // after the /*, but this would involve lexing a lot of what really is the
772 // comment, which surely would confuse the parser.
773 BufferPtr = CurPtr-1;
Chris Lattnercb283342006-06-18 06:48:37 +0000774 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000775 }
776 C = *CurPtr++;
777 }
778
779 // It is common for the tokens immediately after a /**/ comment to be
780 // whitespace. Instead of going through the big switch, handle it
781 // efficiently now.
782 if (isHorizontalWhitespace(*CurPtr)) {
783 Result.SetFlag(LexerToken::LeadingSpace);
784 return SkipWhitespace(Result, CurPtr+1);
785 }
786
787 // Otherwise, just return so that the next character will be lexed as a token.
788 BufferPtr = CurPtr;
789 Result.SetFlag(LexerToken::LeadingSpace);
Chris Lattner22eb9722006-06-18 05:43:12 +0000790}
791
792//===----------------------------------------------------------------------===//
793// Primary Lexing Entry Points
794//===----------------------------------------------------------------------===//
795
796/// LexIncludeFilename - After the preprocessor has parsed a #include, lex and
797/// (potentially) macro expand the filename.
Chris Lattner269c2322006-06-25 06:23:00 +0000798std::string Lexer::LexIncludeFilename(LexerToken &FilenameTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000799 assert(ParsingPreprocessorDirective &&
800 ParsingFilename == false &&
801 "Must be in a preprocessing directive!");
802
803 // We are now parsing a filename!
804 ParsingFilename = true;
805
Chris Lattner269c2322006-06-25 06:23:00 +0000806 // Lex the filename.
807 Lex(FilenameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +0000808
809 // We should have gotten the filename now.
810 ParsingFilename = false;
811
812 // No filename?
Chris Lattner269c2322006-06-25 06:23:00 +0000813 if (FilenameTok.getKind() == tok::eom) {
814 PP.Diag(FilenameTok, diag::err_pp_expects_filename);
815 return "";
Chris Lattnercb283342006-06-18 06:48:37 +0000816 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000817
Chris Lattner269c2322006-06-25 06:23:00 +0000818 // Get the text form of the filename.
819 std::string Filename = PP.getSpelling(FilenameTok);
820 assert(!Filename.empty() && "Can't have tokens with empty spellings!");
821
822 // Make sure the filename is <x> or "x".
823 if (Filename[0] == '<') {
824 if (Filename[Filename.size()-1] != '>') {
825 PP.Diag(FilenameTok, diag::err_pp_expects_filename);
826 FilenameTok.SetKind(tok::eom);
827 return "";
828 }
829 } else if (Filename[0] == '"') {
830 if (Filename[Filename.size()-1] != '"') {
831 PP.Diag(FilenameTok, diag::err_pp_expects_filename);
832 FilenameTok.SetKind(tok::eom);
833 return "";
834 }
835 } else {
836 PP.Diag(FilenameTok, diag::err_pp_expects_filename);
837 FilenameTok.SetKind(tok::eom);
838 return "";
Chris Lattner22eb9722006-06-18 05:43:12 +0000839 }
Chris Lattner269c2322006-06-25 06:23:00 +0000840
841 // Diagnose #include "" as invalid.
842 if (Filename.size() == 2) {
843 PP.Diag(FilenameTok, diag::err_pp_empty_filename);
844 FilenameTok.SetKind(tok::eom);
845 return "";
846 }
847
848 return Filename;
Chris Lattner22eb9722006-06-18 05:43:12 +0000849}
850
851/// ReadToEndOfLine - Read the rest of the current preprocessor line as an
852/// uninterpreted string. This switches the lexer out of directive mode.
853std::string Lexer::ReadToEndOfLine() {
854 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
855 "Must be in a preprocessing directive!");
856 std::string Result;
857 LexerToken Tmp;
858
859 // CurPtr - Cache BufferPtr in an automatic variable.
860 const char *CurPtr = BufferPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +0000861 while (1) {
862 char Char = getAndAdvanceChar(CurPtr, Tmp);
863 switch (Char) {
864 default:
865 Result += Char;
866 break;
867 case 0: // Null.
868 // Found end of file?
869 if (CurPtr-1 != BufferEnd) {
870 // Nope, normal character, continue.
871 Result += Char;
872 break;
873 }
874 // FALL THROUGH.
875 case '\r':
876 case '\n':
877 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
878 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
879 BufferPtr = CurPtr-1;
880
881 // Next, lex the character, which should handle the EOM transition.
Chris Lattnercb283342006-06-18 06:48:37 +0000882 Lex(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +0000883 assert(Tmp.getKind() == tok::eom && "Unexpected token!");
Chris Lattner22eb9722006-06-18 05:43:12 +0000884
885 // Finally, we're done, return the string we found.
886 return Result;
887 }
888 }
889}
890
891/// LexEndOfFile - CurPtr points to the end of this file. Handle this
892/// condition, reporting diagnostics and handling other edge cases as required.
Chris Lattnercb283342006-06-18 06:48:37 +0000893void Lexer::LexEndOfFile(LexerToken &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000894 // If we hit the end of the file while parsing a preprocessor directive,
895 // end the preprocessor directive first. The next token returned will
896 // then be the end of file.
897 if (ParsingPreprocessorDirective) {
898 // Done parsing the "line".
899 ParsingPreprocessorDirective = false;
900 Result.SetKind(tok::eom);
Chris Lattnerd01e2912006-06-18 16:22:51 +0000901 // Update the location of token as well as BufferPtr.
902 FormTokenWithChars(Result, CurPtr);
Chris Lattnercb283342006-06-18 06:48:37 +0000903 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000904 }
905
Chris Lattner3ebcf4e2006-07-11 05:39:23 +0000906 // If we aren't in raw mode, issue diagnostics. If we are in raw mode, let the
907 // code that put us into raw mode do this: there are multiple possible reasons
908 // for raw mode, and not all want these diagnostics.
909 if (!LexingRawMode) {
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000910 // If we are in a #if directive, emit an error.
911 while (!ConditionalStack.empty()) {
912 PP.Diag(ConditionalStack.back().IfLoc,
913 diag::err_pp_unterminated_conditional);
914 ConditionalStack.pop_back();
915 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000916
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000917 // If the file was empty or didn't end in a newline, issue a pedwarn.
918 if (CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
919 Diag(BufferEnd, diag::ext_no_newline_eof);
920 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000921
922 BufferPtr = CurPtr;
Chris Lattnercb283342006-06-18 06:48:37 +0000923 PP.HandleEndOfFile(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +0000924}
925
Chris Lattner678c8802006-07-11 05:46:12 +0000926/// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
927/// the specified lexer will return a tok::l_paren token, 0 if it is something
928/// else and 2 if there are no more tokens in the buffer controlled by the
929/// lexer.
930unsigned Lexer::isNextPPTokenLParen() {
931 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
932
933 // Switch to 'skipping' mode. This will ensure that we can lex a token
934 // without emitting diagnostics, disables macro expansion, and will cause EOF
935 // to return an EOF token instead of popping the include stack.
936 LexingRawMode = true;
937
938 // Save state that can be changed while lexing so that we can restore it.
939 const char *TmpBufferPtr = BufferPtr;
940
941 LexerToken Tok;
942 Tok.StartToken();
943 LexTokenInternal(Tok);
944
945 // Restore state that may have changed.
946 BufferPtr = TmpBufferPtr;
947
948 // Restore the lexer back to non-skipping mode.
949 LexingRawMode = false;
950
951 if (Tok.getKind() == tok::eof)
952 return 2;
953 return Tok.getKind() == tok::l_paren;
954}
955
Chris Lattner22eb9722006-06-18 05:43:12 +0000956
957/// LexTokenInternal - This implements a simple C family lexer. It is an
958/// extremely performance critical piece of code. This assumes that the buffer
959/// has a null character at the end of the file. Return true if an error
960/// occurred and compilation should terminate, false if normal. This returns a
961/// preprocessing token, not a normal token, as such, it is an internal
962/// interface. It assumes that the Flags of result have been cleared before
963/// calling this.
Chris Lattnercb283342006-06-18 06:48:37 +0000964void Lexer::LexTokenInternal(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000965LexNextToken:
966 // New token, can't need cleaning yet.
967 Result.ClearFlag(LexerToken::NeedsCleaning);
Chris Lattner27746e42006-07-05 00:07:54 +0000968 Result.SetIdentifierInfo(0);
Chris Lattner22eb9722006-06-18 05:43:12 +0000969
970 // CurPtr - Cache BufferPtr in an automatic variable.
971 const char *CurPtr = BufferPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +0000972
Chris Lattnereb54b592006-07-10 06:34:27 +0000973 // Small amounts of horizontal whitespace is very common between tokens.
974 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
975 ++CurPtr;
976 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
977 ++CurPtr;
978 BufferPtr = CurPtr;
979 Result.SetFlag(LexerToken::LeadingSpace);
980 }
981
Chris Lattner22eb9722006-06-18 05:43:12 +0000982 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
983
984 // Read a character, advancing over it.
985 char Char = getAndAdvanceChar(CurPtr, Result);
986 switch (Char) {
987 case 0: // Null.
988 // Found end of file?
989 if (CurPtr-1 == BufferEnd)
990 return LexEndOfFile(Result, CurPtr-1); // Retreat back into the file.
991
Chris Lattnercb283342006-06-18 06:48:37 +0000992 Diag(CurPtr-1, diag::null_in_file);
Chris Lattner22eb9722006-06-18 05:43:12 +0000993 Result.SetFlag(LexerToken::LeadingSpace);
Chris Lattnercb283342006-06-18 06:48:37 +0000994 SkipWhitespace(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +0000995 goto LexNextToken; // GCC isn't tail call eliminating.
996 case '\n':
997 case '\r':
998 // If we are inside a preprocessor directive and we see the end of line,
999 // we know we are done with the directive, so return an EOM token.
1000 if (ParsingPreprocessorDirective) {
1001 // Done parsing the "line".
1002 ParsingPreprocessorDirective = false;
1003
1004 // Since we consumed a newline, we are back at the start of a line.
1005 IsAtStartOfLine = true;
1006
1007 Result.SetKind(tok::eom);
1008 break;
1009 }
1010 // The returned token is at the start of the line.
1011 Result.SetFlag(LexerToken::StartOfLine);
1012 // No leading whitespace seen so far.
1013 Result.ClearFlag(LexerToken::LeadingSpace);
Chris Lattnercb283342006-06-18 06:48:37 +00001014 SkipWhitespace(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +00001015 goto LexNextToken; // GCC isn't tail call eliminating.
1016 case ' ':
1017 case '\t':
1018 case '\f':
1019 case '\v':
1020 Result.SetFlag(LexerToken::LeadingSpace);
Chris Lattnercb283342006-06-18 06:48:37 +00001021 SkipWhitespace(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +00001022 goto LexNextToken; // GCC isn't tail call eliminating.
1023
1024 case 'L':
Chris Lattner371ac8a2006-07-04 07:11:10 +00001025 // Notify MIOpt that we read a non-whitespace/non-comment token.
1026 MIOpt.ReadToken();
Chris Lattner22eb9722006-06-18 05:43:12 +00001027 Char = getCharAndSize(CurPtr, SizeTmp);
1028
1029 // Wide string literal.
1030 if (Char == '"')
1031 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result));
1032
1033 // Wide character constant.
1034 if (Char == '\'')
1035 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
1036 // FALL THROUGH, treating L like the start of an identifier.
1037
1038 // C99 6.4.2: Identifiers.
1039 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
1040 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
1041 case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U':
1042 case 'V': case 'W': case 'X': case 'Y': case 'Z':
1043 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
1044 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
1045 case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u':
1046 case 'v': case 'w': case 'x': case 'y': case 'z':
1047 case '_':
Chris Lattner371ac8a2006-07-04 07:11:10 +00001048 // Notify MIOpt that we read a non-whitespace/non-comment token.
1049 MIOpt.ReadToken();
Chris Lattner22eb9722006-06-18 05:43:12 +00001050 return LexIdentifier(Result, CurPtr);
1051
1052 // C99 6.4.4.1: Integer Constants.
1053 // C99 6.4.4.2: Floating Constants.
1054 case '0': case '1': case '2': case '3': case '4':
1055 case '5': case '6': case '7': case '8': case '9':
Chris Lattner371ac8a2006-07-04 07:11:10 +00001056 // Notify MIOpt that we read a non-whitespace/non-comment token.
1057 MIOpt.ReadToken();
Chris Lattner22eb9722006-06-18 05:43:12 +00001058 return LexNumericConstant(Result, CurPtr);
1059
1060 // C99 6.4.4: Character Constants.
1061 case '\'':
Chris Lattner371ac8a2006-07-04 07:11:10 +00001062 // Notify MIOpt that we read a non-whitespace/non-comment token.
1063 MIOpt.ReadToken();
Chris Lattner22eb9722006-06-18 05:43:12 +00001064 return LexCharConstant(Result, CurPtr);
1065
1066 // C99 6.4.5: String Literals.
1067 case '"':
Chris Lattner371ac8a2006-07-04 07:11:10 +00001068 // Notify MIOpt that we read a non-whitespace/non-comment token.
1069 MIOpt.ReadToken();
Chris Lattner22eb9722006-06-18 05:43:12 +00001070 return LexStringLiteral(Result, CurPtr);
1071
1072 // C99 6.4.6: Punctuators.
1073 case '?':
1074 Result.SetKind(tok::question);
1075 break;
1076 case '[':
1077 Result.SetKind(tok::l_square);
1078 break;
1079 case ']':
1080 Result.SetKind(tok::r_square);
1081 break;
1082 case '(':
1083 Result.SetKind(tok::l_paren);
1084 break;
1085 case ')':
1086 Result.SetKind(tok::r_paren);
1087 break;
1088 case '{':
1089 Result.SetKind(tok::l_brace);
1090 break;
1091 case '}':
1092 Result.SetKind(tok::r_brace);
1093 break;
1094 case '.':
1095 Char = getCharAndSize(CurPtr, SizeTmp);
1096 if (Char >= '0' && Char <= '9') {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001097 // Notify MIOpt that we read a non-whitespace/non-comment token.
1098 MIOpt.ReadToken();
1099
Chris Lattner22eb9722006-06-18 05:43:12 +00001100 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
1101 } else if (Features.CPlusPlus && Char == '*') {
1102 Result.SetKind(tok::periodstar);
1103 CurPtr += SizeTmp;
1104 } else if (Char == '.' &&
1105 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
1106 Result.SetKind(tok::ellipsis);
1107 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1108 SizeTmp2, Result);
1109 } else {
1110 Result.SetKind(tok::period);
1111 }
1112 break;
1113 case '&':
1114 Char = getCharAndSize(CurPtr, SizeTmp);
1115 if (Char == '&') {
1116 Result.SetKind(tok::ampamp);
1117 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1118 } else if (Char == '=') {
1119 Result.SetKind(tok::ampequal);
1120 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1121 } else {
1122 Result.SetKind(tok::amp);
1123 }
1124 break;
1125 case '*':
1126 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
1127 Result.SetKind(tok::starequal);
1128 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1129 } else {
1130 Result.SetKind(tok::star);
1131 }
1132 break;
1133 case '+':
1134 Char = getCharAndSize(CurPtr, SizeTmp);
1135 if (Char == '+') {
1136 Result.SetKind(tok::plusplus);
1137 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1138 } else if (Char == '=') {
1139 Result.SetKind(tok::plusequal);
1140 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1141 } else {
1142 Result.SetKind(tok::plus);
1143 }
1144 break;
1145 case '-':
1146 Char = getCharAndSize(CurPtr, SizeTmp);
1147 if (Char == '-') {
1148 Result.SetKind(tok::minusminus);
1149 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1150 } else if (Char == '>' && Features.CPlusPlus &&
1151 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') {
1152 Result.SetKind(tok::arrowstar); // C++ ->*
1153 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1154 SizeTmp2, Result);
1155 } else if (Char == '>') {
1156 Result.SetKind(tok::arrow);
1157 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1158 } else if (Char == '=') {
1159 Result.SetKind(tok::minusequal);
1160 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1161 } else {
1162 Result.SetKind(tok::minus);
1163 }
1164 break;
1165 case '~':
1166 Result.SetKind(tok::tilde);
1167 break;
1168 case '!':
1169 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
1170 Result.SetKind(tok::exclaimequal);
1171 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1172 } else {
1173 Result.SetKind(tok::exclaim);
1174 }
1175 break;
1176 case '/':
1177 // 6.4.9: Comments
1178 Char = getCharAndSize(CurPtr, SizeTmp);
1179 if (Char == '/') { // BCPL comment.
1180 Result.SetFlag(LexerToken::LeadingSpace);
Chris Lattnercb283342006-06-18 06:48:37 +00001181 SkipBCPLComment(Result, ConsumeChar(CurPtr, SizeTmp, Result));
Chris Lattner22eb9722006-06-18 05:43:12 +00001182 goto LexNextToken; // GCC isn't tail call eliminating.
1183 } else if (Char == '*') { // /**/ comment.
1184 Result.SetFlag(LexerToken::LeadingSpace);
Chris Lattnercb283342006-06-18 06:48:37 +00001185 SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result));
Chris Lattner22eb9722006-06-18 05:43:12 +00001186 goto LexNextToken; // GCC isn't tail call eliminating.
1187 } else if (Char == '=') {
1188 Result.SetKind(tok::slashequal);
1189 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1190 } else {
1191 Result.SetKind(tok::slash);
1192 }
1193 break;
1194 case '%':
1195 Char = getCharAndSize(CurPtr, SizeTmp);
1196 if (Char == '=') {
1197 Result.SetKind(tok::percentequal);
1198 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1199 } else if (Features.Digraphs && Char == '>') {
1200 Result.SetKind(tok::r_brace); // '%>' -> '}'
1201 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1202 } else if (Features.Digraphs && Char == ':') {
1203 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1204 if (getCharAndSize(CurPtr, SizeTmp) == '%' &&
1205 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
1206 Result.SetKind(tok::hashhash); // '%:%:' -> '##'
1207 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1208 SizeTmp2, Result);
1209 } else {
1210 Result.SetKind(tok::hash); // '%:' -> '#'
1211
1212 // We parsed a # character. If this occurs at the start of the line,
1213 // it's actually the start of a preprocessing directive. Callback to
1214 // the preprocessor to handle it.
1215 // FIXME: -fpreprocessed mode??
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001216 if (Result.isAtStartOfLine() && !LexingRawMode) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001217 BufferPtr = CurPtr;
Chris Lattnercb283342006-06-18 06:48:37 +00001218 PP.HandleDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001219
1220 // As an optimization, if the preprocessor didn't switch lexers, tail
1221 // recurse.
1222 if (PP.isCurrentLexer(this)) {
1223 // Start a new token. If this is a #include or something, the PP may
1224 // want us starting at the beginning of the line again. If so, set
1225 // the StartOfLine flag.
1226 if (IsAtStartOfLine) {
1227 Result.SetFlag(LexerToken::StartOfLine);
1228 IsAtStartOfLine = false;
1229 }
1230 goto LexNextToken; // GCC isn't tail call eliminating.
1231 }
1232
1233 return PP.Lex(Result);
1234 }
1235 }
1236 } else {
1237 Result.SetKind(tok::percent);
1238 }
1239 break;
1240 case '<':
1241 Char = getCharAndSize(CurPtr, SizeTmp);
1242 if (ParsingFilename) {
1243 return LexAngledStringLiteral(Result, CurPtr+SizeTmp);
1244 } else if (Char == '<' &&
1245 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '=') {
1246 Result.SetKind(tok::lesslessequal);
1247 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1248 SizeTmp2, Result);
1249 } else if (Char == '<') {
1250 Result.SetKind(tok::lessless);
1251 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1252 } else if (Char == '=') {
1253 Result.SetKind(tok::lessequal);
1254 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1255 } else if (Features.Digraphs && Char == ':') {
1256 Result.SetKind(tok::l_square); // '<:' -> '['
1257 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1258 } else if (Features.Digraphs && Char == '>') {
1259 Result.SetKind(tok::l_brace); // '<%' -> '{'
1260 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1261 } else if (Features.CPPMinMax && Char == '?') { // <?
1262 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerd01e2912006-06-18 16:22:51 +00001263 Diag(BufferPtr, diag::min_max_deprecated);
Chris Lattner22eb9722006-06-18 05:43:12 +00001264
1265 if (getCharAndSize(CurPtr, SizeTmp) == '=') { // <?=
1266 Result.SetKind(tok::lessquestionequal);
1267 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1268 } else {
1269 Result.SetKind(tok::lessquestion);
1270 }
1271 } else {
1272 Result.SetKind(tok::less);
1273 }
1274 break;
1275 case '>':
1276 Char = getCharAndSize(CurPtr, SizeTmp);
1277 if (Char == '=') {
1278 Result.SetKind(tok::greaterequal);
1279 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1280 } else if (Char == '>' &&
1281 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '=') {
1282 Result.SetKind(tok::greatergreaterequal);
1283 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1284 SizeTmp2, Result);
1285 } else if (Char == '>') {
1286 Result.SetKind(tok::greatergreater);
1287 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1288 } else if (Features.CPPMinMax && Char == '?') {
1289 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerd01e2912006-06-18 16:22:51 +00001290 Diag(BufferPtr, diag::min_max_deprecated);
Chris Lattner22eb9722006-06-18 05:43:12 +00001291
1292 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
1293 Result.SetKind(tok::greaterquestionequal); // >?=
1294 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1295 } else {
1296 Result.SetKind(tok::greaterquestion); // >?
1297 }
1298 } else {
1299 Result.SetKind(tok::greater);
1300 }
1301 break;
1302 case '^':
1303 Char = getCharAndSize(CurPtr, SizeTmp);
1304 if (Char == '=') {
1305 Result.SetKind(tok::caretequal);
1306 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1307 } else {
1308 Result.SetKind(tok::caret);
1309 }
1310 break;
1311 case '|':
1312 Char = getCharAndSize(CurPtr, SizeTmp);
1313 if (Char == '=') {
1314 Result.SetKind(tok::pipeequal);
1315 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1316 } else if (Char == '|') {
1317 Result.SetKind(tok::pipepipe);
1318 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1319 } else {
1320 Result.SetKind(tok::pipe);
1321 }
1322 break;
1323 case ':':
1324 Char = getCharAndSize(CurPtr, SizeTmp);
1325 if (Features.Digraphs && Char == '>') {
1326 Result.SetKind(tok::r_square); // ':>' -> ']'
1327 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1328 } else if (Features.CPlusPlus && Char == ':') {
1329 Result.SetKind(tok::coloncolon);
1330 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1331 } else {
1332 Result.SetKind(tok::colon);
1333 }
1334 break;
1335 case ';':
1336 Result.SetKind(tok::semi);
1337 break;
1338 case '=':
1339 Char = getCharAndSize(CurPtr, SizeTmp);
1340 if (Char == '=') {
1341 Result.SetKind(tok::equalequal);
1342 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1343 } else {
1344 Result.SetKind(tok::equal);
1345 }
1346 break;
1347 case ',':
1348 Result.SetKind(tok::comma);
1349 break;
1350 case '#':
1351 Char = getCharAndSize(CurPtr, SizeTmp);
1352 if (Char == '#') {
1353 Result.SetKind(tok::hashhash);
1354 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1355 } else {
1356 Result.SetKind(tok::hash);
1357 // We parsed a # character. If this occurs at the start of the line,
1358 // it's actually the start of a preprocessing directive. Callback to
1359 // the preprocessor to handle it.
Chris Lattner505c5472006-07-03 00:55:48 +00001360 // FIXME: -fpreprocessed mode??
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001361 if (Result.isAtStartOfLine() && !LexingRawMode) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001362 BufferPtr = CurPtr;
Chris Lattnercb283342006-06-18 06:48:37 +00001363 PP.HandleDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001364
1365 // As an optimization, if the preprocessor didn't switch lexers, tail
1366 // recurse.
1367 if (PP.isCurrentLexer(this)) {
1368 // Start a new token. If this is a #include or something, the PP may
1369 // want us starting at the beginning of the line again. If so, set
1370 // the StartOfLine flag.
1371 if (IsAtStartOfLine) {
1372 Result.SetFlag(LexerToken::StartOfLine);
1373 IsAtStartOfLine = false;
1374 }
1375 goto LexNextToken; // GCC isn't tail call eliminating.
1376 }
1377 return PP.Lex(Result);
1378 }
1379 }
1380 break;
1381
1382 case '\\':
Chris Lattner505c5472006-07-03 00:55:48 +00001383 // FIXME: UCN's.
Chris Lattner22eb9722006-06-18 05:43:12 +00001384 // FALL THROUGH.
1385 default:
1386 // Objective C support.
1387 if (CurPtr[-1] == '@' && Features.ObjC1) {
1388 Result.SetKind(tok::at);
1389 break;
1390 } else if (CurPtr[-1] == '$' && Features.DollarIdents) {// $ in identifiers.
Chris Lattnercb283342006-06-18 06:48:37 +00001391 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
Chris Lattner371ac8a2006-07-04 07:11:10 +00001392 // Notify MIOpt that we read a non-whitespace/non-comment token.
1393 MIOpt.ReadToken();
Chris Lattner22eb9722006-06-18 05:43:12 +00001394 return LexIdentifier(Result, CurPtr);
1395 }
1396
Chris Lattner041bef82006-07-11 05:52:53 +00001397 Result.SetKind(tok::unknown);
1398 break;
Chris Lattner22eb9722006-06-18 05:43:12 +00001399 }
1400
Chris Lattner371ac8a2006-07-04 07:11:10 +00001401 // Notify MIOpt that we read a non-whitespace/non-comment token.
1402 MIOpt.ReadToken();
1403
Chris Lattnerd01e2912006-06-18 16:22:51 +00001404 // Update the location of token as well as BufferPtr.
1405 FormTokenWithChars(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +00001406}