blob: 69c3a878dd15ac0400dbbff8687fc3e390910f58 [file] [log] [blame]
Chris Lattner22eb9722006-06-18 05:43:12 +00001//===--- Lexer.cpp - C Language Family Lexer ------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Lexer and LexerToken interfaces.
11//
12//===----------------------------------------------------------------------===//
13//
14// TODO: GCC Diagnostics emitted by the lexer:
15// PEDWARN: (form feed|vertical tab) in preprocessing directive
16//
17// Universal characters, unicode, char mapping:
18// WARNING: `%.*s' is not in NFKC
19// WARNING: `%.*s' is not in NFC
20//
21// Other:
Chris Lattner22eb9722006-06-18 05:43:12 +000022// TODO: Options to support:
23// -fexec-charset,-fwide-exec-charset
24//
25//===----------------------------------------------------------------------===//
26
27#include "clang/Lex/Lexer.h"
28#include "clang/Lex/Preprocessor.h"
29#include "clang/Basic/Diagnostic.h"
30#include "clang/Basic/SourceBuffer.h"
31#include "clang/Basic/SourceLocation.h"
32#include "llvm/Config/alloca.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000033#include <cctype>
34#include <iostream>
35using namespace llvm;
36using namespace clang;
37
38static void InitCharacterInfo();
39
Chris Lattner4cca5ba2006-07-02 20:05:54 +000040Lexer::Lexer(const SourceBuffer *File, unsigned fileid, Preprocessor &pp,
41 const char *BufStart, const char *BufEnd)
Chris Lattner678c8802006-07-11 05:46:12 +000042 : BufferEnd(BufEnd ? BufEnd : File->getBufferEnd()),
Chris Lattner4cca5ba2006-07-02 20:05:54 +000043 InputFile(File), CurFileID(fileid), PP(pp), Features(PP.getLangOptions()) {
Chris Lattnerecfeafe2006-07-02 21:26:45 +000044 Is_PragmaLexer = false;
Chris Lattner4ec473f2006-07-03 05:16:05 +000045 IsMainFile = false;
Chris Lattner22eb9722006-06-18 05:43:12 +000046 InitCharacterInfo();
47
48 assert(BufferEnd[0] == 0 &&
49 "We assume that the input buffer has a null character at the end"
50 " to simplify lexing!");
Chris Lattner678c8802006-07-11 05:46:12 +000051
52 BufferPtr = BufStart ? BufStart : File->getBufferStart();
53
Chris Lattner22eb9722006-06-18 05:43:12 +000054 // Start of the file is a start of line.
55 IsAtStartOfLine = true;
56
57 // We are not after parsing a #.
58 ParsingPreprocessorDirective = false;
59
60 // We are not after parsing #include.
61 ParsingFilename = false;
Chris Lattner3ebcf4e2006-07-11 05:39:23 +000062
63 // We are not in raw mode. Raw mode disables diagnostics and interpretation
64 // of tokens (e.g. identifiers, thus disabling macro expansion). It is used
65 // to quickly lex the tokens of the buffer, e.g. when handling a "#if 0" block
66 // or otherwise skipping over tokens.
67 LexingRawMode = false;
Chris Lattner22eb9722006-06-18 05:43:12 +000068}
69
Chris Lattnere3e81ea2006-07-03 01:13:26 +000070/// Stringify - Convert the specified string into a C string, with surrounding
71/// ""'s, and with escaped \ and " characters.
Chris Lattnerecc39e92006-07-15 05:23:31 +000072std::string Lexer::Stringify(const std::string &Str, bool Charify) {
Chris Lattnere3e81ea2006-07-03 01:13:26 +000073 std::string Result = Str;
Chris Lattnerecc39e92006-07-15 05:23:31 +000074 char Quote = Charify ? '\'' : '"';
Chris Lattnere3e81ea2006-07-03 01:13:26 +000075 for (unsigned i = 0, e = Result.size(); i != e; ++i) {
Chris Lattnerecc39e92006-07-15 05:23:31 +000076 if (Result[i] == '\\' || Result[i] == Quote) {
Chris Lattnere3e81ea2006-07-03 01:13:26 +000077 Result.insert(Result.begin()+i, '\\');
78 ++i; ++e;
79 }
80 }
Chris Lattnerecc39e92006-07-15 05:23:31 +000081 return Result;
Chris Lattnere3e81ea2006-07-03 01:13:26 +000082}
83
Chris Lattner22eb9722006-06-18 05:43:12 +000084
Chris Lattner22eb9722006-06-18 05:43:12 +000085//===----------------------------------------------------------------------===//
86// Character information.
87//===----------------------------------------------------------------------===//
88
89static unsigned char CharInfo[256];
90
91enum {
92 CHAR_HORZ_WS = 0x01, // ' ', '\t', '\f', '\v'. Note, no '\0'
93 CHAR_VERT_WS = 0x02, // '\r', '\n'
94 CHAR_LETTER = 0x04, // a-z,A-Z
95 CHAR_NUMBER = 0x08, // 0-9
96 CHAR_UNDER = 0x10, // _
97 CHAR_PERIOD = 0x20 // .
98};
99
100static void InitCharacterInfo() {
101 static bool isInited = false;
102 if (isInited) return;
103 isInited = true;
104
105 // Intiialize the CharInfo table.
106 // TODO: statically initialize this.
107 CharInfo[(int)' '] = CharInfo[(int)'\t'] =
108 CharInfo[(int)'\f'] = CharInfo[(int)'\v'] = CHAR_HORZ_WS;
109 CharInfo[(int)'\n'] = CharInfo[(int)'\r'] = CHAR_VERT_WS;
110
111 CharInfo[(int)'_'] = CHAR_UNDER;
112 for (unsigned i = 'a'; i <= 'z'; ++i)
113 CharInfo[i] = CharInfo[i+'A'-'a'] = CHAR_LETTER;
114 for (unsigned i = '0'; i <= '9'; ++i)
115 CharInfo[i] = CHAR_NUMBER;
116}
117
118/// isIdentifierBody - Return true if this is the body character of an
119/// identifier, which is [a-zA-Z0-9_].
120static inline bool isIdentifierBody(unsigned char c) {
121 return CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER);
122}
123
124/// isHorizontalWhitespace - Return true if this character is horizontal
125/// whitespace: ' ', '\t', '\f', '\v'. Note that this returns false for '\0'.
126static inline bool isHorizontalWhitespace(unsigned char c) {
127 return CharInfo[c] & CHAR_HORZ_WS;
128}
129
130/// isWhitespace - Return true if this character is horizontal or vertical
131/// whitespace: ' ', '\t', '\f', '\v', '\n', '\r'. Note that this returns false
132/// for '\0'.
133static inline bool isWhitespace(unsigned char c) {
134 return CharInfo[c] & (CHAR_HORZ_WS|CHAR_VERT_WS);
135}
136
137/// isNumberBody - Return true if this is the body character of an
138/// preprocessing number, which is [a-zA-Z0-9_.].
139static inline bool isNumberBody(unsigned char c) {
140 return CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER|CHAR_PERIOD);
141}
142
Chris Lattnerd01e2912006-06-18 16:22:51 +0000143
Chris Lattner22eb9722006-06-18 05:43:12 +0000144//===----------------------------------------------------------------------===//
145// Diagnostics forwarding code.
146//===----------------------------------------------------------------------===//
147
148/// getSourceLocation - Return a source location identifier for the specified
149/// offset in the current file.
150SourceLocation Lexer::getSourceLocation(const char *Loc) const {
Chris Lattner8bbfe462006-07-02 22:27:49 +0000151 assert(Loc >= InputFile->getBufferStart() && Loc <= BufferEnd &&
Chris Lattner4cca5ba2006-07-02 20:05:54 +0000152 "Location out of range for this buffer!");
Chris Lattner8bbfe462006-07-02 22:27:49 +0000153 return SourceLocation(CurFileID, Loc-InputFile->getBufferStart());
Chris Lattner22eb9722006-06-18 05:43:12 +0000154}
155
156
157/// Diag - Forwarding function for diagnostics. This translate a source
158/// position in the current buffer into a SourceLocation object for rendering.
Chris Lattnercb283342006-06-18 06:48:37 +0000159void Lexer::Diag(const char *Loc, unsigned DiagID,
Chris Lattner22eb9722006-06-18 05:43:12 +0000160 const std::string &Msg) const {
Chris Lattnercb283342006-06-18 06:48:37 +0000161 PP.Diag(getSourceLocation(Loc), DiagID, Msg);
Chris Lattner22eb9722006-06-18 05:43:12 +0000162}
163
164//===----------------------------------------------------------------------===//
165// Trigraph and Escaped Newline Handling Code.
166//===----------------------------------------------------------------------===//
167
168/// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
169/// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
170static char GetTrigraphCharForLetter(char Letter) {
171 switch (Letter) {
172 default: return 0;
173 case '=': return '#';
174 case ')': return ']';
175 case '(': return '[';
176 case '!': return '|';
177 case '\'': return '^';
178 case '>': return '}';
179 case '/': return '\\';
180 case '<': return '{';
181 case '-': return '~';
182 }
183}
184
185/// DecodeTrigraphChar - If the specified character is a legal trigraph when
186/// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
187/// return the result character. Finally, emit a warning about trigraph use
188/// whether trigraphs are enabled or not.
189static char DecodeTrigraphChar(const char *CP, Lexer *L) {
190 char Res = GetTrigraphCharForLetter(*CP);
191 if (Res && L) {
192 if (!L->getFeatures().Trigraphs) {
193 L->Diag(CP-2, diag::trigraph_ignored);
194 return 0;
195 } else {
196 L->Diag(CP-2, diag::trigraph_converted, std::string()+Res);
197 }
198 }
199 return Res;
200}
201
202/// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
203/// get its size, and return it. This is tricky in several cases:
204/// 1. If currently at the start of a trigraph, we warn about the trigraph,
205/// then either return the trigraph (skipping 3 chars) or the '?',
206/// depending on whether trigraphs are enabled or not.
207/// 2. If this is an escaped newline (potentially with whitespace between
208/// the backslash and newline), implicitly skip the newline and return
209/// the char after it.
Chris Lattner505c5472006-07-03 00:55:48 +0000210/// 3. If this is a UCN, return it. FIXME: C++ UCN's?
Chris Lattner22eb9722006-06-18 05:43:12 +0000211///
212/// This handles the slow/uncommon case of the getCharAndSize method. Here we
213/// know that we can accumulate into Size, and that we have already incremented
214/// Ptr by Size bytes.
215///
Chris Lattnerd01e2912006-06-18 16:22:51 +0000216/// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
217/// be updated to match.
Chris Lattner22eb9722006-06-18 05:43:12 +0000218///
219char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
220 LexerToken *Tok) {
221 // If we have a slash, look for an escaped newline.
222 if (Ptr[0] == '\\') {
223 ++Size;
224 ++Ptr;
225Slash:
226 // Common case, backslash-char where the char is not whitespace.
227 if (!isWhitespace(Ptr[0])) return '\\';
228
229 // See if we have optional whitespace characters followed by a newline.
230 {
231 unsigned SizeTmp = 0;
232 do {
233 ++SizeTmp;
234 if (Ptr[SizeTmp-1] == '\n' || Ptr[SizeTmp-1] == '\r') {
235 // Remember that this token needs to be cleaned.
236 if (Tok) Tok->SetFlag(LexerToken::NeedsCleaning);
237
238 // Warn if there was whitespace between the backslash and newline.
239 if (SizeTmp != 1 && Tok)
240 Diag(Ptr, diag::backslash_newline_space);
241
242 // If this is a \r\n or \n\r, skip the newlines.
243 if ((Ptr[SizeTmp] == '\r' || Ptr[SizeTmp] == '\n') &&
244 Ptr[SizeTmp-1] != Ptr[SizeTmp])
245 ++SizeTmp;
246
247 // Found backslash<whitespace><newline>. Parse the char after it.
248 Size += SizeTmp;
249 Ptr += SizeTmp;
250 // Use slow version to accumulate a correct size field.
251 return getCharAndSizeSlow(Ptr, Size, Tok);
252 }
253 } while (isWhitespace(Ptr[SizeTmp]));
254 }
255
256 // Otherwise, this is not an escaped newline, just return the slash.
257 return '\\';
258 }
259
260 // If this is a trigraph, process it.
261 if (Ptr[0] == '?' && Ptr[1] == '?') {
262 // If this is actually a legal trigraph (not something like "??x"), emit
263 // a trigraph warning. If so, and if trigraphs are enabled, return it.
264 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : 0)) {
265 // Remember that this token needs to be cleaned.
266 if (Tok) Tok->SetFlag(LexerToken::NeedsCleaning);
267
268 Ptr += 3;
269 Size += 3;
270 if (C == '\\') goto Slash;
271 return C;
272 }
273 }
274
275 // If this is neither, return a single character.
276 ++Size;
277 return *Ptr;
278}
279
Chris Lattnerd01e2912006-06-18 16:22:51 +0000280
Chris Lattner22eb9722006-06-18 05:43:12 +0000281/// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
282/// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
283/// and that we have already incremented Ptr by Size bytes.
284///
Chris Lattnerd01e2912006-06-18 16:22:51 +0000285/// NOTE: When this method is updated, getCharAndSizeSlow (above) should
286/// be updated to match.
287char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
Chris Lattner22eb9722006-06-18 05:43:12 +0000288 const LangOptions &Features) {
289 // If we have a slash, look for an escaped newline.
290 if (Ptr[0] == '\\') {
291 ++Size;
292 ++Ptr;
293Slash:
294 // Common case, backslash-char where the char is not whitespace.
295 if (!isWhitespace(Ptr[0])) return '\\';
296
297 // See if we have optional whitespace characters followed by a newline.
298 {
299 unsigned SizeTmp = 0;
300 do {
301 ++SizeTmp;
302 if (Ptr[SizeTmp-1] == '\n' || Ptr[SizeTmp-1] == '\r') {
303
304 // If this is a \r\n or \n\r, skip the newlines.
305 if ((Ptr[SizeTmp] == '\r' || Ptr[SizeTmp] == '\n') &&
306 Ptr[SizeTmp-1] != Ptr[SizeTmp])
307 ++SizeTmp;
308
309 // Found backslash<whitespace><newline>. Parse the char after it.
310 Size += SizeTmp;
311 Ptr += SizeTmp;
312
313 // Use slow version to accumulate a correct size field.
314 return getCharAndSizeSlowNoWarn(Ptr, Size, Features);
315 }
316 } while (isWhitespace(Ptr[SizeTmp]));
317 }
318
319 // Otherwise, this is not an escaped newline, just return the slash.
320 return '\\';
321 }
322
323 // If this is a trigraph, process it.
324 if (Features.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
325 // If this is actually a legal trigraph (not something like "??x"), return
326 // it.
327 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
328 Ptr += 3;
329 Size += 3;
330 if (C == '\\') goto Slash;
331 return C;
332 }
333 }
334
335 // If this is neither, return a single character.
336 ++Size;
337 return *Ptr;
338}
339
Chris Lattner22eb9722006-06-18 05:43:12 +0000340//===----------------------------------------------------------------------===//
341// Helper methods for lexing.
342//===----------------------------------------------------------------------===//
343
Chris Lattnercb283342006-06-18 06:48:37 +0000344void Lexer::LexIdentifier(LexerToken &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000345 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
346 unsigned Size;
347 unsigned char C = *CurPtr++;
348 while (isIdentifierBody(C)) {
349 C = *CurPtr++;
350 }
351 --CurPtr; // Back up over the skipped character.
352
353 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
354 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
Chris Lattner505c5472006-07-03 00:55:48 +0000355 // FIXME: UCNs.
Chris Lattner22eb9722006-06-18 05:43:12 +0000356 if (C != '\\' && C != '?' && (C != '$' || !Features.DollarIdents)) {
357FinishIdentifier:
Chris Lattnercefc7682006-07-08 08:28:12 +0000358 const char *IdStart = BufferPtr;
Chris Lattnerd01e2912006-06-18 16:22:51 +0000359 FormTokenWithChars(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +0000360 Result.SetKind(tok::identifier);
361
Chris Lattnercefc7682006-07-08 08:28:12 +0000362 // Fill in Result.IdentifierInfo, looking up the identifier in the
363 // identifier table.
364 PP.LookUpIdentifierInfo(Result, IdStart);
Chris Lattner22eb9722006-06-18 05:43:12 +0000365
Chris Lattnerc5a00062006-06-18 16:41:01 +0000366 // Finally, now that we know we have an identifier, pass this off to the
367 // preprocessor, which may macro expand it or something.
Chris Lattner22eb9722006-06-18 05:43:12 +0000368 return PP.HandleIdentifier(Result);
369 }
370
371 // Otherwise, $,\,? in identifier found. Enter slower path.
372
373 C = getCharAndSize(CurPtr, Size);
374 while (1) {
375 if (C == '$') {
376 // If we hit a $ and they are not supported in identifiers, we are done.
377 if (!Features.DollarIdents) goto FinishIdentifier;
378
379 // Otherwise, emit a diagnostic and continue.
Chris Lattnercb283342006-06-18 06:48:37 +0000380 Diag(CurPtr, diag::ext_dollar_in_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +0000381 CurPtr = ConsumeChar(CurPtr, Size, Result);
382 C = getCharAndSize(CurPtr, Size);
383 continue;
Chris Lattner505c5472006-07-03 00:55:48 +0000384 } else if (!isIdentifierBody(C)) { // FIXME: UCNs.
Chris Lattner22eb9722006-06-18 05:43:12 +0000385 // Found end of identifier.
386 goto FinishIdentifier;
387 }
388
389 // Otherwise, this character is good, consume it.
390 CurPtr = ConsumeChar(CurPtr, Size, Result);
391
392 C = getCharAndSize(CurPtr, Size);
Chris Lattner505c5472006-07-03 00:55:48 +0000393 while (isIdentifierBody(C)) { // FIXME: UCNs.
Chris Lattner22eb9722006-06-18 05:43:12 +0000394 CurPtr = ConsumeChar(CurPtr, Size, Result);
395 C = getCharAndSize(CurPtr, Size);
396 }
397 }
398}
399
400
401/// LexNumericConstant - Lex the remainer of a integer or floating point
402/// constant. From[-1] is the first character lexed. Return the end of the
403/// constant.
Chris Lattnercb283342006-06-18 06:48:37 +0000404void Lexer::LexNumericConstant(LexerToken &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000405 unsigned Size;
406 char C = getCharAndSize(CurPtr, Size);
407 char PrevCh = 0;
Chris Lattner505c5472006-07-03 00:55:48 +0000408 while (isNumberBody(C)) { // FIXME: UCNs?
Chris Lattner22eb9722006-06-18 05:43:12 +0000409 CurPtr = ConsumeChar(CurPtr, Size, Result);
410 PrevCh = C;
411 C = getCharAndSize(CurPtr, Size);
412 }
413
414 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
415 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e'))
416 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
417
418 // If we have a hex FP constant, continue.
419 if (Features.HexFloats &&
420 (C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p'))
421 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
422
423 Result.SetKind(tok::numeric_constant);
424
Chris Lattnerd01e2912006-06-18 16:22:51 +0000425 // Update the location of token as well as BufferPtr.
426 FormTokenWithChars(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +0000427}
428
429/// LexStringLiteral - Lex the remainder of a string literal, after having lexed
430/// either " or L".
Chris Lattnercb283342006-06-18 06:48:37 +0000431void Lexer::LexStringLiteral(LexerToken &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000432 const char *NulCharacter = 0; // Does this string contain the \0 character?
433
434 char C = getAndAdvanceChar(CurPtr, Result);
435 while (C != '"') {
436 // Skip escaped characters.
437 if (C == '\\') {
438 // Skip the escaped character.
439 C = getAndAdvanceChar(CurPtr, Result);
440 } else if (C == '\n' || C == '\r' || // Newline.
441 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000442 Diag(BufferPtr, diag::err_unterminated_string);
Chris Lattner22eb9722006-06-18 05:43:12 +0000443 BufferPtr = CurPtr-1;
444 return LexTokenInternal(Result);
445 } else if (C == 0) {
446 NulCharacter = CurPtr-1;
447 }
448 C = getAndAdvanceChar(CurPtr, Result);
449 }
450
Chris Lattnercb283342006-06-18 06:48:37 +0000451 if (NulCharacter) Diag(NulCharacter, diag::null_in_string);
Chris Lattner22eb9722006-06-18 05:43:12 +0000452
453 Result.SetKind(tok::string_literal);
454
Chris Lattnerd01e2912006-06-18 16:22:51 +0000455 // Update the location of the token as well as the BufferPtr instance var.
456 FormTokenWithChars(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +0000457}
458
459/// LexAngledStringLiteral - Lex the remainder of an angled string literal,
460/// after having lexed the '<' character. This is used for #include filenames.
Chris Lattnercb283342006-06-18 06:48:37 +0000461void Lexer::LexAngledStringLiteral(LexerToken &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000462 const char *NulCharacter = 0; // Does this string contain the \0 character?
463
464 char C = getAndAdvanceChar(CurPtr, Result);
465 while (C != '>') {
466 // Skip escaped characters.
467 if (C == '\\') {
468 // Skip the escaped character.
469 C = getAndAdvanceChar(CurPtr, Result);
470 } else if (C == '\n' || C == '\r' || // Newline.
471 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000472 Diag(BufferPtr, diag::err_unterminated_string);
Chris Lattner22eb9722006-06-18 05:43:12 +0000473 BufferPtr = CurPtr-1;
474 return LexTokenInternal(Result);
475 } else if (C == 0) {
476 NulCharacter = CurPtr-1;
477 }
478 C = getAndAdvanceChar(CurPtr, Result);
479 }
480
Chris Lattnercb283342006-06-18 06:48:37 +0000481 if (NulCharacter) Diag(NulCharacter, diag::null_in_string);
Chris Lattner22eb9722006-06-18 05:43:12 +0000482
483 Result.SetKind(tok::angle_string_literal);
484
Chris Lattnerd01e2912006-06-18 16:22:51 +0000485 // Update the location of token as well as BufferPtr.
486 FormTokenWithChars(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +0000487}
488
489
490/// LexCharConstant - Lex the remainder of a character constant, after having
491/// lexed either ' or L'.
Chris Lattnercb283342006-06-18 06:48:37 +0000492void Lexer::LexCharConstant(LexerToken &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000493 const char *NulCharacter = 0; // Does this character contain the \0 character?
494
495 // Handle the common case of 'x' and '\y' efficiently.
496 char C = getAndAdvanceChar(CurPtr, Result);
497 if (C == '\'') {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000498 Diag(BufferPtr, diag::err_empty_character);
Chris Lattner22eb9722006-06-18 05:43:12 +0000499 BufferPtr = CurPtr;
500 return LexTokenInternal(Result);
501 } else if (C == '\\') {
502 // Skip the escaped character.
503 // FIXME: UCN's.
504 C = getAndAdvanceChar(CurPtr, Result);
505 }
506
507 if (C && C != '\n' && C != '\r' && CurPtr[0] == '\'') {
508 ++CurPtr;
509 } else {
510 // Fall back on generic code for embedded nulls, newlines, wide chars.
511 do {
512 // Skip escaped characters.
513 if (C == '\\') {
514 // Skip the escaped character.
515 C = getAndAdvanceChar(CurPtr, Result);
516 } else if (C == '\n' || C == '\r' || // Newline.
517 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000518 Diag(BufferPtr, diag::err_unterminated_char);
Chris Lattner22eb9722006-06-18 05:43:12 +0000519 BufferPtr = CurPtr-1;
520 return LexTokenInternal(Result);
521 } else if (C == 0) {
522 NulCharacter = CurPtr-1;
523 }
524 C = getAndAdvanceChar(CurPtr, Result);
525 } while (C != '\'');
526 }
527
Chris Lattnercb283342006-06-18 06:48:37 +0000528 if (NulCharacter) Diag(NulCharacter, diag::null_in_char);
Chris Lattner22eb9722006-06-18 05:43:12 +0000529
530 Result.SetKind(tok::char_constant);
531
Chris Lattnerd01e2912006-06-18 16:22:51 +0000532 // Update the location of token as well as BufferPtr.
533 FormTokenWithChars(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +0000534}
535
536/// SkipWhitespace - Efficiently skip over a series of whitespace characters.
537/// Update BufferPtr to point to the next non-whitespace character and return.
Chris Lattnercb283342006-06-18 06:48:37 +0000538void Lexer::SkipWhitespace(LexerToken &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000539 // Whitespace - Skip it, then return the token after the whitespace.
540 unsigned char Char = *CurPtr; // Skip consequtive spaces efficiently.
541 while (1) {
542 // Skip horizontal whitespace very aggressively.
543 while (isHorizontalWhitespace(Char))
544 Char = *++CurPtr;
545
546 // Otherwise if we something other than whitespace, we're done.
547 if (Char != '\n' && Char != '\r')
548 break;
549
550 if (ParsingPreprocessorDirective) {
551 // End of preprocessor directive line, let LexTokenInternal handle this.
552 BufferPtr = CurPtr;
Chris Lattnercb283342006-06-18 06:48:37 +0000553 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000554 }
555
556 // ok, but handle newline.
557 // The returned token is at the start of the line.
558 Result.SetFlag(LexerToken::StartOfLine);
559 // No leading whitespace seen so far.
560 Result.ClearFlag(LexerToken::LeadingSpace);
561 Char = *++CurPtr;
562 }
563
564 // If this isn't immediately after a newline, there is leading space.
565 char PrevChar = CurPtr[-1];
566 if (PrevChar != '\n' && PrevChar != '\r')
567 Result.SetFlag(LexerToken::LeadingSpace);
568
569 // If the next token is obviously a // or /* */ comment, skip it efficiently
570 // too (without going through the big switch stmt).
571 if (Char == '/' && CurPtr[1] == '/') {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000572 BufferPtr = CurPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +0000573 return SkipBCPLComment(Result, CurPtr+1);
574 }
575 if (Char == '/' && CurPtr[1] == '*') {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000576 BufferPtr = CurPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +0000577 return SkipBlockComment(Result, CurPtr+2);
578 }
579 BufferPtr = CurPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +0000580}
581
582// SkipBCPLComment - We have just read the // characters from input. Skip until
583// we find the newline character thats terminate the comment. Then update
584/// BufferPtr and return.
Chris Lattnercb283342006-06-18 06:48:37 +0000585void Lexer::SkipBCPLComment(LexerToken &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000586 // If BCPL comments aren't explicitly enabled for this language, emit an
587 // extension warning.
588 if (!Features.BCPLComment) {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000589 Diag(BufferPtr, diag::ext_bcpl_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +0000590
591 // Mark them enabled so we only emit one warning for this translation
592 // unit.
593 Features.BCPLComment = true;
594 }
595
596 // Scan over the body of the comment. The common case, when scanning, is that
597 // the comment contains normal ascii characters with nothing interesting in
598 // them. As such, optimize for this case with the inner loop.
599 char C;
600 do {
601 C = *CurPtr;
Chris Lattner505c5472006-07-03 00:55:48 +0000602 // FIXME: Speedup BCPL comment lexing. Just scan for a \n or \r character.
603 // If we find a \n character, scan backwards, checking to see if it's an
604 // escaped newline, like we do for block comments.
Chris Lattner22eb9722006-06-18 05:43:12 +0000605
606 // Skip over characters in the fast loop.
607 while (C != 0 && // Potentially EOF.
608 C != '\\' && // Potentially escaped newline.
609 C != '?' && // Potentially trigraph.
610 C != '\n' && C != '\r') // Newline or DOS-style newline.
611 C = *++CurPtr;
612
613 // If this is a newline, we're done.
614 if (C == '\n' || C == '\r')
615 break; // Found the newline? Break out!
616
617 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
618 // properly decode the character.
619 const char *OldPtr = CurPtr;
620 C = getAndAdvanceChar(CurPtr, Result);
621
622 // If we read multiple characters, and one of those characters was a \r or
623 // \n, then we had an escaped newline within the comment. Emit diagnostic.
624 if (CurPtr != OldPtr+1) {
625 for (; OldPtr != CurPtr; ++OldPtr)
626 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
Chris Lattnercb283342006-06-18 06:48:37 +0000627 Diag(OldPtr-1, diag::ext_multi_line_bcpl_comment);
628 break;
Chris Lattner22eb9722006-06-18 05:43:12 +0000629 }
630 }
631
632 if (CurPtr == BufferEnd+1) goto FoundEOF;
633 } while (C != '\n' && C != '\r');
634
635 // Found and did not consume a newline.
636
637 // If we are inside a preprocessor directive and we see the end of line,
638 // return immediately, so that the lexer can return this as an EOM token.
639 if (ParsingPreprocessorDirective) {
640 BufferPtr = CurPtr;
Chris Lattnercb283342006-06-18 06:48:37 +0000641 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000642 }
643
644 // Otherwise, eat the \n character. We don't care if this is a \n\r or
645 // \r\n sequence.
646 ++CurPtr;
647
648 // The next returned token is at the start of the line.
649 Result.SetFlag(LexerToken::StartOfLine);
650 // No leading whitespace seen so far.
651 Result.ClearFlag(LexerToken::LeadingSpace);
652
653 // It is common for the tokens immediately after a // comment to be
654 // whitespace (indentation for the next line). Instead of going through the
655 // big switch, handle it efficiently now.
656 if (isWhitespace(*CurPtr)) {
657 Result.SetFlag(LexerToken::LeadingSpace);
658 return SkipWhitespace(Result, CurPtr+1);
659 }
660
661 BufferPtr = CurPtr;
Chris Lattnercb283342006-06-18 06:48:37 +0000662 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000663
664FoundEOF: // If we ran off the end of the buffer, return EOF.
665 BufferPtr = CurPtr-1;
Chris Lattnercb283342006-06-18 06:48:37 +0000666 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000667}
668
Chris Lattnercb283342006-06-18 06:48:37 +0000669/// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
670/// character (either \n or \r) is part of an escaped newline sequence. Issue a
Chris Lattner22eb9722006-06-18 05:43:12 +0000671/// diagnostic if so. We know that the is inside of a block comment.
Chris Lattner1f583052006-06-18 06:53:56 +0000672static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
673 Lexer *L) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000674 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
Chris Lattner22eb9722006-06-18 05:43:12 +0000675
676 // Back up off the newline.
677 --CurPtr;
678
679 // If this is a two-character newline sequence, skip the other character.
680 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
681 // \n\n or \r\r -> not escaped newline.
682 if (CurPtr[0] == CurPtr[1])
683 return false;
684 // \n\r or \r\n -> skip the newline.
685 --CurPtr;
686 }
687
688 // If we have horizontal whitespace, skip over it. We allow whitespace
689 // between the slash and newline.
690 bool HasSpace = false;
691 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
692 --CurPtr;
693 HasSpace = true;
694 }
695
696 // If we have a slash, we know this is an escaped newline.
697 if (*CurPtr == '\\') {
Chris Lattnercb283342006-06-18 06:48:37 +0000698 if (CurPtr[-1] != '*') return false;
Chris Lattner22eb9722006-06-18 05:43:12 +0000699 } else {
700 // It isn't a slash, is it the ?? / trigraph?
Chris Lattnercb283342006-06-18 06:48:37 +0000701 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
702 CurPtr[-3] != '*')
Chris Lattner22eb9722006-06-18 05:43:12 +0000703 return false;
Chris Lattnercb283342006-06-18 06:48:37 +0000704
705 // This is the trigraph ending the comment. Emit a stern warning!
Chris Lattner22eb9722006-06-18 05:43:12 +0000706 CurPtr -= 2;
707
708 // If no trigraphs are enabled, warn that we ignored this trigraph and
709 // ignore this * character.
Chris Lattner1f583052006-06-18 06:53:56 +0000710 if (!L->getFeatures().Trigraphs) {
711 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
Chris Lattnercb283342006-06-18 06:48:37 +0000712 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +0000713 }
Chris Lattner1f583052006-06-18 06:53:56 +0000714 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +0000715 }
716
717 // Warn about having an escaped newline between the */ characters.
Chris Lattner1f583052006-06-18 06:53:56 +0000718 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
Chris Lattner22eb9722006-06-18 05:43:12 +0000719
720 // If there was space between the backslash and newline, warn about it.
Chris Lattner1f583052006-06-18 06:53:56 +0000721 if (HasSpace) L->Diag(CurPtr, diag::backslash_newline_space);
Chris Lattner22eb9722006-06-18 05:43:12 +0000722
Chris Lattnercb283342006-06-18 06:48:37 +0000723 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +0000724}
725
726/// SkipBlockComment - We have just read the /* characters from input. Read
727/// until we find the */ characters that terminate the comment. Note that we
728/// don't bother decoding trigraphs or escaped newlines in block comments,
729/// because they cannot cause the comment to end. The only thing that can
730/// happen is the comment could end with an escaped newline between the */ end
731/// of comment.
Chris Lattnercb283342006-06-18 06:48:37 +0000732void Lexer::SkipBlockComment(LexerToken &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000733 // Scan one character past where we should, looking for a '/' character. Once
734 // we find it, check to see if it was preceeded by a *. This common
735 // optimization helps people who like to put a lot of * characters in their
736 // comments.
737 unsigned char C = *CurPtr++;
738 if (C == 0 && CurPtr == BufferEnd+1) {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000739 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +0000740 BufferPtr = CurPtr-1;
Chris Lattnercb283342006-06-18 06:48:37 +0000741 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000742 }
743
744 while (1) {
745 // Skip over all non-interesting characters.
746 // TODO: Vectorize this. Note: memchr on Darwin is slower than this loop.
747 while (C != '/' && C != '\0')
748 C = *CurPtr++;
749
750 if (C == '/') {
Chris Lattner22eb9722006-06-18 05:43:12 +0000751 if (CurPtr[-2] == '*') // We found the final */. We're done!
752 break;
753
754 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
Chris Lattner1f583052006-06-18 06:53:56 +0000755 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000756 // We found the final */, though it had an escaped newline between the
757 // * and /. We're done!
758 break;
759 }
760 }
761 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
762 // If this is a /* inside of the comment, emit a warning. Don't do this
763 // if this is a /*/, which will end the comment. This misses cases with
764 // embedded escaped newlines, but oh well.
Chris Lattnercb283342006-06-18 06:48:37 +0000765 Diag(CurPtr-1, diag::nested_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +0000766 }
767 } else if (C == 0 && CurPtr == BufferEnd+1) {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000768 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +0000769 // Note: the user probably forgot a */. We could continue immediately
770 // after the /*, but this would involve lexing a lot of what really is the
771 // comment, which surely would confuse the parser.
772 BufferPtr = CurPtr-1;
Chris Lattnercb283342006-06-18 06:48:37 +0000773 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000774 }
775 C = *CurPtr++;
776 }
777
778 // It is common for the tokens immediately after a /**/ comment to be
779 // whitespace. Instead of going through the big switch, handle it
780 // efficiently now.
781 if (isHorizontalWhitespace(*CurPtr)) {
782 Result.SetFlag(LexerToken::LeadingSpace);
783 return SkipWhitespace(Result, CurPtr+1);
784 }
785
786 // Otherwise, just return so that the next character will be lexed as a token.
787 BufferPtr = CurPtr;
788 Result.SetFlag(LexerToken::LeadingSpace);
Chris Lattner22eb9722006-06-18 05:43:12 +0000789}
790
791//===----------------------------------------------------------------------===//
792// Primary Lexing Entry Points
793//===----------------------------------------------------------------------===//
794
795/// LexIncludeFilename - After the preprocessor has parsed a #include, lex and
796/// (potentially) macro expand the filename.
Chris Lattner269c2322006-06-25 06:23:00 +0000797std::string Lexer::LexIncludeFilename(LexerToken &FilenameTok) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000798 assert(ParsingPreprocessorDirective &&
799 ParsingFilename == false &&
800 "Must be in a preprocessing directive!");
801
802 // We are now parsing a filename!
803 ParsingFilename = true;
804
Chris Lattner269c2322006-06-25 06:23:00 +0000805 // Lex the filename.
806 Lex(FilenameTok);
Chris Lattner22eb9722006-06-18 05:43:12 +0000807
808 // We should have gotten the filename now.
809 ParsingFilename = false;
810
811 // No filename?
Chris Lattner269c2322006-06-25 06:23:00 +0000812 if (FilenameTok.getKind() == tok::eom) {
813 PP.Diag(FilenameTok, diag::err_pp_expects_filename);
814 return "";
Chris Lattnercb283342006-06-18 06:48:37 +0000815 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000816
Chris Lattner269c2322006-06-25 06:23:00 +0000817 // Get the text form of the filename.
818 std::string Filename = PP.getSpelling(FilenameTok);
819 assert(!Filename.empty() && "Can't have tokens with empty spellings!");
820
821 // Make sure the filename is <x> or "x".
822 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 if (Filename[0] == '"') {
829 if (Filename[Filename.size()-1] != '"') {
830 PP.Diag(FilenameTok, diag::err_pp_expects_filename);
831 FilenameTok.SetKind(tok::eom);
832 return "";
833 }
834 } else {
835 PP.Diag(FilenameTok, diag::err_pp_expects_filename);
836 FilenameTok.SetKind(tok::eom);
837 return "";
Chris Lattner22eb9722006-06-18 05:43:12 +0000838 }
Chris Lattner269c2322006-06-25 06:23:00 +0000839
840 // Diagnose #include "" as invalid.
841 if (Filename.size() == 2) {
842 PP.Diag(FilenameTok, diag::err_pp_empty_filename);
843 FilenameTok.SetKind(tok::eom);
844 return "";
845 }
846
847 return Filename;
Chris Lattner22eb9722006-06-18 05:43:12 +0000848}
849
850/// ReadToEndOfLine - Read the rest of the current preprocessor line as an
851/// uninterpreted string. This switches the lexer out of directive mode.
852std::string Lexer::ReadToEndOfLine() {
853 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
854 "Must be in a preprocessing directive!");
855 std::string Result;
856 LexerToken Tmp;
857
858 // CurPtr - Cache BufferPtr in an automatic variable.
859 const char *CurPtr = BufferPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +0000860 while (1) {
861 char Char = getAndAdvanceChar(CurPtr, Tmp);
862 switch (Char) {
863 default:
864 Result += Char;
865 break;
866 case 0: // Null.
867 // Found end of file?
868 if (CurPtr-1 != BufferEnd) {
869 // Nope, normal character, continue.
870 Result += Char;
871 break;
872 }
873 // FALL THROUGH.
874 case '\r':
875 case '\n':
876 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
877 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
878 BufferPtr = CurPtr-1;
879
880 // Next, lex the character, which should handle the EOM transition.
Chris Lattnercb283342006-06-18 06:48:37 +0000881 Lex(Tmp);
Chris Lattner22eb9722006-06-18 05:43:12 +0000882 assert(Tmp.getKind() == tok::eom && "Unexpected token!");
Chris Lattner22eb9722006-06-18 05:43:12 +0000883
884 // Finally, we're done, return the string we found.
885 return Result;
886 }
887 }
888}
889
890/// LexEndOfFile - CurPtr points to the end of this file. Handle this
891/// condition, reporting diagnostics and handling other edge cases as required.
Chris Lattnercb283342006-06-18 06:48:37 +0000892void Lexer::LexEndOfFile(LexerToken &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000893 // If we hit the end of the file while parsing a preprocessor directive,
894 // end the preprocessor directive first. The next token returned will
895 // then be the end of file.
896 if (ParsingPreprocessorDirective) {
897 // Done parsing the "line".
898 ParsingPreprocessorDirective = false;
899 Result.SetKind(tok::eom);
Chris Lattnerd01e2912006-06-18 16:22:51 +0000900 // Update the location of token as well as BufferPtr.
901 FormTokenWithChars(Result, CurPtr);
Chris Lattnercb283342006-06-18 06:48:37 +0000902 return;
Chris Lattner22eb9722006-06-18 05:43:12 +0000903 }
904
Chris Lattner3ebcf4e2006-07-11 05:39:23 +0000905 // If we aren't in raw mode, issue diagnostics. If we are in raw mode, let the
906 // code that put us into raw mode do this: there are multiple possible reasons
907 // for raw mode, and not all want these diagnostics.
908 if (!LexingRawMode) {
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000909 // If we are in a #if directive, emit an error.
910 while (!ConditionalStack.empty()) {
911 PP.Diag(ConditionalStack.back().IfLoc,
912 diag::err_pp_unterminated_conditional);
913 ConditionalStack.pop_back();
914 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000915
Chris Lattnerd8aee0e2006-07-11 05:04:55 +0000916 // If the file was empty or didn't end in a newline, issue a pedwarn.
917 if (CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
918 Diag(BufferEnd, diag::ext_no_newline_eof);
919 }
Chris Lattner22eb9722006-06-18 05:43:12 +0000920
921 BufferPtr = CurPtr;
Chris Lattnercb283342006-06-18 06:48:37 +0000922 PP.HandleEndOfFile(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +0000923}
924
Chris Lattner678c8802006-07-11 05:46:12 +0000925/// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
926/// the specified lexer will return a tok::l_paren token, 0 if it is something
927/// else and 2 if there are no more tokens in the buffer controlled by the
928/// lexer.
929unsigned Lexer::isNextPPTokenLParen() {
930 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
931
932 // Switch to 'skipping' mode. This will ensure that we can lex a token
933 // without emitting diagnostics, disables macro expansion, and will cause EOF
934 // to return an EOF token instead of popping the include stack.
935 LexingRawMode = true;
936
937 // Save state that can be changed while lexing so that we can restore it.
938 const char *TmpBufferPtr = BufferPtr;
939
940 LexerToken Tok;
941 Tok.StartToken();
942 LexTokenInternal(Tok);
943
944 // Restore state that may have changed.
945 BufferPtr = TmpBufferPtr;
946
947 // Restore the lexer back to non-skipping mode.
948 LexingRawMode = false;
949
950 if (Tok.getKind() == tok::eof)
951 return 2;
952 return Tok.getKind() == tok::l_paren;
953}
954
Chris Lattner22eb9722006-06-18 05:43:12 +0000955
956/// LexTokenInternal - This implements a simple C family lexer. It is an
957/// extremely performance critical piece of code. This assumes that the buffer
958/// has a null character at the end of the file. Return true if an error
959/// occurred and compilation should terminate, false if normal. This returns a
960/// preprocessing token, not a normal token, as such, it is an internal
961/// interface. It assumes that the Flags of result have been cleared before
962/// calling this.
Chris Lattnercb283342006-06-18 06:48:37 +0000963void Lexer::LexTokenInternal(LexerToken &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000964LexNextToken:
965 // New token, can't need cleaning yet.
966 Result.ClearFlag(LexerToken::NeedsCleaning);
Chris Lattner27746e42006-07-05 00:07:54 +0000967 Result.SetIdentifierInfo(0);
Chris Lattner22eb9722006-06-18 05:43:12 +0000968
969 // CurPtr - Cache BufferPtr in an automatic variable.
970 const char *CurPtr = BufferPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +0000971
Chris Lattnereb54b592006-07-10 06:34:27 +0000972 // Small amounts of horizontal whitespace is very common between tokens.
973 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
974 ++CurPtr;
975 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
976 ++CurPtr;
977 BufferPtr = CurPtr;
978 Result.SetFlag(LexerToken::LeadingSpace);
979 }
980
Chris Lattner22eb9722006-06-18 05:43:12 +0000981 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
982
983 // Read a character, advancing over it.
984 char Char = getAndAdvanceChar(CurPtr, Result);
985 switch (Char) {
986 case 0: // Null.
987 // Found end of file?
988 if (CurPtr-1 == BufferEnd)
989 return LexEndOfFile(Result, CurPtr-1); // Retreat back into the file.
990
Chris Lattnercb283342006-06-18 06:48:37 +0000991 Diag(CurPtr-1, diag::null_in_file);
Chris Lattner22eb9722006-06-18 05:43:12 +0000992 Result.SetFlag(LexerToken::LeadingSpace);
Chris Lattnercb283342006-06-18 06:48:37 +0000993 SkipWhitespace(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +0000994 goto LexNextToken; // GCC isn't tail call eliminating.
995 case '\n':
996 case '\r':
997 // If we are inside a preprocessor directive and we see the end of line,
998 // we know we are done with the directive, so return an EOM token.
999 if (ParsingPreprocessorDirective) {
1000 // Done parsing the "line".
1001 ParsingPreprocessorDirective = false;
1002
1003 // Since we consumed a newline, we are back at the start of a line.
1004 IsAtStartOfLine = true;
1005
1006 Result.SetKind(tok::eom);
1007 break;
1008 }
1009 // The returned token is at the start of the line.
1010 Result.SetFlag(LexerToken::StartOfLine);
1011 // No leading whitespace seen so far.
1012 Result.ClearFlag(LexerToken::LeadingSpace);
Chris Lattnercb283342006-06-18 06:48:37 +00001013 SkipWhitespace(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +00001014 goto LexNextToken; // GCC isn't tail call eliminating.
1015 case ' ':
1016 case '\t':
1017 case '\f':
1018 case '\v':
1019 Result.SetFlag(LexerToken::LeadingSpace);
Chris Lattnercb283342006-06-18 06:48:37 +00001020 SkipWhitespace(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +00001021 goto LexNextToken; // GCC isn't tail call eliminating.
1022
1023 case 'L':
Chris Lattner371ac8a2006-07-04 07:11:10 +00001024 // Notify MIOpt that we read a non-whitespace/non-comment token.
1025 MIOpt.ReadToken();
Chris Lattner22eb9722006-06-18 05:43:12 +00001026 Char = getCharAndSize(CurPtr, SizeTmp);
1027
1028 // Wide string literal.
1029 if (Char == '"')
1030 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result));
1031
1032 // Wide character constant.
1033 if (Char == '\'')
1034 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
1035 // FALL THROUGH, treating L like the start of an identifier.
1036
1037 // C99 6.4.2: Identifiers.
1038 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
1039 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
1040 case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U':
1041 case 'V': case 'W': case 'X': case 'Y': case 'Z':
1042 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
1043 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
1044 case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u':
1045 case 'v': case 'w': case 'x': case 'y': case 'z':
1046 case '_':
Chris Lattner371ac8a2006-07-04 07:11:10 +00001047 // Notify MIOpt that we read a non-whitespace/non-comment token.
1048 MIOpt.ReadToken();
Chris Lattner22eb9722006-06-18 05:43:12 +00001049 return LexIdentifier(Result, CurPtr);
1050
1051 // C99 6.4.4.1: Integer Constants.
1052 // C99 6.4.4.2: Floating Constants.
1053 case '0': case '1': case '2': case '3': case '4':
1054 case '5': case '6': case '7': case '8': case '9':
Chris Lattner371ac8a2006-07-04 07:11:10 +00001055 // Notify MIOpt that we read a non-whitespace/non-comment token.
1056 MIOpt.ReadToken();
Chris Lattner22eb9722006-06-18 05:43:12 +00001057 return LexNumericConstant(Result, CurPtr);
1058
1059 // C99 6.4.4: Character Constants.
1060 case '\'':
Chris Lattner371ac8a2006-07-04 07:11:10 +00001061 // Notify MIOpt that we read a non-whitespace/non-comment token.
1062 MIOpt.ReadToken();
Chris Lattner22eb9722006-06-18 05:43:12 +00001063 return LexCharConstant(Result, CurPtr);
1064
1065 // C99 6.4.5: String Literals.
1066 case '"':
Chris Lattner371ac8a2006-07-04 07:11:10 +00001067 // Notify MIOpt that we read a non-whitespace/non-comment token.
1068 MIOpt.ReadToken();
Chris Lattner22eb9722006-06-18 05:43:12 +00001069 return LexStringLiteral(Result, CurPtr);
1070
1071 // C99 6.4.6: Punctuators.
1072 case '?':
1073 Result.SetKind(tok::question);
1074 break;
1075 case '[':
1076 Result.SetKind(tok::l_square);
1077 break;
1078 case ']':
1079 Result.SetKind(tok::r_square);
1080 break;
1081 case '(':
1082 Result.SetKind(tok::l_paren);
1083 break;
1084 case ')':
1085 Result.SetKind(tok::r_paren);
1086 break;
1087 case '{':
1088 Result.SetKind(tok::l_brace);
1089 break;
1090 case '}':
1091 Result.SetKind(tok::r_brace);
1092 break;
1093 case '.':
1094 Char = getCharAndSize(CurPtr, SizeTmp);
1095 if (Char >= '0' && Char <= '9') {
Chris Lattner371ac8a2006-07-04 07:11:10 +00001096 // Notify MIOpt that we read a non-whitespace/non-comment token.
1097 MIOpt.ReadToken();
1098
Chris Lattner22eb9722006-06-18 05:43:12 +00001099 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
1100 } else if (Features.CPlusPlus && Char == '*') {
1101 Result.SetKind(tok::periodstar);
1102 CurPtr += SizeTmp;
1103 } else if (Char == '.' &&
1104 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
1105 Result.SetKind(tok::ellipsis);
1106 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1107 SizeTmp2, Result);
1108 } else {
1109 Result.SetKind(tok::period);
1110 }
1111 break;
1112 case '&':
1113 Char = getCharAndSize(CurPtr, SizeTmp);
1114 if (Char == '&') {
1115 Result.SetKind(tok::ampamp);
1116 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1117 } else if (Char == '=') {
1118 Result.SetKind(tok::ampequal);
1119 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1120 } else {
1121 Result.SetKind(tok::amp);
1122 }
1123 break;
1124 case '*':
1125 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
1126 Result.SetKind(tok::starequal);
1127 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1128 } else {
1129 Result.SetKind(tok::star);
1130 }
1131 break;
1132 case '+':
1133 Char = getCharAndSize(CurPtr, SizeTmp);
1134 if (Char == '+') {
1135 Result.SetKind(tok::plusplus);
1136 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1137 } else if (Char == '=') {
1138 Result.SetKind(tok::plusequal);
1139 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1140 } else {
1141 Result.SetKind(tok::plus);
1142 }
1143 break;
1144 case '-':
1145 Char = getCharAndSize(CurPtr, SizeTmp);
1146 if (Char == '-') {
1147 Result.SetKind(tok::minusminus);
1148 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1149 } else if (Char == '>' && Features.CPlusPlus &&
1150 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') {
1151 Result.SetKind(tok::arrowstar); // C++ ->*
1152 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1153 SizeTmp2, Result);
1154 } else if (Char == '>') {
1155 Result.SetKind(tok::arrow);
1156 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1157 } else if (Char == '=') {
1158 Result.SetKind(tok::minusequal);
1159 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1160 } else {
1161 Result.SetKind(tok::minus);
1162 }
1163 break;
1164 case '~':
1165 Result.SetKind(tok::tilde);
1166 break;
1167 case '!':
1168 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
1169 Result.SetKind(tok::exclaimequal);
1170 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1171 } else {
1172 Result.SetKind(tok::exclaim);
1173 }
1174 break;
1175 case '/':
1176 // 6.4.9: Comments
1177 Char = getCharAndSize(CurPtr, SizeTmp);
1178 if (Char == '/') { // BCPL comment.
1179 Result.SetFlag(LexerToken::LeadingSpace);
Chris Lattnercb283342006-06-18 06:48:37 +00001180 SkipBCPLComment(Result, ConsumeChar(CurPtr, SizeTmp, Result));
Chris Lattner22eb9722006-06-18 05:43:12 +00001181 goto LexNextToken; // GCC isn't tail call eliminating.
1182 } else if (Char == '*') { // /**/ comment.
1183 Result.SetFlag(LexerToken::LeadingSpace);
Chris Lattnercb283342006-06-18 06:48:37 +00001184 SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result));
Chris Lattner22eb9722006-06-18 05:43:12 +00001185 goto LexNextToken; // GCC isn't tail call eliminating.
1186 } else if (Char == '=') {
1187 Result.SetKind(tok::slashequal);
1188 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1189 } else {
1190 Result.SetKind(tok::slash);
1191 }
1192 break;
1193 case '%':
1194 Char = getCharAndSize(CurPtr, SizeTmp);
1195 if (Char == '=') {
1196 Result.SetKind(tok::percentequal);
1197 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1198 } else if (Features.Digraphs && Char == '>') {
1199 Result.SetKind(tok::r_brace); // '%>' -> '}'
1200 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1201 } else if (Features.Digraphs && Char == ':') {
1202 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner2b271db2006-07-15 05:41:09 +00001203 Char = getCharAndSize(CurPtr, SizeTmp);
1204 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
Chris Lattner22eb9722006-06-18 05:43:12 +00001205 Result.SetKind(tok::hashhash); // '%:%:' -> '##'
1206 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1207 SizeTmp2, Result);
Chris Lattner2b271db2006-07-15 05:41:09 +00001208 } else if (Char == '@' && Features.Microsoft) { // %:@ -> #@ -> Charize
1209 Result.SetKind(tok::hashat);
1210 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1211 Diag(BufferPtr, diag::charize_microsoft_ext);
Chris Lattner22eb9722006-06-18 05:43:12 +00001212 } else {
1213 Result.SetKind(tok::hash); // '%:' -> '#'
1214
1215 // We parsed a # character. If this occurs at the start of the line,
1216 // it's actually the start of a preprocessing directive. Callback to
1217 // the preprocessor to handle it.
1218 // FIXME: -fpreprocessed mode??
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001219 if (Result.isAtStartOfLine() && !LexingRawMode) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001220 BufferPtr = CurPtr;
Chris Lattnercb283342006-06-18 06:48:37 +00001221 PP.HandleDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001222
1223 // As an optimization, if the preprocessor didn't switch lexers, tail
1224 // recurse.
1225 if (PP.isCurrentLexer(this)) {
1226 // Start a new token. If this is a #include or something, the PP may
1227 // want us starting at the beginning of the line again. If so, set
1228 // the StartOfLine flag.
1229 if (IsAtStartOfLine) {
1230 Result.SetFlag(LexerToken::StartOfLine);
1231 IsAtStartOfLine = false;
1232 }
1233 goto LexNextToken; // GCC isn't tail call eliminating.
1234 }
1235
1236 return PP.Lex(Result);
1237 }
1238 }
1239 } else {
1240 Result.SetKind(tok::percent);
1241 }
1242 break;
1243 case '<':
1244 Char = getCharAndSize(CurPtr, SizeTmp);
1245 if (ParsingFilename) {
1246 return LexAngledStringLiteral(Result, CurPtr+SizeTmp);
1247 } else if (Char == '<' &&
1248 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '=') {
1249 Result.SetKind(tok::lesslessequal);
1250 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1251 SizeTmp2, Result);
1252 } else if (Char == '<') {
1253 Result.SetKind(tok::lessless);
1254 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1255 } else if (Char == '=') {
1256 Result.SetKind(tok::lessequal);
1257 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1258 } else if (Features.Digraphs && Char == ':') {
1259 Result.SetKind(tok::l_square); // '<:' -> '['
1260 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1261 } else if (Features.Digraphs && Char == '>') {
1262 Result.SetKind(tok::l_brace); // '<%' -> '{'
1263 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1264 } else if (Features.CPPMinMax && Char == '?') { // <?
1265 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerd01e2912006-06-18 16:22:51 +00001266 Diag(BufferPtr, diag::min_max_deprecated);
Chris Lattner22eb9722006-06-18 05:43:12 +00001267
1268 if (getCharAndSize(CurPtr, SizeTmp) == '=') { // <?=
1269 Result.SetKind(tok::lessquestionequal);
1270 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1271 } else {
1272 Result.SetKind(tok::lessquestion);
1273 }
1274 } else {
1275 Result.SetKind(tok::less);
1276 }
1277 break;
1278 case '>':
1279 Char = getCharAndSize(CurPtr, SizeTmp);
1280 if (Char == '=') {
1281 Result.SetKind(tok::greaterequal);
1282 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1283 } else if (Char == '>' &&
1284 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '=') {
1285 Result.SetKind(tok::greatergreaterequal);
1286 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
1287 SizeTmp2, Result);
1288 } else if (Char == '>') {
1289 Result.SetKind(tok::greatergreater);
1290 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1291 } else if (Features.CPPMinMax && Char == '?') {
1292 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerd01e2912006-06-18 16:22:51 +00001293 Diag(BufferPtr, diag::min_max_deprecated);
Chris Lattner22eb9722006-06-18 05:43:12 +00001294
1295 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
1296 Result.SetKind(tok::greaterquestionequal); // >?=
1297 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1298 } else {
1299 Result.SetKind(tok::greaterquestion); // >?
1300 }
1301 } else {
1302 Result.SetKind(tok::greater);
1303 }
1304 break;
1305 case '^':
1306 Char = getCharAndSize(CurPtr, SizeTmp);
1307 if (Char == '=') {
1308 Result.SetKind(tok::caretequal);
1309 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1310 } else {
1311 Result.SetKind(tok::caret);
1312 }
1313 break;
1314 case '|':
1315 Char = getCharAndSize(CurPtr, SizeTmp);
1316 if (Char == '=') {
1317 Result.SetKind(tok::pipeequal);
1318 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1319 } else if (Char == '|') {
1320 Result.SetKind(tok::pipepipe);
1321 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1322 } else {
1323 Result.SetKind(tok::pipe);
1324 }
1325 break;
1326 case ':':
1327 Char = getCharAndSize(CurPtr, SizeTmp);
1328 if (Features.Digraphs && Char == '>') {
1329 Result.SetKind(tok::r_square); // ':>' -> ']'
1330 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1331 } else if (Features.CPlusPlus && Char == ':') {
1332 Result.SetKind(tok::coloncolon);
1333 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1334 } else {
1335 Result.SetKind(tok::colon);
1336 }
1337 break;
1338 case ';':
1339 Result.SetKind(tok::semi);
1340 break;
1341 case '=':
1342 Char = getCharAndSize(CurPtr, SizeTmp);
1343 if (Char == '=') {
1344 Result.SetKind(tok::equalequal);
1345 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
1346 } else {
1347 Result.SetKind(tok::equal);
1348 }
1349 break;
1350 case ',':
1351 Result.SetKind(tok::comma);
1352 break;
1353 case '#':
1354 Char = getCharAndSize(CurPtr, SizeTmp);
1355 if (Char == '#') {
1356 Result.SetKind(tok::hashhash);
1357 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner2b271db2006-07-15 05:41:09 +00001358 } else if (Char == '@' && Features.Microsoft) { // #@ -> Charize
1359 Result.SetKind(tok::hashat);
1360 Diag(BufferPtr, diag::charize_microsoft_ext);
1361 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001362 } else {
1363 Result.SetKind(tok::hash);
1364 // We parsed a # character. If this occurs at the start of the line,
1365 // it's actually the start of a preprocessing directive. Callback to
1366 // the preprocessor to handle it.
Chris Lattner505c5472006-07-03 00:55:48 +00001367 // FIXME: -fpreprocessed mode??
Chris Lattner3ebcf4e2006-07-11 05:39:23 +00001368 if (Result.isAtStartOfLine() && !LexingRawMode) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001369 BufferPtr = CurPtr;
Chris Lattnercb283342006-06-18 06:48:37 +00001370 PP.HandleDirective(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001371
1372 // As an optimization, if the preprocessor didn't switch lexers, tail
1373 // recurse.
1374 if (PP.isCurrentLexer(this)) {
1375 // Start a new token. If this is a #include or something, the PP may
1376 // want us starting at the beginning of the line again. If so, set
1377 // the StartOfLine flag.
1378 if (IsAtStartOfLine) {
1379 Result.SetFlag(LexerToken::StartOfLine);
1380 IsAtStartOfLine = false;
1381 }
1382 goto LexNextToken; // GCC isn't tail call eliminating.
1383 }
1384 return PP.Lex(Result);
1385 }
1386 }
1387 break;
1388
1389 case '\\':
Chris Lattner505c5472006-07-03 00:55:48 +00001390 // FIXME: UCN's.
Chris Lattner22eb9722006-06-18 05:43:12 +00001391 // FALL THROUGH.
1392 default:
1393 // Objective C support.
1394 if (CurPtr[-1] == '@' && Features.ObjC1) {
1395 Result.SetKind(tok::at);
1396 break;
1397 } else if (CurPtr[-1] == '$' && Features.DollarIdents) {// $ in identifiers.
Chris Lattnercb283342006-06-18 06:48:37 +00001398 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
Chris Lattner371ac8a2006-07-04 07:11:10 +00001399 // Notify MIOpt that we read a non-whitespace/non-comment token.
1400 MIOpt.ReadToken();
Chris Lattner22eb9722006-06-18 05:43:12 +00001401 return LexIdentifier(Result, CurPtr);
1402 }
1403
Chris Lattner041bef82006-07-11 05:52:53 +00001404 Result.SetKind(tok::unknown);
1405 break;
Chris Lattner22eb9722006-06-18 05:43:12 +00001406 }
1407
Chris Lattner371ac8a2006-07-04 07:11:10 +00001408 // Notify MIOpt that we read a non-whitespace/non-comment token.
1409 MIOpt.ReadToken();
1410
Chris Lattnerd01e2912006-06-18 16:22:51 +00001411 // Update the location of token as well as BufferPtr.
1412 FormTokenWithChars(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +00001413}