blob: 51d4c73190a40f6515af4406839b6b77ca0a820f [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 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!");
51
52 // Start of the file is a start of line.
53 IsAtStartOfLine = true;
54
55 // We are not after parsing a #.
56 ParsingPreprocessorDirective = false;
57
58 // We are not after parsing #include.
59 ParsingFilename = false;
60}
61
Chris Lattnere3e81ea2006-07-03 01:13:26 +000062/// Stringify - Convert the specified string into a C string, with surrounding
63/// ""'s, and with escaped \ and " characters.
64std::string Lexer::Stringify(const std::string &Str) {
65 std::string Result = Str;
66 for (unsigned i = 0, e = Result.size(); i != e; ++i) {
67 if (Result[i] == '\\' || Result[i] == '"') {
68 Result.insert(Result.begin()+i, '\\');
69 ++i; ++e;
70 }
71 }
72
73 // Add quotes.
74 return '"' + Result + '"';
75}
76
Chris Lattner22eb9722006-06-18 05:43:12 +000077
Chris Lattner22eb9722006-06-18 05:43:12 +000078//===----------------------------------------------------------------------===//
79// Character information.
80//===----------------------------------------------------------------------===//
81
82static unsigned char CharInfo[256];
83
84enum {
85 CHAR_HORZ_WS = 0x01, // ' ', '\t', '\f', '\v'. Note, no '\0'
86 CHAR_VERT_WS = 0x02, // '\r', '\n'
87 CHAR_LETTER = 0x04, // a-z,A-Z
88 CHAR_NUMBER = 0x08, // 0-9
89 CHAR_UNDER = 0x10, // _
90 CHAR_PERIOD = 0x20 // .
91};
92
93static void InitCharacterInfo() {
94 static bool isInited = false;
95 if (isInited) return;
96 isInited = true;
97
98 // Intiialize the CharInfo table.
99 // TODO: statically initialize this.
100 CharInfo[(int)' '] = CharInfo[(int)'\t'] =
101 CharInfo[(int)'\f'] = CharInfo[(int)'\v'] = CHAR_HORZ_WS;
102 CharInfo[(int)'\n'] = CharInfo[(int)'\r'] = CHAR_VERT_WS;
103
104 CharInfo[(int)'_'] = CHAR_UNDER;
105 for (unsigned i = 'a'; i <= 'z'; ++i)
106 CharInfo[i] = CharInfo[i+'A'-'a'] = CHAR_LETTER;
107 for (unsigned i = '0'; i <= '9'; ++i)
108 CharInfo[i] = CHAR_NUMBER;
109}
110
111/// isIdentifierBody - Return true if this is the body character of an
112/// identifier, which is [a-zA-Z0-9_].
113static inline bool isIdentifierBody(unsigned char c) {
114 return CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER);
115}
116
117/// isHorizontalWhitespace - Return true if this character is horizontal
118/// whitespace: ' ', '\t', '\f', '\v'. Note that this returns false for '\0'.
119static inline bool isHorizontalWhitespace(unsigned char c) {
120 return CharInfo[c] & CHAR_HORZ_WS;
121}
122
123/// isWhitespace - Return true if this character is horizontal or vertical
124/// whitespace: ' ', '\t', '\f', '\v', '\n', '\r'. Note that this returns false
125/// for '\0'.
126static inline bool isWhitespace(unsigned char c) {
127 return CharInfo[c] & (CHAR_HORZ_WS|CHAR_VERT_WS);
128}
129
130/// isNumberBody - Return true if this is the body character of an
131/// preprocessing number, which is [a-zA-Z0-9_.].
132static inline bool isNumberBody(unsigned char c) {
133 return CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER|CHAR_PERIOD);
134}
135
Chris Lattnerd01e2912006-06-18 16:22:51 +0000136
Chris Lattner22eb9722006-06-18 05:43:12 +0000137//===----------------------------------------------------------------------===//
138// Diagnostics forwarding code.
139//===----------------------------------------------------------------------===//
140
141/// getSourceLocation - Return a source location identifier for the specified
142/// offset in the current file.
143SourceLocation Lexer::getSourceLocation(const char *Loc) const {
Chris Lattner8bbfe462006-07-02 22:27:49 +0000144 assert(Loc >= InputFile->getBufferStart() && Loc <= BufferEnd &&
Chris Lattner4cca5ba2006-07-02 20:05:54 +0000145 "Location out of range for this buffer!");
Chris Lattner8bbfe462006-07-02 22:27:49 +0000146 return SourceLocation(CurFileID, Loc-InputFile->getBufferStart());
Chris Lattner22eb9722006-06-18 05:43:12 +0000147}
148
149
150/// Diag - Forwarding function for diagnostics. This translate a source
151/// position in the current buffer into a SourceLocation object for rendering.
Chris Lattnercb283342006-06-18 06:48:37 +0000152void Lexer::Diag(const char *Loc, unsigned DiagID,
Chris Lattner22eb9722006-06-18 05:43:12 +0000153 const std::string &Msg) const {
Chris Lattnercb283342006-06-18 06:48:37 +0000154 PP.Diag(getSourceLocation(Loc), DiagID, Msg);
Chris Lattner22eb9722006-06-18 05:43:12 +0000155}
156
157//===----------------------------------------------------------------------===//
158// Trigraph and Escaped Newline Handling Code.
159//===----------------------------------------------------------------------===//
160
161/// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
162/// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
163static char GetTrigraphCharForLetter(char Letter) {
164 switch (Letter) {
165 default: return 0;
166 case '=': return '#';
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 }
176}
177
178/// DecodeTrigraphChar - If the specified character is a legal trigraph when
179/// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
180/// return the result character. Finally, emit a warning about trigraph use
181/// whether trigraphs are enabled or not.
182static char DecodeTrigraphChar(const char *CP, Lexer *L) {
183 char Res = GetTrigraphCharForLetter(*CP);
184 if (Res && L) {
185 if (!L->getFeatures().Trigraphs) {
186 L->Diag(CP-2, diag::trigraph_ignored);
187 return 0;
188 } else {
189 L->Diag(CP-2, diag::trigraph_converted, std::string()+Res);
190 }
191 }
192 return Res;
193}
194
195/// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
196/// get its size, and return it. This is tricky in several cases:
197/// 1. If currently at the start of a trigraph, we warn about the trigraph,
198/// then either return the trigraph (skipping 3 chars) or the '?',
199/// depending on whether trigraphs are enabled or not.
200/// 2. If this is an escaped newline (potentially with whitespace between
201/// the backslash and newline), implicitly skip the newline and return
202/// the char after it.
Chris Lattner505c5472006-07-03 00:55:48 +0000203/// 3. If this is a UCN, return it. FIXME: C++ UCN's?
Chris Lattner22eb9722006-06-18 05:43:12 +0000204///
205/// This handles the slow/uncommon case of the getCharAndSize method. Here we
206/// know that we can accumulate into Size, and that we have already incremented
207/// Ptr by Size bytes.
208///
Chris Lattnerd01e2912006-06-18 16:22:51 +0000209/// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
210/// be updated to match.
Chris Lattner22eb9722006-06-18 05:43:12 +0000211///
212char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
213 LexerToken *Tok) {
214 // If we have a slash, look for an escaped newline.
215 if (Ptr[0] == '\\') {
216 ++Size;
217 ++Ptr;
218Slash:
219 // Common case, backslash-char where the char is not whitespace.
220 if (!isWhitespace(Ptr[0])) return '\\';
221
222 // See if we have optional whitespace characters followed by a newline.
223 {
224 unsigned SizeTmp = 0;
225 do {
226 ++SizeTmp;
227 if (Ptr[SizeTmp-1] == '\n' || Ptr[SizeTmp-1] == '\r') {
228 // Remember that this token needs to be cleaned.
229 if (Tok) Tok->SetFlag(LexerToken::NeedsCleaning);
230
231 // Warn if there was whitespace between the backslash and newline.
232 if (SizeTmp != 1 && Tok)
233 Diag(Ptr, diag::backslash_newline_space);
234
235 // If this is a \r\n or \n\r, skip the newlines.
236 if ((Ptr[SizeTmp] == '\r' || Ptr[SizeTmp] == '\n') &&
237 Ptr[SizeTmp-1] != Ptr[SizeTmp])
238 ++SizeTmp;
239
240 // Found backslash<whitespace><newline>. Parse the char after it.
241 Size += SizeTmp;
242 Ptr += SizeTmp;
243 // Use slow version to accumulate a correct size field.
244 return getCharAndSizeSlow(Ptr, Size, Tok);
245 }
246 } while (isWhitespace(Ptr[SizeTmp]));
247 }
248
249 // Otherwise, this is not an escaped newline, just return the slash.
250 return '\\';
251 }
252
253 // If this is a trigraph, process it.
254 if (Ptr[0] == '?' && Ptr[1] == '?') {
255 // If this is actually a legal trigraph (not something like "??x"), emit
256 // a trigraph warning. If so, and if trigraphs are enabled, return it.
257 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : 0)) {
258 // Remember that this token needs to be cleaned.
259 if (Tok) Tok->SetFlag(LexerToken::NeedsCleaning);
260
261 Ptr += 3;
262 Size += 3;
263 if (C == '\\') goto Slash;
264 return C;
265 }
266 }
267
268 // If this is neither, return a single character.
269 ++Size;
270 return *Ptr;
271}
272
Chris Lattnerd01e2912006-06-18 16:22:51 +0000273
Chris Lattner22eb9722006-06-18 05:43:12 +0000274/// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
275/// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
276/// and that we have already incremented Ptr by Size bytes.
277///
Chris Lattnerd01e2912006-06-18 16:22:51 +0000278/// NOTE: When this method is updated, getCharAndSizeSlow (above) should
279/// be updated to match.
280char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
Chris Lattner22eb9722006-06-18 05:43:12 +0000281 const LangOptions &Features) {
282 // If we have a slash, look for an escaped newline.
283 if (Ptr[0] == '\\') {
284 ++Size;
285 ++Ptr;
286Slash:
287 // Common case, backslash-char where the char is not whitespace.
288 if (!isWhitespace(Ptr[0])) return '\\';
289
290 // See if we have optional whitespace characters followed by a newline.
291 {
292 unsigned SizeTmp = 0;
293 do {
294 ++SizeTmp;
295 if (Ptr[SizeTmp-1] == '\n' || Ptr[SizeTmp-1] == '\r') {
296
297 // If this is a \r\n or \n\r, skip the newlines.
298 if ((Ptr[SizeTmp] == '\r' || Ptr[SizeTmp] == '\n') &&
299 Ptr[SizeTmp-1] != Ptr[SizeTmp])
300 ++SizeTmp;
301
302 // Found backslash<whitespace><newline>. Parse the char after it.
303 Size += SizeTmp;
304 Ptr += SizeTmp;
305
306 // Use slow version to accumulate a correct size field.
307 return getCharAndSizeSlowNoWarn(Ptr, Size, Features);
308 }
309 } while (isWhitespace(Ptr[SizeTmp]));
310 }
311
312 // Otherwise, this is not an escaped newline, just return the slash.
313 return '\\';
314 }
315
316 // If this is a trigraph, process it.
317 if (Features.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
318 // If this is actually a legal trigraph (not something like "??x"), return
319 // it.
320 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
321 Ptr += 3;
322 Size += 3;
323 if (C == '\\') goto Slash;
324 return C;
325 }
326 }
327
328 // If this is neither, return a single character.
329 ++Size;
330 return *Ptr;
331}
332
Chris Lattner22eb9722006-06-18 05:43:12 +0000333//===----------------------------------------------------------------------===//
334// Helper methods for lexing.
335//===----------------------------------------------------------------------===//
336
Chris Lattnercb283342006-06-18 06:48:37 +0000337void Lexer::LexIdentifier(LexerToken &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000338 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
339 unsigned Size;
340 unsigned char C = *CurPtr++;
341 while (isIdentifierBody(C)) {
342 C = *CurPtr++;
343 }
344 --CurPtr; // Back up over the skipped character.
345
346 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
347 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
Chris Lattner505c5472006-07-03 00:55:48 +0000348 // FIXME: UCNs.
Chris Lattner22eb9722006-06-18 05:43:12 +0000349 if (C != '\\' && C != '?' && (C != '$' || !Features.DollarIdents)) {
350FinishIdentifier:
Chris Lattnerd01e2912006-06-18 16:22:51 +0000351 const char *IdStart = BufferPtr, *IdEnd = CurPtr;
352 FormTokenWithChars(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +0000353 Result.SetKind(tok::identifier);
354
355 // Look up this token, see if it is a macro, or if it is a language keyword.
Chris Lattnerc5a00062006-06-18 16:41:01 +0000356 IdentifierTokenInfo *II;
Chris Lattner22eb9722006-06-18 05:43:12 +0000357 if (!Result.needsCleaning()) {
358 // No cleaning needed, just use the characters from the lexed buffer.
Chris Lattnerc5a00062006-06-18 16:41:01 +0000359 II = PP.getIdentifierInfo(IdStart, IdEnd);
Chris Lattner22eb9722006-06-18 05:43:12 +0000360 } else {
361 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
Chris Lattner33ce7282006-06-18 07:35:33 +0000362 char *TmpBuf = (char*)alloca(Result.getLength());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000363 unsigned Size = PP.getSpelling(Result, TmpBuf);
Chris Lattnerc5a00062006-06-18 16:41:01 +0000364 II = PP.getIdentifierInfo(TmpBuf, TmpBuf+Size);
Chris Lattner22eb9722006-06-18 05:43:12 +0000365 }
Chris Lattnerc5a00062006-06-18 16:41:01 +0000366 Result.SetIdentifierInfo(II);
Chris Lattner22eb9722006-06-18 05:43:12 +0000367
Chris Lattnerc5a00062006-06-18 16:41:01 +0000368 // Finally, now that we know we have an identifier, pass this off to the
369 // preprocessor, which may macro expand it or something.
Chris Lattner22eb9722006-06-18 05:43:12 +0000370 return PP.HandleIdentifier(Result);
371 }
372
373 // Otherwise, $,\,? in identifier found. Enter slower path.
374
375 C = getCharAndSize(CurPtr, Size);
376 while (1) {
377 if (C == '$') {
378 // If we hit a $ and they are not supported in identifiers, we are done.
379 if (!Features.DollarIdents) goto FinishIdentifier;
380
381 // Otherwise, emit a diagnostic and continue.
Chris Lattnercb283342006-06-18 06:48:37 +0000382 Diag(CurPtr, diag::ext_dollar_in_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +0000383 CurPtr = ConsumeChar(CurPtr, Size, Result);
384 C = getCharAndSize(CurPtr, Size);
385 continue;
Chris Lattner505c5472006-07-03 00:55:48 +0000386 } else if (!isIdentifierBody(C)) { // FIXME: UCNs.
Chris Lattner22eb9722006-06-18 05:43:12 +0000387 // Found end of identifier.
388 goto FinishIdentifier;
389 }
390
391 // Otherwise, this character is good, consume it.
392 CurPtr = ConsumeChar(CurPtr, Size, Result);
393
394 C = getCharAndSize(CurPtr, Size);
Chris Lattner505c5472006-07-03 00:55:48 +0000395 while (isIdentifierBody(C)) { // FIXME: UCNs.
Chris Lattner22eb9722006-06-18 05:43:12 +0000396 CurPtr = ConsumeChar(CurPtr, Size, Result);
397 C = getCharAndSize(CurPtr, Size);
398 }
399 }
400}
401
402
403/// LexNumericConstant - Lex the remainer of a integer or floating point
404/// constant. From[-1] is the first character lexed. Return the end of the
405/// constant.
Chris Lattnercb283342006-06-18 06:48:37 +0000406void Lexer::LexNumericConstant(LexerToken &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000407 unsigned Size;
408 char C = getCharAndSize(CurPtr, Size);
409 char PrevCh = 0;
Chris Lattner505c5472006-07-03 00:55:48 +0000410 while (isNumberBody(C)) { // FIXME: UCNs?
Chris Lattner22eb9722006-06-18 05:43:12 +0000411 CurPtr = ConsumeChar(CurPtr, Size, Result);
412 PrevCh = C;
413 C = getCharAndSize(CurPtr, Size);
414 }
415
416 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
417 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e'))
418 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
419
420 // If we have a hex FP constant, continue.
421 if (Features.HexFloats &&
422 (C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p'))
423 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
424
425 Result.SetKind(tok::numeric_constant);
426
Chris Lattnerd01e2912006-06-18 16:22:51 +0000427 // Update the location of token as well as BufferPtr.
428 FormTokenWithChars(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +0000429}
430
431/// LexStringLiteral - Lex the remainder of a string literal, after having lexed
432/// either " or L".
Chris Lattnercb283342006-06-18 06:48:37 +0000433void Lexer::LexStringLiteral(LexerToken &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000434 const char *NulCharacter = 0; // Does this string contain the \0 character?
435
436 char C = getAndAdvanceChar(CurPtr, Result);
437 while (C != '"') {
438 // Skip escaped characters.
439 if (C == '\\') {
440 // Skip the escaped character.
441 C = getAndAdvanceChar(CurPtr, Result);
442 } else if (C == '\n' || C == '\r' || // Newline.
443 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000444 Diag(BufferPtr, diag::err_unterminated_string);
Chris Lattner22eb9722006-06-18 05:43:12 +0000445 BufferPtr = CurPtr-1;
446 return LexTokenInternal(Result);
447 } else if (C == 0) {
448 NulCharacter = CurPtr-1;
449 }
450 C = getAndAdvanceChar(CurPtr, Result);
451 }
452
Chris Lattnercb283342006-06-18 06:48:37 +0000453 if (NulCharacter) Diag(NulCharacter, diag::null_in_string);
Chris Lattner22eb9722006-06-18 05:43:12 +0000454
455 Result.SetKind(tok::string_literal);
456
Chris Lattnerd01e2912006-06-18 16:22:51 +0000457 // Update the location of the token as well as the BufferPtr instance var.
458 FormTokenWithChars(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +0000459}
460
461/// LexAngledStringLiteral - Lex the remainder of an angled string literal,
462/// after having lexed the '<' character. This is used for #include filenames.
Chris Lattnercb283342006-06-18 06:48:37 +0000463void Lexer::LexAngledStringLiteral(LexerToken &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000464 const char *NulCharacter = 0; // Does this string contain the \0 character?
465
466 char C = getAndAdvanceChar(CurPtr, Result);
467 while (C != '>') {
468 // Skip escaped characters.
469 if (C == '\\') {
470 // Skip the escaped character.
471 C = getAndAdvanceChar(CurPtr, Result);
472 } else if (C == '\n' || C == '\r' || // Newline.
473 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000474 Diag(BufferPtr, diag::err_unterminated_string);
Chris Lattner22eb9722006-06-18 05:43:12 +0000475 BufferPtr = CurPtr-1;
476 return LexTokenInternal(Result);
477 } else if (C == 0) {
478 NulCharacter = CurPtr-1;
479 }
480 C = getAndAdvanceChar(CurPtr, Result);
481 }
482
Chris Lattnercb283342006-06-18 06:48:37 +0000483 if (NulCharacter) Diag(NulCharacter, diag::null_in_string);
Chris Lattner22eb9722006-06-18 05:43:12 +0000484
485 Result.SetKind(tok::angle_string_literal);
486
Chris Lattnerd01e2912006-06-18 16:22:51 +0000487 // Update the location of token as well as BufferPtr.
488 FormTokenWithChars(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +0000489}
490
491
492/// LexCharConstant - Lex the remainder of a character constant, after having
493/// lexed either ' or L'.
Chris Lattnercb283342006-06-18 06:48:37 +0000494void Lexer::LexCharConstant(LexerToken &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000495 const char *NulCharacter = 0; // Does this character contain the \0 character?
496
497 // Handle the common case of 'x' and '\y' efficiently.
498 char C = getAndAdvanceChar(CurPtr, Result);
499 if (C == '\'') {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000500 Diag(BufferPtr, diag::err_empty_character);
Chris Lattner22eb9722006-06-18 05:43:12 +0000501 BufferPtr = CurPtr;
502 return LexTokenInternal(Result);
503 } else if (C == '\\') {
504 // Skip the escaped character.
505 // FIXME: UCN's.
506 C = getAndAdvanceChar(CurPtr, Result);
507 }
508
509 if (C && C != '\n' && C != '\r' && CurPtr[0] == '\'') {
510 ++CurPtr;
511 } else {
512 // Fall back on generic code for embedded nulls, newlines, wide chars.
513 do {
514 // Skip escaped characters.
515 if (C == '\\') {
516 // Skip the escaped character.
517 C = getAndAdvanceChar(CurPtr, Result);
518 } else if (C == '\n' || C == '\r' || // Newline.
519 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000520 Diag(BufferPtr, diag::err_unterminated_char);
Chris Lattner22eb9722006-06-18 05:43:12 +0000521 BufferPtr = CurPtr-1;
522 return LexTokenInternal(Result);
523 } else if (C == 0) {
524 NulCharacter = CurPtr-1;
525 }
526 C = getAndAdvanceChar(CurPtr, Result);
527 } while (C != '\'');
528 }
529
Chris Lattnercb283342006-06-18 06:48:37 +0000530 if (NulCharacter) Diag(NulCharacter, diag::null_in_char);
Chris Lattner22eb9722006-06-18 05:43:12 +0000531
532 Result.SetKind(tok::char_constant);
533
Chris Lattnerd01e2912006-06-18 16:22:51 +0000534 // Update the location of token as well as BufferPtr.
535 FormTokenWithChars(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +0000536}
537
538/// SkipWhitespace - Efficiently skip over a series of whitespace characters.
539/// Update BufferPtr to point to the next non-whitespace character and return.
Chris Lattnercb283342006-06-18 06:48:37 +0000540void Lexer::SkipWhitespace(LexerToken &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000541 // Whitespace - Skip it, then return the token after the whitespace.
542 unsigned char Char = *CurPtr; // Skip consequtive spaces efficiently.
543 while (1) {
544 // Skip horizontal whitespace very aggressively.
545 while (isHorizontalWhitespace(Char))
546 Char = *++CurPtr;
547
548 // Otherwise if we something other than whitespace, we're done.
549 if (Char != '\n' && Char != '\r')
550 break;
551
552 if (ParsingPreprocessorDirective) {
553 // End of preprocessor directive line, let LexTokenInternal handle this.
554 BufferPtr = CurPtr;
Chris Lattnercb283342006-06-18 06:48:37 +0000555 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000556 }
557
558 // ok, but handle newline.
559 // The returned token is at the start of the line.
560 Result.SetFlag(LexerToken::StartOfLine);
561 // No leading whitespace seen so far.
562 Result.ClearFlag(LexerToken::LeadingSpace);
563 Char = *++CurPtr;
564 }
565
566 // If this isn't immediately after a newline, there is leading space.
567 char PrevChar = CurPtr[-1];
568 if (PrevChar != '\n' && PrevChar != '\r')
569 Result.SetFlag(LexerToken::LeadingSpace);
570
571 // If the next token is obviously a // or /* */ comment, skip it efficiently
572 // too (without going through the big switch stmt).
573 if (Char == '/' && CurPtr[1] == '/') {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000574 BufferPtr = CurPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +0000575 return SkipBCPLComment(Result, CurPtr+1);
576 }
577 if (Char == '/' && CurPtr[1] == '*') {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000578 BufferPtr = CurPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +0000579 return SkipBlockComment(Result, CurPtr+2);
580 }
581 BufferPtr = CurPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +0000582}
583
584// SkipBCPLComment - We have just read the // characters from input. Skip until
585// we find the newline character thats terminate the comment. Then update
586/// BufferPtr and return.
Chris Lattnercb283342006-06-18 06:48:37 +0000587void Lexer::SkipBCPLComment(LexerToken &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000588 // If BCPL comments aren't explicitly enabled for this language, emit an
589 // extension warning.
590 if (!Features.BCPLComment) {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000591 Diag(BufferPtr, diag::ext_bcpl_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +0000592
593 // Mark them enabled so we only emit one warning for this translation
594 // unit.
595 Features.BCPLComment = true;
596 }
597
598 // Scan over the body of the comment. The common case, when scanning, is that
599 // the comment contains normal ascii characters with nothing interesting in
600 // them. As such, optimize for this case with the inner loop.
601 char C;
602 do {
603 C = *CurPtr;
Chris Lattner505c5472006-07-03 00:55:48 +0000604 // FIXME: Speedup BCPL comment lexing. Just scan for a \n or \r character.
605 // If we find a \n character, scan backwards, checking to see if it's an
606 // escaped newline, like we do for block comments.
Chris Lattner22eb9722006-06-18 05:43:12 +0000607
608 // Skip over characters in the fast loop.
609 while (C != 0 && // Potentially EOF.
610 C != '\\' && // Potentially escaped newline.
611 C != '?' && // Potentially trigraph.
612 C != '\n' && C != '\r') // Newline or DOS-style newline.
613 C = *++CurPtr;
614
615 // If this is a newline, we're done.
616 if (C == '\n' || C == '\r')
617 break; // Found the newline? Break out!
618
619 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
620 // properly decode the character.
621 const char *OldPtr = CurPtr;
622 C = getAndAdvanceChar(CurPtr, Result);
623
624 // If we read multiple characters, and one of those characters was a \r or
625 // \n, then we had an escaped newline within the comment. Emit diagnostic.
626 if (CurPtr != OldPtr+1) {
627 for (; OldPtr != CurPtr; ++OldPtr)
628 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
Chris Lattnercb283342006-06-18 06:48:37 +0000629 Diag(OldPtr-1, diag::ext_multi_line_bcpl_comment);
630 break;
Chris Lattner22eb9722006-06-18 05:43:12 +0000631 }
632 }
633
634 if (CurPtr == BufferEnd+1) goto FoundEOF;
635 } while (C != '\n' && C != '\r');
636
637 // Found and did not consume a newline.
638
639 // If we are inside a preprocessor directive and we see the end of line,
640 // return immediately, so that the lexer can return this as an EOM token.
641 if (ParsingPreprocessorDirective) {
642 BufferPtr = CurPtr;
Chris Lattnercb283342006-06-18 06:48:37 +0000643 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000644 }
645
646 // Otherwise, eat the \n character. We don't care if this is a \n\r or
647 // \r\n sequence.
648 ++CurPtr;
649
650 // The next returned token is at the start of the line.
651 Result.SetFlag(LexerToken::StartOfLine);
652 // No leading whitespace seen so far.
653 Result.ClearFlag(LexerToken::LeadingSpace);
654
655 // It is common for the tokens immediately after a // comment to be
656 // whitespace (indentation for the next line). Instead of going through the
657 // big switch, handle it efficiently now.
658 if (isWhitespace(*CurPtr)) {
659 Result.SetFlag(LexerToken::LeadingSpace);
660 return SkipWhitespace(Result, CurPtr+1);
661 }
662
663 BufferPtr = CurPtr;
Chris Lattnercb283342006-06-18 06:48:37 +0000664 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000665
666FoundEOF: // If we ran off the end of the buffer, return EOF.
667 BufferPtr = CurPtr-1;
Chris Lattnercb283342006-06-18 06:48:37 +0000668 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000669}
670
Chris Lattnercb283342006-06-18 06:48:37 +0000671/// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
672/// character (either \n or \r) is part of an escaped newline sequence. Issue a
Chris Lattner22eb9722006-06-18 05:43:12 +0000673/// diagnostic if so. We know that the is inside of a block comment.
Chris Lattner1f583052006-06-18 06:53:56 +0000674static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
675 Lexer *L) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000676 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
Chris Lattner22eb9722006-06-18 05:43:12 +0000677
678 // Back up off the newline.
679 --CurPtr;
680
681 // If this is a two-character newline sequence, skip the other character.
682 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
683 // \n\n or \r\r -> not escaped newline.
684 if (CurPtr[0] == CurPtr[1])
685 return false;
686 // \n\r or \r\n -> skip the newline.
687 --CurPtr;
688 }
689
690 // If we have horizontal whitespace, skip over it. We allow whitespace
691 // between the slash and newline.
692 bool HasSpace = false;
693 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
694 --CurPtr;
695 HasSpace = true;
696 }
697
698 // If we have a slash, we know this is an escaped newline.
699 if (*CurPtr == '\\') {
Chris Lattnercb283342006-06-18 06:48:37 +0000700 if (CurPtr[-1] != '*') return false;
Chris Lattner22eb9722006-06-18 05:43:12 +0000701 } else {
702 // It isn't a slash, is it the ?? / trigraph?
Chris Lattnercb283342006-06-18 06:48:37 +0000703 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
704 CurPtr[-3] != '*')
Chris Lattner22eb9722006-06-18 05:43:12 +0000705 return false;
Chris Lattnercb283342006-06-18 06:48:37 +0000706
707 // This is the trigraph ending the comment. Emit a stern warning!
Chris Lattner22eb9722006-06-18 05:43:12 +0000708 CurPtr -= 2;
709
710 // If no trigraphs are enabled, warn that we ignored this trigraph and
711 // ignore this * character.
Chris Lattner1f583052006-06-18 06:53:56 +0000712 if (!L->getFeatures().Trigraphs) {
713 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
Chris Lattnercb283342006-06-18 06:48:37 +0000714 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +0000715 }
Chris Lattner1f583052006-06-18 06:53:56 +0000716 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +0000717 }
718
719 // Warn about having an escaped newline between the */ characters.
Chris Lattner1f583052006-06-18 06:53:56 +0000720 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
Chris Lattner22eb9722006-06-18 05:43:12 +0000721
722 // If there was space between the backslash and newline, warn about it.
Chris Lattner1f583052006-06-18 06:53:56 +0000723 if (HasSpace) L->Diag(CurPtr, diag::backslash_newline_space);
Chris Lattner22eb9722006-06-18 05:43:12 +0000724
Chris Lattnercb283342006-06-18 06:48:37 +0000725 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +0000726}
727
728/// SkipBlockComment - We have just read the /* characters from input. Read
729/// until we find the */ characters that terminate the comment. Note that we
730/// don't bother decoding trigraphs or escaped newlines in block comments,
731/// because they cannot cause the comment to end. The only thing that can
732/// happen is the comment could end with an escaped newline between the */ end
733/// of comment.
Chris Lattnercb283342006-06-18 06:48:37 +0000734void Lexer::SkipBlockComment(LexerToken &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000735 // Scan one character past where we should, looking for a '/' character. Once
736 // we find it, check to see if it was preceeded by a *. This common
737 // optimization helps people who like to put a lot of * characters in their
738 // comments.
739 unsigned char C = *CurPtr++;
740 if (C == 0 && CurPtr == BufferEnd+1) {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000741 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +0000742 BufferPtr = CurPtr-1;
Chris Lattnercb283342006-06-18 06:48:37 +0000743 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000744 }
745
746 while (1) {
747 // Skip over all non-interesting characters.
748 // TODO: Vectorize this. Note: memchr on Darwin is slower than this loop.
749 while (C != '/' && C != '\0')
750 C = *CurPtr++;
751
752 if (C == '/') {
Chris Lattner22eb9722006-06-18 05:43:12 +0000753 if (CurPtr[-2] == '*') // We found the final */. We're done!
754 break;
755
756 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
Chris Lattner1f583052006-06-18 06:53:56 +0000757 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000758 // We found the final */, though it had an escaped newline between the
759 // * and /. We're done!
760 break;
761 }
762 }
763 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
764 // If this is a /* inside of the comment, emit a warning. Don't do this
765 // if this is a /*/, which will end the comment. This misses cases with
766 // embedded escaped newlines, but oh well.
Chris Lattnercb283342006-06-18 06:48:37 +0000767 Diag(CurPtr-1, diag::nested_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +0000768 }
769 } else if (C == 0 && CurPtr == BufferEnd+1) {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000770 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +0000771 // Note: the user probably forgot a */. We could continue immediately
772 // after the /*, but this would involve lexing a lot of what really is the
773 // comment, which surely would confuse the parser.
774 BufferPtr = CurPtr-1;
Chris Lattnercb283342006-06-18 06:48:37 +0000775 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000776 }
777 C = *CurPtr++;
778 }
779
780 // It is common for the tokens immediately after a /**/ comment to be
781 // whitespace. Instead of going through the big switch, handle it
782 // efficiently now.
783 if (isHorizontalWhitespace(*CurPtr)) {
784 Result.SetFlag(LexerToken::LeadingSpace);
785 return SkipWhitespace(Result, CurPtr+1);
786 }
787
788 // Otherwise, just return so that the next character will be lexed as a token.
789 BufferPtr = CurPtr;
790 Result.SetFlag(LexerToken::LeadingSpace);
Chris Lattner22eb9722006-06-18 05:43:12 +0000791}
792
793//===----------------------------------------------------------------------===//
794// Primary Lexing Entry Points
795//===----------------------------------------------------------------------===//
796
797/// LexIncludeFilename - After the preprocessor has parsed a #include, lex and
798/// (potentially) macro expand the filename.
Chris Lattner269c2322006-06-25 06:23:00 +0000799std::string Lexer::LexIncludeFilename(LexerToken &FilenameTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000800 assert(ParsingPreprocessorDirective &&
801 ParsingFilename == false &&
802 "Must be in a preprocessing directive!");
803
804 // We are now parsing a filename!
805 ParsingFilename = true;
806
Chris Lattner269c2322006-06-25 06:23:00 +0000807 // Lex the filename.
808 Lex(FilenameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +0000809
810 // We should have gotten the filename now.
811 ParsingFilename = false;
812
813 // No filename?
Chris Lattner269c2322006-06-25 06:23:00 +0000814 if (FilenameTok.getKind() == tok::eom) {
815 PP.Diag(FilenameTok, diag::err_pp_expects_filename);
816 return "";
Chris Lattnercb283342006-06-18 06:48:37 +0000817 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000818
Chris Lattner269c2322006-06-25 06:23:00 +0000819 // Get the text form of the filename.
820 std::string Filename = PP.getSpelling(FilenameTok);
821 assert(!Filename.empty() && "Can't have tokens with empty spellings!");
822
823 // Make sure the filename is <x> or "x".
824 if (Filename[0] == '<') {
825 if (Filename[Filename.size()-1] != '>') {
826 PP.Diag(FilenameTok, diag::err_pp_expects_filename);
827 FilenameTok.SetKind(tok::eom);
828 return "";
829 }
830 } else if (Filename[0] == '"') {
831 if (Filename[Filename.size()-1] != '"') {
832 PP.Diag(FilenameTok, diag::err_pp_expects_filename);
833 FilenameTok.SetKind(tok::eom);
834 return "";
835 }
836 } else {
837 PP.Diag(FilenameTok, diag::err_pp_expects_filename);
838 FilenameTok.SetKind(tok::eom);
839 return "";
Chris Lattner22eb9722006-06-18 05:43:12 +0000840 }
Chris Lattner269c2322006-06-25 06:23:00 +0000841
842 // Diagnose #include "" as invalid.
843 if (Filename.size() == 2) {
844 PP.Diag(FilenameTok, diag::err_pp_empty_filename);
845 FilenameTok.SetKind(tok::eom);
846 return "";
847 }
848
849 return Filename;
Chris Lattner22eb9722006-06-18 05:43:12 +0000850}
851
852/// ReadToEndOfLine - Read the rest of the current preprocessor line as an
853/// uninterpreted string. This switches the lexer out of directive mode.
854std::string Lexer::ReadToEndOfLine() {
855 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
856 "Must be in a preprocessing directive!");
857 std::string Result;
858 LexerToken Tmp;
859
860 // CurPtr - Cache BufferPtr in an automatic variable.
861 const char *CurPtr = BufferPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +0000862 while (1) {
863 char Char = getAndAdvanceChar(CurPtr, Tmp);
864 switch (Char) {
865 default:
866 Result += Char;
867 break;
868 case 0: // Null.
869 // Found end of file?
870 if (CurPtr-1 != BufferEnd) {
871 // Nope, normal character, continue.
872 Result += Char;
873 break;
874 }
875 // FALL THROUGH.
876 case '\r':
877 case '\n':
878 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
879 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
880 BufferPtr = CurPtr-1;
881
882 // Next, lex the character, which should handle the EOM transition.
Chris Lattnercb283342006-06-18 06:48:37 +0000883 Lex(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +0000884 assert(Tmp.getKind() == tok::eom && "Unexpected token!");
Chris Lattner22eb9722006-06-18 05:43:12 +0000885
886 // Finally, we're done, return the string we found.
887 return Result;
888 }
889 }
890}
891
892/// LexEndOfFile - CurPtr points to the end of this file. Handle this
893/// condition, reporting diagnostics and handling other edge cases as required.
Chris Lattnercb283342006-06-18 06:48:37 +0000894void Lexer::LexEndOfFile(LexerToken &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000895 // If we hit the end of the file while parsing a preprocessor directive,
896 // end the preprocessor directive first. The next token returned will
897 // then be the end of file.
898 if (ParsingPreprocessorDirective) {
899 // Done parsing the "line".
900 ParsingPreprocessorDirective = false;
901 Result.SetKind(tok::eom);
Chris Lattnerd01e2912006-06-18 16:22:51 +0000902 // Update the location of token as well as BufferPtr.
903 FormTokenWithChars(Result, CurPtr);
Chris Lattnercb283342006-06-18 06:48:37 +0000904 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000905 }
906
907 // If we are in a #if directive, emit an error.
908 while (!ConditionalStack.empty()) {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000909 PP.Diag(ConditionalStack.back().IfLoc,
910 diag::err_pp_unterminated_conditional);
Chris Lattner22eb9722006-06-18 05:43:12 +0000911 ConditionalStack.pop_back();
912 }
913
914 // If the file was empty or didn't end in a newline, issue a pedwarn.
Chris Lattnercb283342006-06-18 06:48:37 +0000915 if (CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
916 Diag(BufferEnd, diag::ext_no_newline_eof);
Chris Lattner22eb9722006-06-18 05:43:12 +0000917
918 BufferPtr = CurPtr;
Chris Lattnercb283342006-06-18 06:48:37 +0000919 PP.HandleEndOfFile(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +0000920}
921
922
923/// LexTokenInternal - This implements a simple C family lexer. It is an
924/// extremely performance critical piece of code. This assumes that the buffer
925/// has a null character at the end of the file. Return true if an error
926/// occurred and compilation should terminate, false if normal. This returns a
927/// preprocessing token, not a normal token, as such, it is an internal
928/// interface. It assumes that the Flags of result have been cleared before
929/// calling this.
Chris Lattnercb283342006-06-18 06:48:37 +0000930void Lexer::LexTokenInternal(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000931LexNextToken:
932 // New token, can't need cleaning yet.
933 Result.ClearFlag(LexerToken::NeedsCleaning);
934
935 // CurPtr - Cache BufferPtr in an automatic variable.
936 const char *CurPtr = BufferPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +0000937
938 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
939
940 // Read a character, advancing over it.
941 char Char = getAndAdvanceChar(CurPtr, Result);
942 switch (Char) {
943 case 0: // Null.
944 // Found end of file?
945 if (CurPtr-1 == BufferEnd)
946 return LexEndOfFile(Result, CurPtr-1); // Retreat back into the file.
947
Chris Lattnercb283342006-06-18 06:48:37 +0000948 Diag(CurPtr-1, diag::null_in_file);
Chris Lattner22eb9722006-06-18 05:43:12 +0000949 Result.SetFlag(LexerToken::LeadingSpace);
Chris Lattnercb283342006-06-18 06:48:37 +0000950 SkipWhitespace(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +0000951 goto LexNextToken; // GCC isn't tail call eliminating.
952 case '\n':
953 case '\r':
954 // If we are inside a preprocessor directive and we see the end of line,
955 // we know we are done with the directive, so return an EOM token.
956 if (ParsingPreprocessorDirective) {
957 // Done parsing the "line".
958 ParsingPreprocessorDirective = false;
959
960 // Since we consumed a newline, we are back at the start of a line.
961 IsAtStartOfLine = true;
962
963 Result.SetKind(tok::eom);
964 break;
965 }
966 // The returned token is at the start of the line.
967 Result.SetFlag(LexerToken::StartOfLine);
968 // No leading whitespace seen so far.
969 Result.ClearFlag(LexerToken::LeadingSpace);
Chris Lattnercb283342006-06-18 06:48:37 +0000970 SkipWhitespace(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +0000971 goto LexNextToken; // GCC isn't tail call eliminating.
972 case ' ':
973 case '\t':
974 case '\f':
975 case '\v':
976 Result.SetFlag(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
980 case 'L':
981 Char = getCharAndSize(CurPtr, SizeTmp);
982
983 // Wide string literal.
984 if (Char == '"')
985 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result));
986
987 // Wide character constant.
988 if (Char == '\'')
989 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
990 // FALL THROUGH, treating L like the start of an identifier.
991
992 // C99 6.4.2: Identifiers.
993 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
994 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
995 case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U':
996 case 'V': case 'W': case 'X': case 'Y': case 'Z':
997 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
998 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
999 case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u':
1000 case 'v': case 'w': case 'x': case 'y': case 'z':
1001 case '_':
1002 return LexIdentifier(Result, CurPtr);
1003
1004 // C99 6.4.4.1: Integer Constants.
1005 // C99 6.4.4.2: Floating Constants.
1006 case '0': case '1': case '2': case '3': case '4':
1007 case '5': case '6': case '7': case '8': case '9':
1008 return LexNumericConstant(Result, CurPtr);
1009
1010 // C99 6.4.4: Character Constants.
1011 case '\'':
1012 return LexCharConstant(Result, CurPtr);
1013
1014 // C99 6.4.5: String Literals.
1015 case '"':
1016 return LexStringLiteral(Result, CurPtr);
1017
1018 // C99 6.4.6: Punctuators.
1019 case '?':
1020 Result.SetKind(tok::question);
1021 break;
1022 case '[':
1023 Result.SetKind(tok::l_square);
1024 break;
1025 case ']':
1026 Result.SetKind(tok::r_square);
1027 break;
1028 case '(':
1029 Result.SetKind(tok::l_paren);
1030 break;
1031 case ')':
1032 Result.SetKind(tok::r_paren);
1033 break;
1034 case '{':
1035 Result.SetKind(tok::l_brace);
1036 break;
1037 case '}':
1038 Result.SetKind(tok::r_brace);
1039 break;
1040 case '.':
1041 Char = getCharAndSize(CurPtr, SizeTmp);
1042 if (Char >= '0' && Char <= '9') {
1043 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
1044 } else if (Features.CPlusPlus && Char == '*') {
1045 Result.SetKind(tok::periodstar);
1046 CurPtr += SizeTmp;
1047 } else if (Char == '.' &&
1048 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
1049 Result.SetKind(tok::ellipsis);
1050 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1051 SizeTmp2, Result);
1052 } else {
1053 Result.SetKind(tok::period);
1054 }
1055 break;
1056 case '&':
1057 Char = getCharAndSize(CurPtr, SizeTmp);
1058 if (Char == '&') {
1059 Result.SetKind(tok::ampamp);
1060 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1061 } else if (Char == '=') {
1062 Result.SetKind(tok::ampequal);
1063 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1064 } else {
1065 Result.SetKind(tok::amp);
1066 }
1067 break;
1068 case '*':
1069 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
1070 Result.SetKind(tok::starequal);
1071 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1072 } else {
1073 Result.SetKind(tok::star);
1074 }
1075 break;
1076 case '+':
1077 Char = getCharAndSize(CurPtr, SizeTmp);
1078 if (Char == '+') {
1079 Result.SetKind(tok::plusplus);
1080 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1081 } else if (Char == '=') {
1082 Result.SetKind(tok::plusequal);
1083 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1084 } else {
1085 Result.SetKind(tok::plus);
1086 }
1087 break;
1088 case '-':
1089 Char = getCharAndSize(CurPtr, SizeTmp);
1090 if (Char == '-') {
1091 Result.SetKind(tok::minusminus);
1092 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1093 } else if (Char == '>' && Features.CPlusPlus &&
1094 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') {
1095 Result.SetKind(tok::arrowstar); // C++ ->*
1096 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1097 SizeTmp2, Result);
1098 } else if (Char == '>') {
1099 Result.SetKind(tok::arrow);
1100 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1101 } else if (Char == '=') {
1102 Result.SetKind(tok::minusequal);
1103 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1104 } else {
1105 Result.SetKind(tok::minus);
1106 }
1107 break;
1108 case '~':
1109 Result.SetKind(tok::tilde);
1110 break;
1111 case '!':
1112 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
1113 Result.SetKind(tok::exclaimequal);
1114 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1115 } else {
1116 Result.SetKind(tok::exclaim);
1117 }
1118 break;
1119 case '/':
1120 // 6.4.9: Comments
1121 Char = getCharAndSize(CurPtr, SizeTmp);
1122 if (Char == '/') { // BCPL comment.
1123 Result.SetFlag(LexerToken::LeadingSpace);
Chris Lattnercb283342006-06-18 06:48:37 +00001124 SkipBCPLComment(Result, ConsumeChar(CurPtr, SizeTmp, Result));
Chris Lattner22eb9722006-06-18 05:43:12 +00001125 goto LexNextToken; // GCC isn't tail call eliminating.
1126 } else if (Char == '*') { // /**/ comment.
1127 Result.SetFlag(LexerToken::LeadingSpace);
Chris Lattnercb283342006-06-18 06:48:37 +00001128 SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result));
Chris Lattner22eb9722006-06-18 05:43:12 +00001129 goto LexNextToken; // GCC isn't tail call eliminating.
1130 } else if (Char == '=') {
1131 Result.SetKind(tok::slashequal);
1132 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1133 } else {
1134 Result.SetKind(tok::slash);
1135 }
1136 break;
1137 case '%':
1138 Char = getCharAndSize(CurPtr, SizeTmp);
1139 if (Char == '=') {
1140 Result.SetKind(tok::percentequal);
1141 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1142 } else if (Features.Digraphs && Char == '>') {
1143 Result.SetKind(tok::r_brace); // '%>' -> '}'
1144 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1145 } else if (Features.Digraphs && Char == ':') {
1146 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1147 if (getCharAndSize(CurPtr, SizeTmp) == '%' &&
1148 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
1149 Result.SetKind(tok::hashhash); // '%:%:' -> '##'
1150 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1151 SizeTmp2, Result);
1152 } else {
1153 Result.SetKind(tok::hash); // '%:' -> '#'
1154
1155 // We parsed a # character. If this occurs at the start of the line,
1156 // it's actually the start of a preprocessing directive. Callback to
1157 // the preprocessor to handle it.
1158 // FIXME: -fpreprocessed mode??
1159 if (Result.isAtStartOfLine() && !PP.isSkipping()) {
1160 BufferPtr = CurPtr;
Chris Lattnercb283342006-06-18 06:48:37 +00001161 PP.HandleDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001162
1163 // As an optimization, if the preprocessor didn't switch lexers, tail
1164 // recurse.
1165 if (PP.isCurrentLexer(this)) {
1166 // Start a new token. If this is a #include or something, the PP may
1167 // want us starting at the beginning of the line again. If so, set
1168 // the StartOfLine flag.
1169 if (IsAtStartOfLine) {
1170 Result.SetFlag(LexerToken::StartOfLine);
1171 IsAtStartOfLine = false;
1172 }
1173 goto LexNextToken; // GCC isn't tail call eliminating.
1174 }
1175
1176 return PP.Lex(Result);
1177 }
1178 }
1179 } else {
1180 Result.SetKind(tok::percent);
1181 }
1182 break;
1183 case '<':
1184 Char = getCharAndSize(CurPtr, SizeTmp);
1185 if (ParsingFilename) {
1186 return LexAngledStringLiteral(Result, CurPtr+SizeTmp);
1187 } else if (Char == '<' &&
1188 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '=') {
1189 Result.SetKind(tok::lesslessequal);
1190 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1191 SizeTmp2, Result);
1192 } else if (Char == '<') {
1193 Result.SetKind(tok::lessless);
1194 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1195 } else if (Char == '=') {
1196 Result.SetKind(tok::lessequal);
1197 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1198 } else if (Features.Digraphs && Char == ':') {
1199 Result.SetKind(tok::l_square); // '<:' -> '['
1200 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1201 } else if (Features.Digraphs && Char == '>') {
1202 Result.SetKind(tok::l_brace); // '<%' -> '{'
1203 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1204 } else if (Features.CPPMinMax && Char == '?') { // <?
1205 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerd01e2912006-06-18 16:22:51 +00001206 Diag(BufferPtr, diag::min_max_deprecated);
Chris Lattner22eb9722006-06-18 05:43:12 +00001207
1208 if (getCharAndSize(CurPtr, SizeTmp) == '=') { // <?=
1209 Result.SetKind(tok::lessquestionequal);
1210 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1211 } else {
1212 Result.SetKind(tok::lessquestion);
1213 }
1214 } else {
1215 Result.SetKind(tok::less);
1216 }
1217 break;
1218 case '>':
1219 Char = getCharAndSize(CurPtr, SizeTmp);
1220 if (Char == '=') {
1221 Result.SetKind(tok::greaterequal);
1222 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1223 } else if (Char == '>' &&
1224 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '=') {
1225 Result.SetKind(tok::greatergreaterequal);
1226 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1227 SizeTmp2, Result);
1228 } else if (Char == '>') {
1229 Result.SetKind(tok::greatergreater);
1230 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1231 } else if (Features.CPPMinMax && Char == '?') {
1232 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerd01e2912006-06-18 16:22:51 +00001233 Diag(BufferPtr, diag::min_max_deprecated);
Chris Lattner22eb9722006-06-18 05:43:12 +00001234
1235 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
1236 Result.SetKind(tok::greaterquestionequal); // >?=
1237 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1238 } else {
1239 Result.SetKind(tok::greaterquestion); // >?
1240 }
1241 } else {
1242 Result.SetKind(tok::greater);
1243 }
1244 break;
1245 case '^':
1246 Char = getCharAndSize(CurPtr, SizeTmp);
1247 if (Char == '=') {
1248 Result.SetKind(tok::caretequal);
1249 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1250 } else {
1251 Result.SetKind(tok::caret);
1252 }
1253 break;
1254 case '|':
1255 Char = getCharAndSize(CurPtr, SizeTmp);
1256 if (Char == '=') {
1257 Result.SetKind(tok::pipeequal);
1258 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1259 } else if (Char == '|') {
1260 Result.SetKind(tok::pipepipe);
1261 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1262 } else {
1263 Result.SetKind(tok::pipe);
1264 }
1265 break;
1266 case ':':
1267 Char = getCharAndSize(CurPtr, SizeTmp);
1268 if (Features.Digraphs && Char == '>') {
1269 Result.SetKind(tok::r_square); // ':>' -> ']'
1270 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1271 } else if (Features.CPlusPlus && Char == ':') {
1272 Result.SetKind(tok::coloncolon);
1273 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1274 } else {
1275 Result.SetKind(tok::colon);
1276 }
1277 break;
1278 case ';':
1279 Result.SetKind(tok::semi);
1280 break;
1281 case '=':
1282 Char = getCharAndSize(CurPtr, SizeTmp);
1283 if (Char == '=') {
1284 Result.SetKind(tok::equalequal);
1285 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1286 } else {
1287 Result.SetKind(tok::equal);
1288 }
1289 break;
1290 case ',':
1291 Result.SetKind(tok::comma);
1292 break;
1293 case '#':
1294 Char = getCharAndSize(CurPtr, SizeTmp);
1295 if (Char == '#') {
1296 Result.SetKind(tok::hashhash);
1297 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1298 } else {
1299 Result.SetKind(tok::hash);
1300 // We parsed a # character. If this occurs at the start of the line,
1301 // it's actually the start of a preprocessing directive. Callback to
1302 // the preprocessor to handle it.
Chris Lattner505c5472006-07-03 00:55:48 +00001303 // FIXME: -fpreprocessed mode??
Chris Lattner22eb9722006-06-18 05:43:12 +00001304 if (Result.isAtStartOfLine() && !PP.isSkipping()) {
1305 BufferPtr = CurPtr;
Chris Lattnercb283342006-06-18 06:48:37 +00001306 PP.HandleDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001307
1308 // As an optimization, if the preprocessor didn't switch lexers, tail
1309 // recurse.
1310 if (PP.isCurrentLexer(this)) {
1311 // Start a new token. If this is a #include or something, the PP may
1312 // want us starting at the beginning of the line again. If so, set
1313 // the StartOfLine flag.
1314 if (IsAtStartOfLine) {
1315 Result.SetFlag(LexerToken::StartOfLine);
1316 IsAtStartOfLine = false;
1317 }
1318 goto LexNextToken; // GCC isn't tail call eliminating.
1319 }
1320 return PP.Lex(Result);
1321 }
1322 }
1323 break;
1324
1325 case '\\':
Chris Lattner505c5472006-07-03 00:55:48 +00001326 // FIXME: UCN's.
Chris Lattner22eb9722006-06-18 05:43:12 +00001327 // FALL THROUGH.
1328 default:
1329 // Objective C support.
1330 if (CurPtr[-1] == '@' && Features.ObjC1) {
1331 Result.SetKind(tok::at);
1332 break;
1333 } else if (CurPtr[-1] == '$' && Features.DollarIdents) {// $ in identifiers.
Chris Lattnercb283342006-06-18 06:48:37 +00001334 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +00001335 return LexIdentifier(Result, CurPtr);
1336 }
1337
Chris Lattnercb283342006-06-18 06:48:37 +00001338 if (!PP.isSkipping()) Diag(CurPtr-1, diag::err_stray_character);
Chris Lattner22eb9722006-06-18 05:43:12 +00001339 BufferPtr = CurPtr;
1340 goto LexNextToken; // GCC isn't tail call eliminating.
1341 }
1342
Chris Lattnerd01e2912006-06-18 16:22:51 +00001343 // Update the location of token as well as BufferPtr.
1344 FormTokenWithChars(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +00001345}