blob: 893ff04d82e99ee9b9de2768a100f593c57b1aad [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)
42 : BufferPtr(BufStart ? BufStart : File->getBufferStart()),
Chris Lattner4cca5ba2006-07-02 20:05:54 +000043 BufferEnd(BufEnd ? BufEnd : File->getBufferEnd()),
44 InputFile(File), CurFileID(fileid), PP(pp), Features(PP.getLangOptions()) {
Chris Lattnerecfeafe2006-07-02 21:26:45 +000045 Is_PragmaLexer = false;
Chris Lattner4ec473f2006-07-03 05:16:05 +000046 IsMainFile = false;
Chris Lattner22eb9722006-06-18 05:43:12 +000047 InitCharacterInfo();
48
49 assert(BufferEnd[0] == 0 &&
50 "We assume that the input buffer has a null character at the end"
51 " to simplify lexing!");
52
53 // Start of the file is a start of line.
54 IsAtStartOfLine = true;
55
56 // We are not after parsing a #.
57 ParsingPreprocessorDirective = false;
58
59 // We are not after parsing #include.
60 ParsingFilename = false;
61}
62
Chris Lattnere3e81ea2006-07-03 01:13:26 +000063/// Stringify - Convert the specified string into a C string, with surrounding
64/// ""'s, and with escaped \ and " characters.
65std::string Lexer::Stringify(const std::string &Str) {
66 std::string Result = Str;
67 for (unsigned i = 0, e = Result.size(); i != e; ++i) {
68 if (Result[i] == '\\' || Result[i] == '"') {
69 Result.insert(Result.begin()+i, '\\');
70 ++i; ++e;
71 }
72 }
73
74 // Add quotes.
75 return '"' + Result + '"';
76}
77
Chris Lattner22eb9722006-06-18 05:43:12 +000078
Chris Lattner22eb9722006-06-18 05:43:12 +000079//===----------------------------------------------------------------------===//
80// Character information.
81//===----------------------------------------------------------------------===//
82
83static unsigned char CharInfo[256];
84
85enum {
86 CHAR_HORZ_WS = 0x01, // ' ', '\t', '\f', '\v'. Note, no '\0'
87 CHAR_VERT_WS = 0x02, // '\r', '\n'
88 CHAR_LETTER = 0x04, // a-z,A-Z
89 CHAR_NUMBER = 0x08, // 0-9
90 CHAR_UNDER = 0x10, // _
91 CHAR_PERIOD = 0x20 // .
92};
93
94static void InitCharacterInfo() {
95 static bool isInited = false;
96 if (isInited) return;
97 isInited = true;
98
99 // Intiialize the CharInfo table.
100 // TODO: statically initialize this.
101 CharInfo[(int)' '] = CharInfo[(int)'\t'] =
102 CharInfo[(int)'\f'] = CharInfo[(int)'\v'] = CHAR_HORZ_WS;
103 CharInfo[(int)'\n'] = CharInfo[(int)'\r'] = CHAR_VERT_WS;
104
105 CharInfo[(int)'_'] = CHAR_UNDER;
106 for (unsigned i = 'a'; i <= 'z'; ++i)
107 CharInfo[i] = CharInfo[i+'A'-'a'] = CHAR_LETTER;
108 for (unsigned i = '0'; i <= '9'; ++i)
109 CharInfo[i] = CHAR_NUMBER;
110}
111
112/// isIdentifierBody - Return true if this is the body character of an
113/// identifier, which is [a-zA-Z0-9_].
114static inline bool isIdentifierBody(unsigned char c) {
115 return CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER);
116}
117
118/// isHorizontalWhitespace - Return true if this character is horizontal
119/// whitespace: ' ', '\t', '\f', '\v'. Note that this returns false for '\0'.
120static inline bool isHorizontalWhitespace(unsigned char c) {
121 return CharInfo[c] & CHAR_HORZ_WS;
122}
123
124/// isWhitespace - Return true if this character is horizontal or vertical
125/// whitespace: ' ', '\t', '\f', '\v', '\n', '\r'. Note that this returns false
126/// for '\0'.
127static inline bool isWhitespace(unsigned char c) {
128 return CharInfo[c] & (CHAR_HORZ_WS|CHAR_VERT_WS);
129}
130
131/// isNumberBody - Return true if this is the body character of an
132/// preprocessing number, which is [a-zA-Z0-9_.].
133static inline bool isNumberBody(unsigned char c) {
134 return CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER|CHAR_PERIOD);
135}
136
Chris Lattnerd01e2912006-06-18 16:22:51 +0000137
Chris Lattner22eb9722006-06-18 05:43:12 +0000138//===----------------------------------------------------------------------===//
139// Diagnostics forwarding code.
140//===----------------------------------------------------------------------===//
141
142/// getSourceLocation - Return a source location identifier for the specified
143/// offset in the current file.
144SourceLocation Lexer::getSourceLocation(const char *Loc) const {
Chris Lattner8bbfe462006-07-02 22:27:49 +0000145 assert(Loc >= InputFile->getBufferStart() && Loc <= BufferEnd &&
Chris Lattner4cca5ba2006-07-02 20:05:54 +0000146 "Location out of range for this buffer!");
Chris Lattner8bbfe462006-07-02 22:27:49 +0000147 return SourceLocation(CurFileID, Loc-InputFile->getBufferStart());
Chris Lattner22eb9722006-06-18 05:43:12 +0000148}
149
150
151/// Diag - Forwarding function for diagnostics. This translate a source
152/// position in the current buffer into a SourceLocation object for rendering.
Chris Lattnercb283342006-06-18 06:48:37 +0000153void Lexer::Diag(const char *Loc, unsigned DiagID,
Chris Lattner22eb9722006-06-18 05:43:12 +0000154 const std::string &Msg) const {
Chris Lattnercb283342006-06-18 06:48:37 +0000155 PP.Diag(getSourceLocation(Loc), DiagID, Msg);
Chris Lattner22eb9722006-06-18 05:43:12 +0000156}
157
158//===----------------------------------------------------------------------===//
159// Trigraph and Escaped Newline Handling Code.
160//===----------------------------------------------------------------------===//
161
162/// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
163/// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
164static char GetTrigraphCharForLetter(char Letter) {
165 switch (Letter) {
166 default: return 0;
167 case '=': return '#';
168 case ')': return ']';
169 case '(': return '[';
170 case '!': return '|';
171 case '\'': return '^';
172 case '>': return '}';
173 case '/': return '\\';
174 case '<': return '{';
175 case '-': return '~';
176 }
177}
178
179/// DecodeTrigraphChar - If the specified character is a legal trigraph when
180/// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
181/// return the result character. Finally, emit a warning about trigraph use
182/// whether trigraphs are enabled or not.
183static char DecodeTrigraphChar(const char *CP, Lexer *L) {
184 char Res = GetTrigraphCharForLetter(*CP);
185 if (Res && L) {
186 if (!L->getFeatures().Trigraphs) {
187 L->Diag(CP-2, diag::trigraph_ignored);
188 return 0;
189 } else {
190 L->Diag(CP-2, diag::trigraph_converted, std::string()+Res);
191 }
192 }
193 return Res;
194}
195
196/// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
197/// get its size, and return it. This is tricky in several cases:
198/// 1. If currently at the start of a trigraph, we warn about the trigraph,
199/// then either return the trigraph (skipping 3 chars) or the '?',
200/// depending on whether trigraphs are enabled or not.
201/// 2. If this is an escaped newline (potentially with whitespace between
202/// the backslash and newline), implicitly skip the newline and return
203/// the char after it.
Chris Lattner505c5472006-07-03 00:55:48 +0000204/// 3. If this is a UCN, return it. FIXME: C++ UCN's?
Chris Lattner22eb9722006-06-18 05:43:12 +0000205///
206/// This handles the slow/uncommon case of the getCharAndSize method. Here we
207/// know that we can accumulate into Size, and that we have already incremented
208/// Ptr by Size bytes.
209///
Chris Lattnerd01e2912006-06-18 16:22:51 +0000210/// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
211/// be updated to match.
Chris Lattner22eb9722006-06-18 05:43:12 +0000212///
213char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
214 LexerToken *Tok) {
215 // If we have a slash, look for an escaped newline.
216 if (Ptr[0] == '\\') {
217 ++Size;
218 ++Ptr;
219Slash:
220 // Common case, backslash-char where the char is not whitespace.
221 if (!isWhitespace(Ptr[0])) return '\\';
222
223 // See if we have optional whitespace characters followed by a newline.
224 {
225 unsigned SizeTmp = 0;
226 do {
227 ++SizeTmp;
228 if (Ptr[SizeTmp-1] == '\n' || Ptr[SizeTmp-1] == '\r') {
229 // Remember that this token needs to be cleaned.
230 if (Tok) Tok->SetFlag(LexerToken::NeedsCleaning);
231
232 // Warn if there was whitespace between the backslash and newline.
233 if (SizeTmp != 1 && Tok)
234 Diag(Ptr, diag::backslash_newline_space);
235
236 // If this is a \r\n or \n\r, skip the newlines.
237 if ((Ptr[SizeTmp] == '\r' || Ptr[SizeTmp] == '\n') &&
238 Ptr[SizeTmp-1] != Ptr[SizeTmp])
239 ++SizeTmp;
240
241 // Found backslash<whitespace><newline>. Parse the char after it.
242 Size += SizeTmp;
243 Ptr += SizeTmp;
244 // Use slow version to accumulate a correct size field.
245 return getCharAndSizeSlow(Ptr, Size, Tok);
246 }
247 } while (isWhitespace(Ptr[SizeTmp]));
248 }
249
250 // Otherwise, this is not an escaped newline, just return the slash.
251 return '\\';
252 }
253
254 // If this is a trigraph, process it.
255 if (Ptr[0] == '?' && Ptr[1] == '?') {
256 // If this is actually a legal trigraph (not something like "??x"), emit
257 // a trigraph warning. If so, and if trigraphs are enabled, return it.
258 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : 0)) {
259 // Remember that this token needs to be cleaned.
260 if (Tok) Tok->SetFlag(LexerToken::NeedsCleaning);
261
262 Ptr += 3;
263 Size += 3;
264 if (C == '\\') goto Slash;
265 return C;
266 }
267 }
268
269 // If this is neither, return a single character.
270 ++Size;
271 return *Ptr;
272}
273
Chris Lattnerd01e2912006-06-18 16:22:51 +0000274
Chris Lattner22eb9722006-06-18 05:43:12 +0000275/// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
276/// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
277/// and that we have already incremented Ptr by Size bytes.
278///
Chris Lattnerd01e2912006-06-18 16:22:51 +0000279/// NOTE: When this method is updated, getCharAndSizeSlow (above) should
280/// be updated to match.
281char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
Chris Lattner22eb9722006-06-18 05:43:12 +0000282 const LangOptions &Features) {
283 // If we have a slash, look for an escaped newline.
284 if (Ptr[0] == '\\') {
285 ++Size;
286 ++Ptr;
287Slash:
288 // Common case, backslash-char where the char is not whitespace.
289 if (!isWhitespace(Ptr[0])) return '\\';
290
291 // See if we have optional whitespace characters followed by a newline.
292 {
293 unsigned SizeTmp = 0;
294 do {
295 ++SizeTmp;
296 if (Ptr[SizeTmp-1] == '\n' || Ptr[SizeTmp-1] == '\r') {
297
298 // If this is a \r\n or \n\r, skip the newlines.
299 if ((Ptr[SizeTmp] == '\r' || Ptr[SizeTmp] == '\n') &&
300 Ptr[SizeTmp-1] != Ptr[SizeTmp])
301 ++SizeTmp;
302
303 // Found backslash<whitespace><newline>. Parse the char after it.
304 Size += SizeTmp;
305 Ptr += SizeTmp;
306
307 // Use slow version to accumulate a correct size field.
308 return getCharAndSizeSlowNoWarn(Ptr, Size, Features);
309 }
310 } while (isWhitespace(Ptr[SizeTmp]));
311 }
312
313 // Otherwise, this is not an escaped newline, just return the slash.
314 return '\\';
315 }
316
317 // If this is a trigraph, process it.
318 if (Features.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
319 // If this is actually a legal trigraph (not something like "??x"), return
320 // it.
321 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
322 Ptr += 3;
323 Size += 3;
324 if (C == '\\') goto Slash;
325 return C;
326 }
327 }
328
329 // If this is neither, return a single character.
330 ++Size;
331 return *Ptr;
332}
333
Chris Lattner22eb9722006-06-18 05:43:12 +0000334//===----------------------------------------------------------------------===//
335// Helper methods for lexing.
336//===----------------------------------------------------------------------===//
337
Chris Lattnercb283342006-06-18 06:48:37 +0000338void Lexer::LexIdentifier(LexerToken &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000339 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
340 unsigned Size;
341 unsigned char C = *CurPtr++;
342 while (isIdentifierBody(C)) {
343 C = *CurPtr++;
344 }
345 --CurPtr; // Back up over the skipped character.
346
347 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
348 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
Chris Lattner505c5472006-07-03 00:55:48 +0000349 // FIXME: UCNs.
Chris Lattner22eb9722006-06-18 05:43:12 +0000350 if (C != '\\' && C != '?' && (C != '$' || !Features.DollarIdents)) {
351FinishIdentifier:
Chris Lattnercefc7682006-07-08 08:28:12 +0000352 const char *IdStart = BufferPtr;
Chris Lattnerd01e2912006-06-18 16:22:51 +0000353 FormTokenWithChars(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +0000354 Result.SetKind(tok::identifier);
355
Chris Lattnercefc7682006-07-08 08:28:12 +0000356 // Fill in Result.IdentifierInfo, looking up the identifier in the
357 // identifier table.
358 PP.LookUpIdentifierInfo(Result, IdStart);
Chris Lattner22eb9722006-06-18 05:43:12 +0000359
Chris Lattnerc5a00062006-06-18 16:41:01 +0000360 // Finally, now that we know we have an identifier, pass this off to the
361 // preprocessor, which may macro expand it or something.
Chris Lattner22eb9722006-06-18 05:43:12 +0000362 return PP.HandleIdentifier(Result);
363 }
364
365 // Otherwise, $,\,? in identifier found. Enter slower path.
366
367 C = getCharAndSize(CurPtr, Size);
368 while (1) {
369 if (C == '$') {
370 // If we hit a $ and they are not supported in identifiers, we are done.
371 if (!Features.DollarIdents) goto FinishIdentifier;
372
373 // Otherwise, emit a diagnostic and continue.
Chris Lattnercb283342006-06-18 06:48:37 +0000374 Diag(CurPtr, diag::ext_dollar_in_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +0000375 CurPtr = ConsumeChar(CurPtr, Size, Result);
376 C = getCharAndSize(CurPtr, Size);
377 continue;
Chris Lattner505c5472006-07-03 00:55:48 +0000378 } else if (!isIdentifierBody(C)) { // FIXME: UCNs.
Chris Lattner22eb9722006-06-18 05:43:12 +0000379 // Found end of identifier.
380 goto FinishIdentifier;
381 }
382
383 // Otherwise, this character is good, consume it.
384 CurPtr = ConsumeChar(CurPtr, Size, Result);
385
386 C = getCharAndSize(CurPtr, Size);
Chris Lattner505c5472006-07-03 00:55:48 +0000387 while (isIdentifierBody(C)) { // FIXME: UCNs.
Chris Lattner22eb9722006-06-18 05:43:12 +0000388 CurPtr = ConsumeChar(CurPtr, Size, Result);
389 C = getCharAndSize(CurPtr, Size);
390 }
391 }
392}
393
394
395/// LexNumericConstant - Lex the remainer of a integer or floating point
396/// constant. From[-1] is the first character lexed. Return the end of the
397/// constant.
Chris Lattnercb283342006-06-18 06:48:37 +0000398void Lexer::LexNumericConstant(LexerToken &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000399 unsigned Size;
400 char C = getCharAndSize(CurPtr, Size);
401 char PrevCh = 0;
Chris Lattner505c5472006-07-03 00:55:48 +0000402 while (isNumberBody(C)) { // FIXME: UCNs?
Chris Lattner22eb9722006-06-18 05:43:12 +0000403 CurPtr = ConsumeChar(CurPtr, Size, Result);
404 PrevCh = C;
405 C = getCharAndSize(CurPtr, Size);
406 }
407
408 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
409 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e'))
410 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
411
412 // If we have a hex FP constant, continue.
413 if (Features.HexFloats &&
414 (C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p'))
415 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
416
417 Result.SetKind(tok::numeric_constant);
418
Chris Lattnerd01e2912006-06-18 16:22:51 +0000419 // Update the location of token as well as BufferPtr.
420 FormTokenWithChars(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +0000421}
422
423/// LexStringLiteral - Lex the remainder of a string literal, after having lexed
424/// either " or L".
Chris Lattnercb283342006-06-18 06:48:37 +0000425void Lexer::LexStringLiteral(LexerToken &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000426 const char *NulCharacter = 0; // Does this string contain the \0 character?
427
428 char C = getAndAdvanceChar(CurPtr, Result);
429 while (C != '"') {
430 // Skip escaped characters.
431 if (C == '\\') {
432 // Skip the escaped character.
433 C = getAndAdvanceChar(CurPtr, Result);
434 } else if (C == '\n' || C == '\r' || // Newline.
435 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000436 Diag(BufferPtr, diag::err_unterminated_string);
Chris Lattner22eb9722006-06-18 05:43:12 +0000437 BufferPtr = CurPtr-1;
438 return LexTokenInternal(Result);
439 } else if (C == 0) {
440 NulCharacter = CurPtr-1;
441 }
442 C = getAndAdvanceChar(CurPtr, Result);
443 }
444
Chris Lattnercb283342006-06-18 06:48:37 +0000445 if (NulCharacter) Diag(NulCharacter, diag::null_in_string);
Chris Lattner22eb9722006-06-18 05:43:12 +0000446
447 Result.SetKind(tok::string_literal);
448
Chris Lattnerd01e2912006-06-18 16:22:51 +0000449 // Update the location of the token as well as the BufferPtr instance var.
450 FormTokenWithChars(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +0000451}
452
453/// LexAngledStringLiteral - Lex the remainder of an angled string literal,
454/// after having lexed the '<' character. This is used for #include filenames.
Chris Lattnercb283342006-06-18 06:48:37 +0000455void Lexer::LexAngledStringLiteral(LexerToken &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000456 const char *NulCharacter = 0; // Does this string contain the \0 character?
457
458 char C = getAndAdvanceChar(CurPtr, Result);
459 while (C != '>') {
460 // Skip escaped characters.
461 if (C == '\\') {
462 // Skip the escaped character.
463 C = getAndAdvanceChar(CurPtr, Result);
464 } else if (C == '\n' || C == '\r' || // Newline.
465 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000466 Diag(BufferPtr, diag::err_unterminated_string);
Chris Lattner22eb9722006-06-18 05:43:12 +0000467 BufferPtr = CurPtr-1;
468 return LexTokenInternal(Result);
469 } else if (C == 0) {
470 NulCharacter = CurPtr-1;
471 }
472 C = getAndAdvanceChar(CurPtr, Result);
473 }
474
Chris Lattnercb283342006-06-18 06:48:37 +0000475 if (NulCharacter) Diag(NulCharacter, diag::null_in_string);
Chris Lattner22eb9722006-06-18 05:43:12 +0000476
477 Result.SetKind(tok::angle_string_literal);
478
Chris Lattnerd01e2912006-06-18 16:22:51 +0000479 // Update the location of token as well as BufferPtr.
480 FormTokenWithChars(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +0000481}
482
483
484/// LexCharConstant - Lex the remainder of a character constant, after having
485/// lexed either ' or L'.
Chris Lattnercb283342006-06-18 06:48:37 +0000486void Lexer::LexCharConstant(LexerToken &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000487 const char *NulCharacter = 0; // Does this character contain the \0 character?
488
489 // Handle the common case of 'x' and '\y' efficiently.
490 char C = getAndAdvanceChar(CurPtr, Result);
491 if (C == '\'') {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000492 Diag(BufferPtr, diag::err_empty_character);
Chris Lattner22eb9722006-06-18 05:43:12 +0000493 BufferPtr = CurPtr;
494 return LexTokenInternal(Result);
495 } else if (C == '\\') {
496 // Skip the escaped character.
497 // FIXME: UCN's.
498 C = getAndAdvanceChar(CurPtr, Result);
499 }
500
501 if (C && C != '\n' && C != '\r' && CurPtr[0] == '\'') {
502 ++CurPtr;
503 } else {
504 // Fall back on generic code for embedded nulls, newlines, wide chars.
505 do {
506 // Skip escaped characters.
507 if (C == '\\') {
508 // Skip the escaped character.
509 C = getAndAdvanceChar(CurPtr, Result);
510 } else if (C == '\n' || C == '\r' || // Newline.
511 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000512 Diag(BufferPtr, diag::err_unterminated_char);
Chris Lattner22eb9722006-06-18 05:43:12 +0000513 BufferPtr = CurPtr-1;
514 return LexTokenInternal(Result);
515 } else if (C == 0) {
516 NulCharacter = CurPtr-1;
517 }
518 C = getAndAdvanceChar(CurPtr, Result);
519 } while (C != '\'');
520 }
521
Chris Lattnercb283342006-06-18 06:48:37 +0000522 if (NulCharacter) Diag(NulCharacter, diag::null_in_char);
Chris Lattner22eb9722006-06-18 05:43:12 +0000523
524 Result.SetKind(tok::char_constant);
525
Chris Lattnerd01e2912006-06-18 16:22:51 +0000526 // Update the location of token as well as BufferPtr.
527 FormTokenWithChars(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +0000528}
529
530/// SkipWhitespace - Efficiently skip over a series of whitespace characters.
531/// Update BufferPtr to point to the next non-whitespace character and return.
Chris Lattnercb283342006-06-18 06:48:37 +0000532void Lexer::SkipWhitespace(LexerToken &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000533 // Whitespace - Skip it, then return the token after the whitespace.
534 unsigned char Char = *CurPtr; // Skip consequtive spaces efficiently.
535 while (1) {
536 // Skip horizontal whitespace very aggressively.
537 while (isHorizontalWhitespace(Char))
538 Char = *++CurPtr;
539
540 // Otherwise if we something other than whitespace, we're done.
541 if (Char != '\n' && Char != '\r')
542 break;
543
544 if (ParsingPreprocessorDirective) {
545 // End of preprocessor directive line, let LexTokenInternal handle this.
546 BufferPtr = CurPtr;
Chris Lattnercb283342006-06-18 06:48:37 +0000547 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000548 }
549
550 // ok, but handle newline.
551 // The returned token is at the start of the line.
552 Result.SetFlag(LexerToken::StartOfLine);
553 // No leading whitespace seen so far.
554 Result.ClearFlag(LexerToken::LeadingSpace);
555 Char = *++CurPtr;
556 }
557
558 // If this isn't immediately after a newline, there is leading space.
559 char PrevChar = CurPtr[-1];
560 if (PrevChar != '\n' && PrevChar != '\r')
561 Result.SetFlag(LexerToken::LeadingSpace);
562
563 // If the next token is obviously a // or /* */ comment, skip it efficiently
564 // too (without going through the big switch stmt).
565 if (Char == '/' && CurPtr[1] == '/') {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000566 BufferPtr = CurPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +0000567 return SkipBCPLComment(Result, CurPtr+1);
568 }
569 if (Char == '/' && CurPtr[1] == '*') {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000570 BufferPtr = CurPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +0000571 return SkipBlockComment(Result, CurPtr+2);
572 }
573 BufferPtr = CurPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +0000574}
575
576// SkipBCPLComment - We have just read the // characters from input. Skip until
577// we find the newline character thats terminate the comment. Then update
578/// BufferPtr and return.
Chris Lattnercb283342006-06-18 06:48:37 +0000579void Lexer::SkipBCPLComment(LexerToken &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000580 // If BCPL comments aren't explicitly enabled for this language, emit an
581 // extension warning.
582 if (!Features.BCPLComment) {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000583 Diag(BufferPtr, diag::ext_bcpl_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +0000584
585 // Mark them enabled so we only emit one warning for this translation
586 // unit.
587 Features.BCPLComment = true;
588 }
589
590 // Scan over the body of the comment. The common case, when scanning, is that
591 // the comment contains normal ascii characters with nothing interesting in
592 // them. As such, optimize for this case with the inner loop.
593 char C;
594 do {
595 C = *CurPtr;
Chris Lattner505c5472006-07-03 00:55:48 +0000596 // FIXME: Speedup BCPL comment lexing. Just scan for a \n or \r character.
597 // If we find a \n character, scan backwards, checking to see if it's an
598 // escaped newline, like we do for block comments.
Chris Lattner22eb9722006-06-18 05:43:12 +0000599
600 // Skip over characters in the fast loop.
601 while (C != 0 && // Potentially EOF.
602 C != '\\' && // Potentially escaped newline.
603 C != '?' && // Potentially trigraph.
604 C != '\n' && C != '\r') // Newline or DOS-style newline.
605 C = *++CurPtr;
606
607 // If this is a newline, we're done.
608 if (C == '\n' || C == '\r')
609 break; // Found the newline? Break out!
610
611 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
612 // properly decode the character.
613 const char *OldPtr = CurPtr;
614 C = getAndAdvanceChar(CurPtr, Result);
615
616 // If we read multiple characters, and one of those characters was a \r or
617 // \n, then we had an escaped newline within the comment. Emit diagnostic.
618 if (CurPtr != OldPtr+1) {
619 for (; OldPtr != CurPtr; ++OldPtr)
620 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
Chris Lattnercb283342006-06-18 06:48:37 +0000621 Diag(OldPtr-1, diag::ext_multi_line_bcpl_comment);
622 break;
Chris Lattner22eb9722006-06-18 05:43:12 +0000623 }
624 }
625
626 if (CurPtr == BufferEnd+1) goto FoundEOF;
627 } while (C != '\n' && C != '\r');
628
629 // Found and did not consume a newline.
630
631 // If we are inside a preprocessor directive and we see the end of line,
632 // return immediately, so that the lexer can return this as an EOM token.
633 if (ParsingPreprocessorDirective) {
634 BufferPtr = CurPtr;
Chris Lattnercb283342006-06-18 06:48:37 +0000635 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000636 }
637
638 // Otherwise, eat the \n character. We don't care if this is a \n\r or
639 // \r\n sequence.
640 ++CurPtr;
641
642 // The next returned token is at the start of the line.
643 Result.SetFlag(LexerToken::StartOfLine);
644 // No leading whitespace seen so far.
645 Result.ClearFlag(LexerToken::LeadingSpace);
646
647 // It is common for the tokens immediately after a // comment to be
648 // whitespace (indentation for the next line). Instead of going through the
649 // big switch, handle it efficiently now.
650 if (isWhitespace(*CurPtr)) {
651 Result.SetFlag(LexerToken::LeadingSpace);
652 return SkipWhitespace(Result, CurPtr+1);
653 }
654
655 BufferPtr = CurPtr;
Chris Lattnercb283342006-06-18 06:48:37 +0000656 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000657
658FoundEOF: // If we ran off the end of the buffer, return EOF.
659 BufferPtr = CurPtr-1;
Chris Lattnercb283342006-06-18 06:48:37 +0000660 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000661}
662
Chris Lattnercb283342006-06-18 06:48:37 +0000663/// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
664/// character (either \n or \r) is part of an escaped newline sequence. Issue a
Chris Lattner22eb9722006-06-18 05:43:12 +0000665/// diagnostic if so. We know that the is inside of a block comment.
Chris Lattner1f583052006-06-18 06:53:56 +0000666static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
667 Lexer *L) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000668 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
Chris Lattner22eb9722006-06-18 05:43:12 +0000669
670 // Back up off the newline.
671 --CurPtr;
672
673 // If this is a two-character newline sequence, skip the other character.
674 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
675 // \n\n or \r\r -> not escaped newline.
676 if (CurPtr[0] == CurPtr[1])
677 return false;
678 // \n\r or \r\n -> skip the newline.
679 --CurPtr;
680 }
681
682 // If we have horizontal whitespace, skip over it. We allow whitespace
683 // between the slash and newline.
684 bool HasSpace = false;
685 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
686 --CurPtr;
687 HasSpace = true;
688 }
689
690 // If we have a slash, we know this is an escaped newline.
691 if (*CurPtr == '\\') {
Chris Lattnercb283342006-06-18 06:48:37 +0000692 if (CurPtr[-1] != '*') return false;
Chris Lattner22eb9722006-06-18 05:43:12 +0000693 } else {
694 // It isn't a slash, is it the ?? / trigraph?
Chris Lattnercb283342006-06-18 06:48:37 +0000695 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
696 CurPtr[-3] != '*')
Chris Lattner22eb9722006-06-18 05:43:12 +0000697 return false;
Chris Lattnercb283342006-06-18 06:48:37 +0000698
699 // This is the trigraph ending the comment. Emit a stern warning!
Chris Lattner22eb9722006-06-18 05:43:12 +0000700 CurPtr -= 2;
701
702 // If no trigraphs are enabled, warn that we ignored this trigraph and
703 // ignore this * character.
Chris Lattner1f583052006-06-18 06:53:56 +0000704 if (!L->getFeatures().Trigraphs) {
705 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
Chris Lattnercb283342006-06-18 06:48:37 +0000706 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +0000707 }
Chris Lattner1f583052006-06-18 06:53:56 +0000708 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +0000709 }
710
711 // Warn about having an escaped newline between the */ characters.
Chris Lattner1f583052006-06-18 06:53:56 +0000712 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
Chris Lattner22eb9722006-06-18 05:43:12 +0000713
714 // If there was space between the backslash and newline, warn about it.
Chris Lattner1f583052006-06-18 06:53:56 +0000715 if (HasSpace) L->Diag(CurPtr, diag::backslash_newline_space);
Chris Lattner22eb9722006-06-18 05:43:12 +0000716
Chris Lattnercb283342006-06-18 06:48:37 +0000717 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +0000718}
719
720/// SkipBlockComment - We have just read the /* characters from input. Read
721/// until we find the */ characters that terminate the comment. Note that we
722/// don't bother decoding trigraphs or escaped newlines in block comments,
723/// because they cannot cause the comment to end. The only thing that can
724/// happen is the comment could end with an escaped newline between the */ end
725/// of comment.
Chris Lattnercb283342006-06-18 06:48:37 +0000726void Lexer::SkipBlockComment(LexerToken &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000727 // Scan one character past where we should, looking for a '/' character. Once
728 // we find it, check to see if it was preceeded by a *. This common
729 // optimization helps people who like to put a lot of * characters in their
730 // comments.
731 unsigned char C = *CurPtr++;
732 if (C == 0 && CurPtr == BufferEnd+1) {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000733 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +0000734 BufferPtr = CurPtr-1;
Chris Lattnercb283342006-06-18 06:48:37 +0000735 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000736 }
737
738 while (1) {
739 // Skip over all non-interesting characters.
740 // TODO: Vectorize this. Note: memchr on Darwin is slower than this loop.
741 while (C != '/' && C != '\0')
742 C = *CurPtr++;
743
744 if (C == '/') {
Chris Lattner22eb9722006-06-18 05:43:12 +0000745 if (CurPtr[-2] == '*') // We found the final */. We're done!
746 break;
747
748 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
Chris Lattner1f583052006-06-18 06:53:56 +0000749 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000750 // We found the final */, though it had an escaped newline between the
751 // * and /. We're done!
752 break;
753 }
754 }
755 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
756 // If this is a /* inside of the comment, emit a warning. Don't do this
757 // if this is a /*/, which will end the comment. This misses cases with
758 // embedded escaped newlines, but oh well.
Chris Lattnercb283342006-06-18 06:48:37 +0000759 Diag(CurPtr-1, diag::nested_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +0000760 }
761 } else if (C == 0 && CurPtr == BufferEnd+1) {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000762 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +0000763 // Note: the user probably forgot a */. We could continue immediately
764 // after the /*, but this would involve lexing a lot of what really is the
765 // comment, which surely would confuse the parser.
766 BufferPtr = CurPtr-1;
Chris Lattnercb283342006-06-18 06:48:37 +0000767 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000768 }
769 C = *CurPtr++;
770 }
771
772 // It is common for the tokens immediately after a /**/ comment to be
773 // whitespace. Instead of going through the big switch, handle it
774 // efficiently now.
775 if (isHorizontalWhitespace(*CurPtr)) {
776 Result.SetFlag(LexerToken::LeadingSpace);
777 return SkipWhitespace(Result, CurPtr+1);
778 }
779
780 // Otherwise, just return so that the next character will be lexed as a token.
781 BufferPtr = CurPtr;
782 Result.SetFlag(LexerToken::LeadingSpace);
Chris Lattner22eb9722006-06-18 05:43:12 +0000783}
784
785//===----------------------------------------------------------------------===//
786// Primary Lexing Entry Points
787//===----------------------------------------------------------------------===//
788
789/// LexIncludeFilename - After the preprocessor has parsed a #include, lex and
790/// (potentially) macro expand the filename.
Chris Lattner269c2322006-06-25 06:23:00 +0000791std::string Lexer::LexIncludeFilename(LexerToken &FilenameTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000792 assert(ParsingPreprocessorDirective &&
793 ParsingFilename == false &&
794 "Must be in a preprocessing directive!");
795
796 // We are now parsing a filename!
797 ParsingFilename = true;
798
Chris Lattner269c2322006-06-25 06:23:00 +0000799 // Lex the filename.
800 Lex(FilenameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +0000801
802 // We should have gotten the filename now.
803 ParsingFilename = false;
804
805 // No filename?
Chris Lattner269c2322006-06-25 06:23:00 +0000806 if (FilenameTok.getKind() == tok::eom) {
807 PP.Diag(FilenameTok, diag::err_pp_expects_filename);
808 return "";
Chris Lattnercb283342006-06-18 06:48:37 +0000809 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000810
Chris Lattner269c2322006-06-25 06:23:00 +0000811 // Get the text form of the filename.
812 std::string Filename = PP.getSpelling(FilenameTok);
813 assert(!Filename.empty() && "Can't have tokens with empty spellings!");
814
815 // Make sure the filename is <x> or "x".
816 if (Filename[0] == '<') {
817 if (Filename[Filename.size()-1] != '>') {
818 PP.Diag(FilenameTok, diag::err_pp_expects_filename);
819 FilenameTok.SetKind(tok::eom);
820 return "";
821 }
822 } else if (Filename[0] == '"') {
823 if (Filename[Filename.size()-1] != '"') {
824 PP.Diag(FilenameTok, diag::err_pp_expects_filename);
825 FilenameTok.SetKind(tok::eom);
826 return "";
827 }
828 } else {
829 PP.Diag(FilenameTok, diag::err_pp_expects_filename);
830 FilenameTok.SetKind(tok::eom);
831 return "";
Chris Lattner22eb9722006-06-18 05:43:12 +0000832 }
Chris Lattner269c2322006-06-25 06:23:00 +0000833
834 // Diagnose #include "" as invalid.
835 if (Filename.size() == 2) {
836 PP.Diag(FilenameTok, diag::err_pp_empty_filename);
837 FilenameTok.SetKind(tok::eom);
838 return "";
839 }
840
841 return Filename;
Chris Lattner22eb9722006-06-18 05:43:12 +0000842}
843
844/// ReadToEndOfLine - Read the rest of the current preprocessor line as an
845/// uninterpreted string. This switches the lexer out of directive mode.
846std::string Lexer::ReadToEndOfLine() {
847 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
848 "Must be in a preprocessing directive!");
849 std::string Result;
850 LexerToken Tmp;
851
852 // CurPtr - Cache BufferPtr in an automatic variable.
853 const char *CurPtr = BufferPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +0000854 while (1) {
855 char Char = getAndAdvanceChar(CurPtr, Tmp);
856 switch (Char) {
857 default:
858 Result += Char;
859 break;
860 case 0: // Null.
861 // Found end of file?
862 if (CurPtr-1 != BufferEnd) {
863 // Nope, normal character, continue.
864 Result += Char;
865 break;
866 }
867 // FALL THROUGH.
868 case '\r':
869 case '\n':
870 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
871 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
872 BufferPtr = CurPtr-1;
873
874 // Next, lex the character, which should handle the EOM transition.
Chris Lattnercb283342006-06-18 06:48:37 +0000875 Lex(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +0000876 assert(Tmp.getKind() == tok::eom && "Unexpected token!");
Chris Lattner22eb9722006-06-18 05:43:12 +0000877
878 // Finally, we're done, return the string we found.
879 return Result;
880 }
881 }
882}
883
884/// LexEndOfFile - CurPtr points to the end of this file. Handle this
885/// condition, reporting diagnostics and handling other edge cases as required.
Chris Lattnercb283342006-06-18 06:48:37 +0000886void Lexer::LexEndOfFile(LexerToken &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000887 // If we hit the end of the file while parsing a preprocessor directive,
888 // end the preprocessor directive first. The next token returned will
889 // then be the end of file.
890 if (ParsingPreprocessorDirective) {
891 // Done parsing the "line".
892 ParsingPreprocessorDirective = false;
893 Result.SetKind(tok::eom);
Chris Lattnerd01e2912006-06-18 16:22:51 +0000894 // Update the location of token as well as BufferPtr.
895 FormTokenWithChars(Result, CurPtr);
Chris Lattnercb283342006-06-18 06:48:37 +0000896 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000897 }
898
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000899 // If we aren't skipping, issue diagnostics. If we are skipping, let the
900 // skipping code do this: there are multiple possible reasons for skipping,
901 // and not all want these diagnostics.
902 if (!PP.isSkipping()) {
903 // If we are in a #if directive, emit an error.
904 while (!ConditionalStack.empty()) {
905 PP.Diag(ConditionalStack.back().IfLoc,
906 diag::err_pp_unterminated_conditional);
907 ConditionalStack.pop_back();
908 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000909
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000910 // If the file was empty or didn't end in a newline, issue a pedwarn.
911 if (CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
912 Diag(BufferEnd, diag::ext_no_newline_eof);
913 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000914
915 BufferPtr = CurPtr;
Chris Lattnercb283342006-06-18 06:48:37 +0000916 PP.HandleEndOfFile(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +0000917}
918
919
920/// LexTokenInternal - This implements a simple C family lexer. It is an
921/// extremely performance critical piece of code. This assumes that the buffer
922/// has a null character at the end of the file. Return true if an error
923/// occurred and compilation should terminate, false if normal. This returns a
924/// preprocessing token, not a normal token, as such, it is an internal
925/// interface. It assumes that the Flags of result have been cleared before
926/// calling this.
Chris Lattnercb283342006-06-18 06:48:37 +0000927void Lexer::LexTokenInternal(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000928LexNextToken:
929 // New token, can't need cleaning yet.
930 Result.ClearFlag(LexerToken::NeedsCleaning);
Chris Lattner27746e42006-07-05 00:07:54 +0000931 Result.SetIdentifierInfo(0);
Chris Lattner22eb9722006-06-18 05:43:12 +0000932
933 // CurPtr - Cache BufferPtr in an automatic variable.
934 const char *CurPtr = BufferPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +0000935
Chris Lattnereb54b592006-07-10 06:34:27 +0000936 // Small amounts of horizontal whitespace is very common between tokens.
937 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
938 ++CurPtr;
939 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
940 ++CurPtr;
941 BufferPtr = CurPtr;
942 Result.SetFlag(LexerToken::LeadingSpace);
943 }
944
Chris Lattner22eb9722006-06-18 05:43:12 +0000945 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
946
947 // Read a character, advancing over it.
948 char Char = getAndAdvanceChar(CurPtr, Result);
949 switch (Char) {
950 case 0: // Null.
951 // Found end of file?
952 if (CurPtr-1 == BufferEnd)
953 return LexEndOfFile(Result, CurPtr-1); // Retreat back into the file.
954
Chris Lattnercb283342006-06-18 06:48:37 +0000955 Diag(CurPtr-1, diag::null_in_file);
Chris Lattner22eb9722006-06-18 05:43:12 +0000956 Result.SetFlag(LexerToken::LeadingSpace);
Chris Lattnercb283342006-06-18 06:48:37 +0000957 SkipWhitespace(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +0000958 goto LexNextToken; // GCC isn't tail call eliminating.
959 case '\n':
960 case '\r':
961 // If we are inside a preprocessor directive and we see the end of line,
962 // we know we are done with the directive, so return an EOM token.
963 if (ParsingPreprocessorDirective) {
964 // Done parsing the "line".
965 ParsingPreprocessorDirective = false;
966
967 // Since we consumed a newline, we are back at the start of a line.
968 IsAtStartOfLine = true;
969
970 Result.SetKind(tok::eom);
971 break;
972 }
973 // The returned token is at the start of the line.
974 Result.SetFlag(LexerToken::StartOfLine);
975 // No leading whitespace seen so far.
976 Result.ClearFlag(LexerToken::LeadingSpace);
Chris Lattnercb283342006-06-18 06:48:37 +0000977 SkipWhitespace(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +0000978 goto LexNextToken; // GCC isn't tail call eliminating.
979 case ' ':
980 case '\t':
981 case '\f':
982 case '\v':
983 Result.SetFlag(LexerToken::LeadingSpace);
Chris Lattnercb283342006-06-18 06:48:37 +0000984 SkipWhitespace(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +0000985 goto LexNextToken; // GCC isn't tail call eliminating.
986
987 case 'L':
Chris Lattner371ac8a2006-07-04 07:11:10 +0000988 // Notify MIOpt that we read a non-whitespace/non-comment token.
989 MIOpt.ReadToken();
Chris Lattner22eb9722006-06-18 05:43:12 +0000990 Char = getCharAndSize(CurPtr, SizeTmp);
991
992 // Wide string literal.
993 if (Char == '"')
994 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result));
995
996 // Wide character constant.
997 if (Char == '\'')
998 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
999 // FALL THROUGH, treating L like the start of an identifier.
1000
1001 // C99 6.4.2: Identifiers.
1002 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
1003 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
1004 case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U':
1005 case 'V': case 'W': case 'X': case 'Y': case 'Z':
1006 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
1007 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
1008 case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u':
1009 case 'v': case 'w': case 'x': case 'y': case 'z':
1010 case '_':
Chris Lattner371ac8a2006-07-04 07:11:10 +00001011 // Notify MIOpt that we read a non-whitespace/non-comment token.
1012 MIOpt.ReadToken();
Chris Lattner22eb9722006-06-18 05:43:12 +00001013 return LexIdentifier(Result, CurPtr);
1014
1015 // C99 6.4.4.1: Integer Constants.
1016 // C99 6.4.4.2: Floating Constants.
1017 case '0': case '1': case '2': case '3': case '4':
1018 case '5': case '6': case '7': case '8': case '9':
Chris Lattner371ac8a2006-07-04 07:11:10 +00001019 // Notify MIOpt that we read a non-whitespace/non-comment token.
1020 MIOpt.ReadToken();
Chris Lattner22eb9722006-06-18 05:43:12 +00001021 return LexNumericConstant(Result, CurPtr);
1022
1023 // C99 6.4.4: Character Constants.
1024 case '\'':
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 return LexCharConstant(Result, CurPtr);
1028
1029 // C99 6.4.5: String Literals.
1030 case '"':
Chris Lattner371ac8a2006-07-04 07:11:10 +00001031 // Notify MIOpt that we read a non-whitespace/non-comment token.
1032 MIOpt.ReadToken();
Chris Lattner22eb9722006-06-18 05:43:12 +00001033 return LexStringLiteral(Result, CurPtr);
1034
1035 // C99 6.4.6: Punctuators.
1036 case '?':
1037 Result.SetKind(tok::question);
1038 break;
1039 case '[':
1040 Result.SetKind(tok::l_square);
1041 break;
1042 case ']':
1043 Result.SetKind(tok::r_square);
1044 break;
1045 case '(':
1046 Result.SetKind(tok::l_paren);
1047 break;
1048 case ')':
1049 Result.SetKind(tok::r_paren);
1050 break;
1051 case '{':
1052 Result.SetKind(tok::l_brace);
1053 break;
1054 case '}':
1055 Result.SetKind(tok::r_brace);
1056 break;
1057 case '.':
1058 Char = getCharAndSize(CurPtr, SizeTmp);
1059 if (Char >= '0' && Char <= '9') {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001060 // Notify MIOpt that we read a non-whitespace/non-comment token.
1061 MIOpt.ReadToken();
1062
Chris Lattner22eb9722006-06-18 05:43:12 +00001063 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
1064 } else if (Features.CPlusPlus && Char == '*') {
1065 Result.SetKind(tok::periodstar);
1066 CurPtr += SizeTmp;
1067 } else if (Char == '.' &&
1068 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
1069 Result.SetKind(tok::ellipsis);
1070 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1071 SizeTmp2, Result);
1072 } else {
1073 Result.SetKind(tok::period);
1074 }
1075 break;
1076 case '&':
1077 Char = getCharAndSize(CurPtr, SizeTmp);
1078 if (Char == '&') {
1079 Result.SetKind(tok::ampamp);
1080 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1081 } else if (Char == '=') {
1082 Result.SetKind(tok::ampequal);
1083 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1084 } else {
1085 Result.SetKind(tok::amp);
1086 }
1087 break;
1088 case '*':
1089 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
1090 Result.SetKind(tok::starequal);
1091 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1092 } else {
1093 Result.SetKind(tok::star);
1094 }
1095 break;
1096 case '+':
1097 Char = getCharAndSize(CurPtr, SizeTmp);
1098 if (Char == '+') {
1099 Result.SetKind(tok::plusplus);
1100 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1101 } else if (Char == '=') {
1102 Result.SetKind(tok::plusequal);
1103 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1104 } else {
1105 Result.SetKind(tok::plus);
1106 }
1107 break;
1108 case '-':
1109 Char = getCharAndSize(CurPtr, SizeTmp);
1110 if (Char == '-') {
1111 Result.SetKind(tok::minusminus);
1112 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1113 } else if (Char == '>' && Features.CPlusPlus &&
1114 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') {
1115 Result.SetKind(tok::arrowstar); // C++ ->*
1116 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1117 SizeTmp2, Result);
1118 } else if (Char == '>') {
1119 Result.SetKind(tok::arrow);
1120 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1121 } else if (Char == '=') {
1122 Result.SetKind(tok::minusequal);
1123 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1124 } else {
1125 Result.SetKind(tok::minus);
1126 }
1127 break;
1128 case '~':
1129 Result.SetKind(tok::tilde);
1130 break;
1131 case '!':
1132 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
1133 Result.SetKind(tok::exclaimequal);
1134 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1135 } else {
1136 Result.SetKind(tok::exclaim);
1137 }
1138 break;
1139 case '/':
1140 // 6.4.9: Comments
1141 Char = getCharAndSize(CurPtr, SizeTmp);
1142 if (Char == '/') { // BCPL comment.
1143 Result.SetFlag(LexerToken::LeadingSpace);
Chris Lattnercb283342006-06-18 06:48:37 +00001144 SkipBCPLComment(Result, ConsumeChar(CurPtr, SizeTmp, Result));
Chris Lattner22eb9722006-06-18 05:43:12 +00001145 goto LexNextToken; // GCC isn't tail call eliminating.
1146 } else if (Char == '*') { // /**/ comment.
1147 Result.SetFlag(LexerToken::LeadingSpace);
Chris Lattnercb283342006-06-18 06:48:37 +00001148 SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result));
Chris Lattner22eb9722006-06-18 05:43:12 +00001149 goto LexNextToken; // GCC isn't tail call eliminating.
1150 } else if (Char == '=') {
1151 Result.SetKind(tok::slashequal);
1152 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1153 } else {
1154 Result.SetKind(tok::slash);
1155 }
1156 break;
1157 case '%':
1158 Char = getCharAndSize(CurPtr, SizeTmp);
1159 if (Char == '=') {
1160 Result.SetKind(tok::percentequal);
1161 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1162 } else if (Features.Digraphs && Char == '>') {
1163 Result.SetKind(tok::r_brace); // '%>' -> '}'
1164 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1165 } else if (Features.Digraphs && Char == ':') {
1166 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1167 if (getCharAndSize(CurPtr, SizeTmp) == '%' &&
1168 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
1169 Result.SetKind(tok::hashhash); // '%:%:' -> '##'
1170 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1171 SizeTmp2, Result);
1172 } else {
1173 Result.SetKind(tok::hash); // '%:' -> '#'
1174
1175 // We parsed a # character. If this occurs at the start of the line,
1176 // it's actually the start of a preprocessing directive. Callback to
1177 // the preprocessor to handle it.
1178 // FIXME: -fpreprocessed mode??
1179 if (Result.isAtStartOfLine() && !PP.isSkipping()) {
1180 BufferPtr = CurPtr;
Chris Lattnercb283342006-06-18 06:48:37 +00001181 PP.HandleDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001182
1183 // As an optimization, if the preprocessor didn't switch lexers, tail
1184 // recurse.
1185 if (PP.isCurrentLexer(this)) {
1186 // Start a new token. If this is a #include or something, the PP may
1187 // want us starting at the beginning of the line again. If so, set
1188 // the StartOfLine flag.
1189 if (IsAtStartOfLine) {
1190 Result.SetFlag(LexerToken::StartOfLine);
1191 IsAtStartOfLine = false;
1192 }
1193 goto LexNextToken; // GCC isn't tail call eliminating.
1194 }
1195
1196 return PP.Lex(Result);
1197 }
1198 }
1199 } else {
1200 Result.SetKind(tok::percent);
1201 }
1202 break;
1203 case '<':
1204 Char = getCharAndSize(CurPtr, SizeTmp);
1205 if (ParsingFilename) {
1206 return LexAngledStringLiteral(Result, CurPtr+SizeTmp);
1207 } else if (Char == '<' &&
1208 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '=') {
1209 Result.SetKind(tok::lesslessequal);
1210 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1211 SizeTmp2, Result);
1212 } else if (Char == '<') {
1213 Result.SetKind(tok::lessless);
1214 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1215 } else if (Char == '=') {
1216 Result.SetKind(tok::lessequal);
1217 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1218 } else if (Features.Digraphs && Char == ':') {
1219 Result.SetKind(tok::l_square); // '<:' -> '['
1220 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1221 } else if (Features.Digraphs && Char == '>') {
1222 Result.SetKind(tok::l_brace); // '<%' -> '{'
1223 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1224 } else if (Features.CPPMinMax && Char == '?') { // <?
1225 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerd01e2912006-06-18 16:22:51 +00001226 Diag(BufferPtr, diag::min_max_deprecated);
Chris Lattner22eb9722006-06-18 05:43:12 +00001227
1228 if (getCharAndSize(CurPtr, SizeTmp) == '=') { // <?=
1229 Result.SetKind(tok::lessquestionequal);
1230 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1231 } else {
1232 Result.SetKind(tok::lessquestion);
1233 }
1234 } else {
1235 Result.SetKind(tok::less);
1236 }
1237 break;
1238 case '>':
1239 Char = getCharAndSize(CurPtr, SizeTmp);
1240 if (Char == '=') {
1241 Result.SetKind(tok::greaterequal);
1242 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1243 } else if (Char == '>' &&
1244 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '=') {
1245 Result.SetKind(tok::greatergreaterequal);
1246 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1247 SizeTmp2, Result);
1248 } else if (Char == '>') {
1249 Result.SetKind(tok::greatergreater);
1250 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1251 } else if (Features.CPPMinMax && Char == '?') {
1252 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerd01e2912006-06-18 16:22:51 +00001253 Diag(BufferPtr, diag::min_max_deprecated);
Chris Lattner22eb9722006-06-18 05:43:12 +00001254
1255 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
1256 Result.SetKind(tok::greaterquestionequal); // >?=
1257 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1258 } else {
1259 Result.SetKind(tok::greaterquestion); // >?
1260 }
1261 } else {
1262 Result.SetKind(tok::greater);
1263 }
1264 break;
1265 case '^':
1266 Char = getCharAndSize(CurPtr, SizeTmp);
1267 if (Char == '=') {
1268 Result.SetKind(tok::caretequal);
1269 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1270 } else {
1271 Result.SetKind(tok::caret);
1272 }
1273 break;
1274 case '|':
1275 Char = getCharAndSize(CurPtr, SizeTmp);
1276 if (Char == '=') {
1277 Result.SetKind(tok::pipeequal);
1278 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1279 } else if (Char == '|') {
1280 Result.SetKind(tok::pipepipe);
1281 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1282 } else {
1283 Result.SetKind(tok::pipe);
1284 }
1285 break;
1286 case ':':
1287 Char = getCharAndSize(CurPtr, SizeTmp);
1288 if (Features.Digraphs && Char == '>') {
1289 Result.SetKind(tok::r_square); // ':>' -> ']'
1290 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1291 } else if (Features.CPlusPlus && Char == ':') {
1292 Result.SetKind(tok::coloncolon);
1293 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1294 } else {
1295 Result.SetKind(tok::colon);
1296 }
1297 break;
1298 case ';':
1299 Result.SetKind(tok::semi);
1300 break;
1301 case '=':
1302 Char = getCharAndSize(CurPtr, SizeTmp);
1303 if (Char == '=') {
1304 Result.SetKind(tok::equalequal);
1305 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1306 } else {
1307 Result.SetKind(tok::equal);
1308 }
1309 break;
1310 case ',':
1311 Result.SetKind(tok::comma);
1312 break;
1313 case '#':
1314 Char = getCharAndSize(CurPtr, SizeTmp);
1315 if (Char == '#') {
1316 Result.SetKind(tok::hashhash);
1317 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1318 } else {
1319 Result.SetKind(tok::hash);
1320 // We parsed a # character. If this occurs at the start of the line,
1321 // it's actually the start of a preprocessing directive. Callback to
1322 // the preprocessor to handle it.
Chris Lattner505c5472006-07-03 00:55:48 +00001323 // FIXME: -fpreprocessed mode??
Chris Lattner22eb9722006-06-18 05:43:12 +00001324 if (Result.isAtStartOfLine() && !PP.isSkipping()) {
1325 BufferPtr = CurPtr;
Chris Lattnercb283342006-06-18 06:48:37 +00001326 PP.HandleDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001327
1328 // As an optimization, if the preprocessor didn't switch lexers, tail
1329 // recurse.
1330 if (PP.isCurrentLexer(this)) {
1331 // Start a new token. If this is a #include or something, the PP may
1332 // want us starting at the beginning of the line again. If so, set
1333 // the StartOfLine flag.
1334 if (IsAtStartOfLine) {
1335 Result.SetFlag(LexerToken::StartOfLine);
1336 IsAtStartOfLine = false;
1337 }
1338 goto LexNextToken; // GCC isn't tail call eliminating.
1339 }
1340 return PP.Lex(Result);
1341 }
1342 }
1343 break;
1344
1345 case '\\':
Chris Lattner505c5472006-07-03 00:55:48 +00001346 // FIXME: UCN's.
Chris Lattner22eb9722006-06-18 05:43:12 +00001347 // FALL THROUGH.
1348 default:
1349 // Objective C support.
1350 if (CurPtr[-1] == '@' && Features.ObjC1) {
1351 Result.SetKind(tok::at);
1352 break;
1353 } else if (CurPtr[-1] == '$' && Features.DollarIdents) {// $ in identifiers.
Chris Lattnercb283342006-06-18 06:48:37 +00001354 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
Chris Lattner371ac8a2006-07-04 07:11:10 +00001355 // Notify MIOpt that we read a non-whitespace/non-comment token.
1356 MIOpt.ReadToken();
Chris Lattner22eb9722006-06-18 05:43:12 +00001357 return LexIdentifier(Result, CurPtr);
1358 }
1359
Chris Lattnercb283342006-06-18 06:48:37 +00001360 if (!PP.isSkipping()) Diag(CurPtr-1, diag::err_stray_character);
Chris Lattner22eb9722006-06-18 05:43:12 +00001361 BufferPtr = CurPtr;
1362 goto LexNextToken; // GCC isn't tail call eliminating.
1363 }
1364
Chris Lattner371ac8a2006-07-04 07:11:10 +00001365 // Notify MIOpt that we read a non-whitespace/non-comment token.
1366 MIOpt.ReadToken();
1367
Chris Lattnerd01e2912006-06-18 16:22:51 +00001368 // Update the location of token as well as BufferPtr.
1369 FormTokenWithChars(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +00001370}