blob: 839cec0744f48d81755db7a1ebf589d6340f6cb7 [file] [log] [blame]
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001//===--- MacroExpansion.cpp - Top level Macro Expansion -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the top level handling of macro expasion for the
11// preprocessor.
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang/Lex/Preprocessor.h"
16#include "MacroArgs.h"
17#include "clang/Lex/MacroInfo.h"
18#include "clang/Basic/SourceManager.h"
19#include "clang/Basic/FileManager.h"
20#include "clang/Basic/TargetInfo.h"
21#include "clang/Lex/LexDiagnostic.h"
22#include "clang/Lex/CodeCompletionHandler.h"
23#include "clang/Lex/ExternalPreprocessorSource.h"
24#include "clang/Lex/LiteralSupport.h"
25#include "llvm/ADT/StringSwitch.h"
26#include "llvm/ADT/STLExtras.h"
27#include "llvm/Config/llvm-config.h"
28#include "llvm/Support/raw_ostream.h"
29#include "llvm/Support/ErrorHandling.h"
Dmitri Gribenkoae07f722012-09-24 20:56:28 +000030#include "llvm/Support/Format.h"
Joao Matosc0d4c1b2012-08-31 21:34:27 +000031#include <cstdio>
32#include <ctime>
33using namespace clang;
34
35MacroInfo *Preprocessor::getInfoForMacro(IdentifierInfo *II) const {
36 assert(II->hasMacroDefinition() && "Identifier is not a macro!");
37
38 macro_iterator Pos = Macros.find(II);
39 if (Pos == Macros.end()) {
40 // Load this macro from the external source.
41 getExternalSource()->LoadMacroDefinition(II);
42 Pos = Macros.find(II);
43 }
44 assert(Pos != Macros.end() && "Identifier macro info is missing!");
45 assert(Pos->second->getUndefLoc().isInvalid() && "Macro is undefined!");
46 return Pos->second;
47}
48
49/// setMacroInfo - Specify a macro for this identifier.
50///
51void Preprocessor::setMacroInfo(IdentifierInfo *II, MacroInfo *MI,
52 bool LoadedFromAST) {
53 assert(MI && "MacroInfo should be non-zero!");
54 MI->setPreviousDefinition(Macros[II]);
55 Macros[II] = MI;
56 II->setHasMacroDefinition(true);
57 if (II->isFromAST() && !LoadedFromAST)
58 II->setChangedSinceDeserialization();
59}
60
61/// \brief Undefine a macro for this identifier.
62void Preprocessor::clearMacroInfo(IdentifierInfo *II) {
63 assert(II->hasMacroDefinition() && "Macro is not defined!");
64 assert(Macros[II]->getUndefLoc().isValid() && "Macro is still defined!");
65 II->setHasMacroDefinition(false);
66 if (II->isFromAST())
67 II->setChangedSinceDeserialization();
68}
69
70/// RegisterBuiltinMacro - Register the specified identifier in the identifier
71/// table and mark it as a builtin macro to be expanded.
72static IdentifierInfo *RegisterBuiltinMacro(Preprocessor &PP, const char *Name){
73 // Get the identifier.
74 IdentifierInfo *Id = PP.getIdentifierInfo(Name);
75
76 // Mark it as being a macro that is builtin.
77 MacroInfo *MI = PP.AllocateMacroInfo(SourceLocation());
78 MI->setIsBuiltinMacro();
79 PP.setMacroInfo(Id, MI);
80 return Id;
81}
82
83
84/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
85/// identifier table.
86void Preprocessor::RegisterBuiltinMacros() {
87 Ident__LINE__ = RegisterBuiltinMacro(*this, "__LINE__");
88 Ident__FILE__ = RegisterBuiltinMacro(*this, "__FILE__");
89 Ident__DATE__ = RegisterBuiltinMacro(*this, "__DATE__");
90 Ident__TIME__ = RegisterBuiltinMacro(*this, "__TIME__");
91 Ident__COUNTER__ = RegisterBuiltinMacro(*this, "__COUNTER__");
92 Ident_Pragma = RegisterBuiltinMacro(*this, "_Pragma");
93
94 // GCC Extensions.
95 Ident__BASE_FILE__ = RegisterBuiltinMacro(*this, "__BASE_FILE__");
96 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro(*this, "__INCLUDE_LEVEL__");
97 Ident__TIMESTAMP__ = RegisterBuiltinMacro(*this, "__TIMESTAMP__");
98
99 // Clang Extensions.
100 Ident__has_feature = RegisterBuiltinMacro(*this, "__has_feature");
101 Ident__has_extension = RegisterBuiltinMacro(*this, "__has_extension");
102 Ident__has_builtin = RegisterBuiltinMacro(*this, "__has_builtin");
103 Ident__has_attribute = RegisterBuiltinMacro(*this, "__has_attribute");
104 Ident__has_include = RegisterBuiltinMacro(*this, "__has_include");
105 Ident__has_include_next = RegisterBuiltinMacro(*this, "__has_include_next");
106 Ident__has_warning = RegisterBuiltinMacro(*this, "__has_warning");
107
108 // Microsoft Extensions.
109 if (LangOpts.MicrosoftExt)
110 Ident__pragma = RegisterBuiltinMacro(*this, "__pragma");
111 else
112 Ident__pragma = 0;
113}
114
115/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
116/// in its expansion, currently expands to that token literally.
117static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
118 const IdentifierInfo *MacroIdent,
119 Preprocessor &PP) {
120 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
121
122 // If the token isn't an identifier, it's always literally expanded.
123 if (II == 0) return true;
124
125 // If the information about this identifier is out of date, update it from
126 // the external source.
127 if (II->isOutOfDate())
128 PP.getExternalSource()->updateOutOfDateIdentifier(*II);
129
130 // If the identifier is a macro, and if that macro is enabled, it may be
131 // expanded so it's not a trivial expansion.
132 if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled() &&
133 // Fast expanding "#define X X" is ok, because X would be disabled.
134 II != MacroIdent)
135 return false;
136
137 // If this is an object-like macro invocation, it is safe to trivially expand
138 // it.
139 if (MI->isObjectLike()) return true;
140
141 // If this is a function-like macro invocation, it's safe to trivially expand
142 // as long as the identifier is not a macro argument.
143 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
144 I != E; ++I)
145 if (*I == II)
146 return false; // Identifier is a macro argument.
147
148 return true;
149}
150
151
152/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
153/// lexed is a '('. If so, consume the token and return true, if not, this
154/// method should have no observable side-effect on the lexed tokens.
155bool Preprocessor::isNextPPTokenLParen() {
156 // Do some quick tests for rejection cases.
157 unsigned Val;
158 if (CurLexer)
159 Val = CurLexer->isNextPPTokenLParen();
160 else if (CurPTHLexer)
161 Val = CurPTHLexer->isNextPPTokenLParen();
162 else
163 Val = CurTokenLexer->isNextTokenLParen();
164
165 if (Val == 2) {
166 // We have run off the end. If it's a source file we don't
167 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the
168 // macro stack.
169 if (CurPPLexer)
170 return false;
171 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
172 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
173 if (Entry.TheLexer)
174 Val = Entry.TheLexer->isNextPPTokenLParen();
175 else if (Entry.ThePTHLexer)
176 Val = Entry.ThePTHLexer->isNextPPTokenLParen();
177 else
178 Val = Entry.TheTokenLexer->isNextTokenLParen();
179
180 if (Val != 2)
181 break;
182
183 // Ran off the end of a source file?
184 if (Entry.ThePPLexer)
185 return false;
186 }
187 }
188
189 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
190 // have found something that isn't a '(' or we found the end of the
191 // translation unit. In either case, return false.
192 return Val == 1;
193}
194
195/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
196/// expanded as a macro, handle it and return the next token as 'Identifier'.
197bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
198 MacroInfo *MI) {
199 // If this is a macro expansion in the "#if !defined(x)" line for the file,
200 // then the macro could expand to different things in other contexts, we need
201 // to disable the optimization in this case.
202 if (CurPPLexer) CurPPLexer->MIOpt.ExpandedMacro();
203
204 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
205 if (MI->isBuiltinMacro()) {
206 if (Callbacks) Callbacks->MacroExpands(Identifier, MI,
207 Identifier.getLocation());
208 ExpandBuiltinMacro(Identifier);
209 return false;
210 }
211
212 /// Args - If this is a function-like macro expansion, this contains,
213 /// for each macro argument, the list of tokens that were provided to the
214 /// invocation.
215 MacroArgs *Args = 0;
216
217 // Remember where the end of the expansion occurred. For an object-like
218 // macro, this is the identifier. For a function-like macro, this is the ')'.
219 SourceLocation ExpansionEnd = Identifier.getLocation();
220
221 // If this is a function-like macro, read the arguments.
222 if (MI->isFunctionLike()) {
223 // C99 6.10.3p10: If the preprocessing token immediately after the macro
224 // name isn't a '(', this macro should not be expanded.
225 if (!isNextPPTokenLParen())
226 return true;
227
228 // Remember that we are now parsing the arguments to a macro invocation.
229 // Preprocessor directives used inside macro arguments are not portable, and
230 // this enables the warning.
231 InMacroArgs = true;
232 Args = ReadFunctionLikeMacroArgs(Identifier, MI, ExpansionEnd);
233
234 // Finished parsing args.
235 InMacroArgs = false;
236
237 // If there was an error parsing the arguments, bail out.
238 if (Args == 0) return false;
239
240 ++NumFnMacroExpanded;
241 } else {
242 ++NumMacroExpanded;
243 }
244
245 // Notice that this macro has been used.
246 markMacroAsUsed(MI);
247
248 // Remember where the token is expanded.
249 SourceLocation ExpandLoc = Identifier.getLocation();
250 SourceRange ExpansionRange(ExpandLoc, ExpansionEnd);
251
252 if (Callbacks) {
253 if (InMacroArgs) {
254 // We can have macro expansion inside a conditional directive while
255 // reading the function macro arguments. To ensure, in that case, that
256 // MacroExpands callbacks still happen in source order, queue this
257 // callback to have it happen after the function macro callback.
258 DelayedMacroExpandsCallbacks.push_back(
259 MacroExpandsInfo(Identifier, MI, ExpansionRange));
260 } else {
261 Callbacks->MacroExpands(Identifier, MI, ExpansionRange);
262 if (!DelayedMacroExpandsCallbacks.empty()) {
263 for (unsigned i=0, e = DelayedMacroExpandsCallbacks.size(); i!=e; ++i) {
264 MacroExpandsInfo &Info = DelayedMacroExpandsCallbacks[i];
265 Callbacks->MacroExpands(Info.Tok, Info.MI, Info.Range);
266 }
267 DelayedMacroExpandsCallbacks.clear();
268 }
269 }
270 }
271
272 // If we started lexing a macro, enter the macro expansion body.
273
274 // If this macro expands to no tokens, don't bother to push it onto the
275 // expansion stack, only to take it right back off.
276 if (MI->getNumTokens() == 0) {
277 // No need for arg info.
278 if (Args) Args->destroy(*this);
279
280 // Ignore this macro use, just return the next token in the current
281 // buffer.
282 bool HadLeadingSpace = Identifier.hasLeadingSpace();
283 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
284
285 Lex(Identifier);
286
287 // If the identifier isn't on some OTHER line, inherit the leading
288 // whitespace/first-on-a-line property of this token. This handles
289 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
290 // empty.
291 if (!Identifier.isAtStartOfLine()) {
292 if (IsAtStartOfLine) Identifier.setFlag(Token::StartOfLine);
293 if (HadLeadingSpace) Identifier.setFlag(Token::LeadingSpace);
294 }
295 Identifier.setFlag(Token::LeadingEmptyMacro);
296 ++NumFastMacroExpanded;
297 return false;
298
299 } else if (MI->getNumTokens() == 1 &&
300 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
301 *this)) {
302 // Otherwise, if this macro expands into a single trivially-expanded
303 // token: expand it now. This handles common cases like
304 // "#define VAL 42".
305
306 // No need for arg info.
307 if (Args) Args->destroy(*this);
308
309 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
310 // identifier to the expanded token.
311 bool isAtStartOfLine = Identifier.isAtStartOfLine();
312 bool hasLeadingSpace = Identifier.hasLeadingSpace();
313
314 // Replace the result token.
315 Identifier = MI->getReplacementToken(0);
316
317 // Restore the StartOfLine/LeadingSpace markers.
318 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
319 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
320
321 // Update the tokens location to include both its expansion and physical
322 // locations.
323 SourceLocation Loc =
324 SourceMgr.createExpansionLoc(Identifier.getLocation(), ExpandLoc,
325 ExpansionEnd,Identifier.getLength());
326 Identifier.setLocation(Loc);
327
328 // If this is a disabled macro or #define X X, we must mark the result as
329 // unexpandable.
330 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo()) {
331 if (MacroInfo *NewMI = getMacroInfo(NewII))
332 if (!NewMI->isEnabled() || NewMI == MI) {
333 Identifier.setFlag(Token::DisableExpand);
334 Diag(Identifier, diag::pp_disabled_macro_expansion);
335 }
336 }
337
338 // Since this is not an identifier token, it can't be macro expanded, so
339 // we're done.
340 ++NumFastMacroExpanded;
341 return false;
342 }
343
344 // Start expanding the macro.
345 EnterMacro(Identifier, ExpansionEnd, MI, Args);
346
347 // Now that the macro is at the top of the include stack, ask the
348 // preprocessor to read the next token from it.
349 Lex(Identifier);
350 return false;
351}
352
353/// ReadFunctionLikeMacroArgs - After reading "MACRO" and knowing that the next
354/// token is the '(' of the macro, this method is invoked to read all of the
355/// actual arguments specified for the macro invocation. This returns null on
356/// error.
357MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
358 MacroInfo *MI,
359 SourceLocation &MacroEnd) {
360 // The number of fixed arguments to parse.
361 unsigned NumFixedArgsLeft = MI->getNumArgs();
362 bool isVariadic = MI->isVariadic();
363
364 // Outer loop, while there are more arguments, keep reading them.
365 Token Tok;
366
367 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
368 // an argument value in a macro could expand to ',' or '(' or ')'.
369 LexUnexpandedToken(Tok);
370 assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
371
372 // ArgTokens - Build up a list of tokens that make up each argument. Each
373 // argument is separated by an EOF token. Use a SmallVector so we can avoid
374 // heap allocations in the common case.
375 SmallVector<Token, 64> ArgTokens;
376
377 unsigned NumActuals = 0;
378 while (Tok.isNot(tok::r_paren)) {
379 assert((Tok.is(tok::l_paren) || Tok.is(tok::comma)) &&
380 "only expect argument separators here");
381
382 unsigned ArgTokenStart = ArgTokens.size();
383 SourceLocation ArgStartLoc = Tok.getLocation();
384
385 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
386 // that we already consumed the first one.
387 unsigned NumParens = 0;
388
389 while (1) {
390 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
391 // an argument value in a macro could expand to ',' or '(' or ')'.
392 LexUnexpandedToken(Tok);
393
394 if (Tok.is(tok::eof) || Tok.is(tok::eod)) { // "#if f(<eof>" & "#if f(\n"
395 Diag(MacroName, diag::err_unterm_macro_invoc);
396 // Do not lose the EOF/EOD. Return it to the client.
397 MacroName = Tok;
398 return 0;
399 } else if (Tok.is(tok::r_paren)) {
400 // If we found the ) token, the macro arg list is done.
401 if (NumParens-- == 0) {
402 MacroEnd = Tok.getLocation();
403 break;
404 }
405 } else if (Tok.is(tok::l_paren)) {
406 ++NumParens;
407 // In Microsoft-compatibility mode, commas from nested macro expan-
408 // sions should not be considered as argument separators. We test
409 // for this with the IgnoredComma token flag.
410 } else if (Tok.is(tok::comma)
411 && !(Tok.getFlags() & Token::IgnoredComma) && NumParens == 0) {
412 // Comma ends this argument if there are more fixed arguments expected.
413 // However, if this is a variadic macro, and this is part of the
414 // variadic part, then the comma is just an argument token.
415 if (!isVariadic) break;
416 if (NumFixedArgsLeft > 1)
417 break;
418 } else if (Tok.is(tok::comment) && !KeepMacroComments) {
419 // If this is a comment token in the argument list and we're just in
420 // -C mode (not -CC mode), discard the comment.
421 continue;
422 } else if (Tok.getIdentifierInfo() != 0) {
423 // Reading macro arguments can cause macros that we are currently
424 // expanding from to be popped off the expansion stack. Doing so causes
425 // them to be reenabled for expansion. Here we record whether any
426 // identifiers we lex as macro arguments correspond to disabled macros.
427 // If so, we mark the token as noexpand. This is a subtle aspect of
428 // C99 6.10.3.4p2.
429 if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
430 if (!MI->isEnabled())
431 Tok.setFlag(Token::DisableExpand);
432 } else if (Tok.is(tok::code_completion)) {
433 if (CodeComplete)
434 CodeComplete->CodeCompleteMacroArgument(MacroName.getIdentifierInfo(),
435 MI, NumActuals);
436 // Don't mark that we reached the code-completion point because the
437 // parser is going to handle the token and there will be another
438 // code-completion callback.
439 }
440
441 ArgTokens.push_back(Tok);
442 }
443
444 // If this was an empty argument list foo(), don't add this as an empty
445 // argument.
446 if (ArgTokens.empty() && Tok.getKind() == tok::r_paren)
447 break;
448
449 // If this is not a variadic macro, and too many args were specified, emit
450 // an error.
451 if (!isVariadic && NumFixedArgsLeft == 0) {
452 if (ArgTokens.size() != ArgTokenStart)
453 ArgStartLoc = ArgTokens[ArgTokenStart].getLocation();
454
455 // Emit the diagnostic at the macro name in case there is a missing ).
456 // Emitting it at the , could be far away from the macro name.
457 Diag(ArgStartLoc, diag::err_too_many_args_in_macro_invoc);
458 return 0;
459 }
460
461 // Empty arguments are standard in C99 and C++0x, and are supported as an extension in
462 // other modes.
463 if (ArgTokens.size() == ArgTokenStart && !LangOpts.C99)
464 Diag(Tok, LangOpts.CPlusPlus0x ?
465 diag::warn_cxx98_compat_empty_fnmacro_arg :
466 diag::ext_empty_fnmacro_arg);
467
468 // Add a marker EOF token to the end of the token list for this argument.
469 Token EOFTok;
470 EOFTok.startToken();
471 EOFTok.setKind(tok::eof);
472 EOFTok.setLocation(Tok.getLocation());
473 EOFTok.setLength(0);
474 ArgTokens.push_back(EOFTok);
475 ++NumActuals;
476 assert(NumFixedArgsLeft != 0 && "Too many arguments parsed");
477 --NumFixedArgsLeft;
478 }
479
480 // Okay, we either found the r_paren. Check to see if we parsed too few
481 // arguments.
482 unsigned MinArgsExpected = MI->getNumArgs();
483
484 // See MacroArgs instance var for description of this.
485 bool isVarargsElided = false;
486
487 if (NumActuals < MinArgsExpected) {
488 // There are several cases where too few arguments is ok, handle them now.
489 if (NumActuals == 0 && MinArgsExpected == 1) {
490 // #define A(X) or #define A(...) ---> A()
491
492 // If there is exactly one argument, and that argument is missing,
493 // then we have an empty "()" argument empty list. This is fine, even if
494 // the macro expects one argument (the argument is just empty).
495 isVarargsElided = MI->isVariadic();
496 } else if (MI->isVariadic() &&
497 (NumActuals+1 == MinArgsExpected || // A(x, ...) -> A(X)
498 (NumActuals == 0 && MinArgsExpected == 2))) {// A(x,...) -> A()
499 // Varargs where the named vararg parameter is missing: OK as extension.
500 // #define A(x, ...)
501 // A("blah")
502 Diag(Tok, diag::ext_missing_varargs_arg);
503 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
504 << MacroName.getIdentifierInfo();
505
506 // Remember this occurred, allowing us to elide the comma when used for
507 // cases like:
508 // #define A(x, foo...) blah(a, ## foo)
509 // #define B(x, ...) blah(a, ## __VA_ARGS__)
510 // #define C(...) blah(a, ## __VA_ARGS__)
511 // A(x) B(x) C()
512 isVarargsElided = true;
513 } else {
514 // Otherwise, emit the error.
515 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
516 return 0;
517 }
518
519 // Add a marker EOF token to the end of the token list for this argument.
520 SourceLocation EndLoc = Tok.getLocation();
521 Tok.startToken();
522 Tok.setKind(tok::eof);
523 Tok.setLocation(EndLoc);
524 Tok.setLength(0);
525 ArgTokens.push_back(Tok);
526
527 // If we expect two arguments, add both as empty.
528 if (NumActuals == 0 && MinArgsExpected == 2)
529 ArgTokens.push_back(Tok);
530
531 } else if (NumActuals > MinArgsExpected && !MI->isVariadic()) {
532 // Emit the diagnostic at the macro name in case there is a missing ).
533 // Emitting it at the , could be far away from the macro name.
534 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
535 return 0;
536 }
537
538 return MacroArgs::create(MI, ArgTokens, isVarargsElided, *this);
539}
540
541/// \brief Keeps macro expanded tokens for TokenLexers.
542//
543/// Works like a stack; a TokenLexer adds the macro expanded tokens that is
544/// going to lex in the cache and when it finishes the tokens are removed
545/// from the end of the cache.
546Token *Preprocessor::cacheMacroExpandedTokens(TokenLexer *tokLexer,
547 ArrayRef<Token> tokens) {
548 assert(tokLexer);
549 if (tokens.empty())
550 return 0;
551
552 size_t newIndex = MacroExpandedTokens.size();
553 bool cacheNeedsToGrow = tokens.size() >
554 MacroExpandedTokens.capacity()-MacroExpandedTokens.size();
555 MacroExpandedTokens.append(tokens.begin(), tokens.end());
556
557 if (cacheNeedsToGrow) {
558 // Go through all the TokenLexers whose 'Tokens' pointer points in the
559 // buffer and update the pointers to the (potential) new buffer array.
560 for (unsigned i = 0, e = MacroExpandingLexersStack.size(); i != e; ++i) {
561 TokenLexer *prevLexer;
562 size_t tokIndex;
563 llvm::tie(prevLexer, tokIndex) = MacroExpandingLexersStack[i];
564 prevLexer->Tokens = MacroExpandedTokens.data() + tokIndex;
565 }
566 }
567
568 MacroExpandingLexersStack.push_back(std::make_pair(tokLexer, newIndex));
569 return MacroExpandedTokens.data() + newIndex;
570}
571
572void Preprocessor::removeCachedMacroExpandedTokensOfLastLexer() {
573 assert(!MacroExpandingLexersStack.empty());
574 size_t tokIndex = MacroExpandingLexersStack.back().second;
575 assert(tokIndex < MacroExpandedTokens.size());
576 // Pop the cached macro expanded tokens from the end.
577 MacroExpandedTokens.resize(tokIndex);
578 MacroExpandingLexersStack.pop_back();
579}
580
581/// ComputeDATE_TIME - Compute the current time, enter it into the specified
582/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
583/// the identifier tokens inserted.
584static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
585 Preprocessor &PP) {
586 time_t TT = time(0);
587 struct tm *TM = localtime(&TT);
588
589 static const char * const Months[] = {
590 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
591 };
592
Dmitri Gribenkoae07f722012-09-24 20:56:28 +0000593 {
594 SmallString<32> TmpBuffer;
595 llvm::raw_svector_ostream TmpStream(TmpBuffer);
596 TmpStream << llvm::format("\"%s %2d %4d\"", Months[TM->tm_mon],
597 TM->tm_mday, TM->tm_year + 1900);
Dmitri Gribenkoae07f722012-09-24 20:56:28 +0000598 Token TmpTok;
599 TmpTok.startToken();
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000600 PP.CreateString(TmpStream.str(), TmpTok);
Dmitri Gribenkoae07f722012-09-24 20:56:28 +0000601 DATELoc = TmpTok.getLocation();
602 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000603
Dmitri Gribenkoae07f722012-09-24 20:56:28 +0000604 {
605 SmallString<32> TmpBuffer;
606 llvm::raw_svector_ostream TmpStream(TmpBuffer);
607 TmpStream << llvm::format("\"%02d:%02d:%02d\"",
608 TM->tm_hour, TM->tm_min, TM->tm_sec);
Dmitri Gribenkoae07f722012-09-24 20:56:28 +0000609 Token TmpTok;
610 TmpTok.startToken();
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000611 PP.CreateString(TmpStream.str(), TmpTok);
Dmitri Gribenkoae07f722012-09-24 20:56:28 +0000612 TIMELoc = TmpTok.getLocation();
613 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000614}
615
616
617/// HasFeature - Return true if we recognize and implement the feature
618/// specified by the identifier as a standard language feature.
619static bool HasFeature(const Preprocessor &PP, const IdentifierInfo *II) {
620 const LangOptions &LangOpts = PP.getLangOpts();
621 StringRef Feature = II->getName();
622
623 // Normalize the feature name, __foo__ becomes foo.
624 if (Feature.startswith("__") && Feature.endswith("__") && Feature.size() >= 4)
625 Feature = Feature.substr(2, Feature.size() - 4);
626
627 return llvm::StringSwitch<bool>(Feature)
628 .Case("address_sanitizer", LangOpts.AddressSanitizer)
629 .Case("attribute_analyzer_noreturn", true)
630 .Case("attribute_availability", true)
631 .Case("attribute_availability_with_message", true)
632 .Case("attribute_cf_returns_not_retained", true)
633 .Case("attribute_cf_returns_retained", true)
634 .Case("attribute_deprecated_with_message", true)
635 .Case("attribute_ext_vector_type", true)
636 .Case("attribute_ns_returns_not_retained", true)
637 .Case("attribute_ns_returns_retained", true)
638 .Case("attribute_ns_consumes_self", true)
639 .Case("attribute_ns_consumed", true)
640 .Case("attribute_cf_consumed", true)
641 .Case("attribute_objc_ivar_unused", true)
642 .Case("attribute_objc_method_family", true)
643 .Case("attribute_overloadable", true)
644 .Case("attribute_unavailable_with_message", true)
645 .Case("attribute_unused_on_fields", true)
646 .Case("blocks", LangOpts.Blocks)
647 .Case("cxx_exceptions", LangOpts.Exceptions)
648 .Case("cxx_rtti", LangOpts.RTTI)
649 .Case("enumerator_attributes", true)
650 // Objective-C features
651 .Case("objc_arr", LangOpts.ObjCAutoRefCount) // FIXME: REMOVE?
652 .Case("objc_arc", LangOpts.ObjCAutoRefCount)
653 .Case("objc_arc_weak", LangOpts.ObjCARCWeak)
654 .Case("objc_default_synthesize_properties", LangOpts.ObjC2)
655 .Case("objc_fixed_enum", LangOpts.ObjC2)
656 .Case("objc_instancetype", LangOpts.ObjC2)
657 .Case("objc_modules", LangOpts.ObjC2 && LangOpts.Modules)
658 .Case("objc_nonfragile_abi", LangOpts.ObjCRuntime.isNonFragile())
659 .Case("objc_weak_class", LangOpts.ObjCRuntime.hasWeakClassImport())
660 .Case("ownership_holds", true)
661 .Case("ownership_returns", true)
662 .Case("ownership_takes", true)
663 .Case("objc_bool", true)
664 .Case("objc_subscripting", LangOpts.ObjCRuntime.isNonFragile())
665 .Case("objc_array_literals", LangOpts.ObjC2)
666 .Case("objc_dictionary_literals", LangOpts.ObjC2)
667 .Case("objc_boxed_expressions", LangOpts.ObjC2)
668 .Case("arc_cf_code_audited", true)
669 // C11 features
670 .Case("c_alignas", LangOpts.C11)
671 .Case("c_atomic", LangOpts.C11)
672 .Case("c_generic_selections", LangOpts.C11)
673 .Case("c_static_assert", LangOpts.C11)
674 // C++11 features
675 .Case("cxx_access_control_sfinae", LangOpts.CPlusPlus0x)
676 .Case("cxx_alias_templates", LangOpts.CPlusPlus0x)
677 .Case("cxx_alignas", LangOpts.CPlusPlus0x)
678 .Case("cxx_atomic", LangOpts.CPlusPlus0x)
679 .Case("cxx_attributes", LangOpts.CPlusPlus0x)
680 .Case("cxx_auto_type", LangOpts.CPlusPlus0x)
681 .Case("cxx_constexpr", LangOpts.CPlusPlus0x)
682 .Case("cxx_decltype", LangOpts.CPlusPlus0x)
683 .Case("cxx_decltype_incomplete_return_types", LangOpts.CPlusPlus0x)
684 .Case("cxx_default_function_template_args", LangOpts.CPlusPlus0x)
685 .Case("cxx_defaulted_functions", LangOpts.CPlusPlus0x)
686 .Case("cxx_delegating_constructors", LangOpts.CPlusPlus0x)
687 .Case("cxx_deleted_functions", LangOpts.CPlusPlus0x)
688 .Case("cxx_explicit_conversions", LangOpts.CPlusPlus0x)
689 .Case("cxx_generalized_initializers", LangOpts.CPlusPlus0x)
690 .Case("cxx_implicit_moves", LangOpts.CPlusPlus0x)
691 //.Case("cxx_inheriting_constructors", false)
692 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus0x)
693 .Case("cxx_lambdas", LangOpts.CPlusPlus0x)
694 .Case("cxx_local_type_template_args", LangOpts.CPlusPlus0x)
695 .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus0x)
696 .Case("cxx_noexcept", LangOpts.CPlusPlus0x)
697 .Case("cxx_nullptr", LangOpts.CPlusPlus0x)
698 .Case("cxx_override_control", LangOpts.CPlusPlus0x)
699 .Case("cxx_range_for", LangOpts.CPlusPlus0x)
700 .Case("cxx_raw_string_literals", LangOpts.CPlusPlus0x)
701 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus0x)
702 .Case("cxx_rvalue_references", LangOpts.CPlusPlus0x)
703 .Case("cxx_strong_enums", LangOpts.CPlusPlus0x)
704 .Case("cxx_static_assert", LangOpts.CPlusPlus0x)
705 .Case("cxx_trailing_return", LangOpts.CPlusPlus0x)
706 .Case("cxx_unicode_literals", LangOpts.CPlusPlus0x)
707 .Case("cxx_unrestricted_unions", LangOpts.CPlusPlus0x)
708 .Case("cxx_user_literals", LangOpts.CPlusPlus0x)
709 .Case("cxx_variadic_templates", LangOpts.CPlusPlus0x)
710 // Type traits
711 .Case("has_nothrow_assign", LangOpts.CPlusPlus)
712 .Case("has_nothrow_copy", LangOpts.CPlusPlus)
713 .Case("has_nothrow_constructor", LangOpts.CPlusPlus)
714 .Case("has_trivial_assign", LangOpts.CPlusPlus)
715 .Case("has_trivial_copy", LangOpts.CPlusPlus)
716 .Case("has_trivial_constructor", LangOpts.CPlusPlus)
717 .Case("has_trivial_destructor", LangOpts.CPlusPlus)
718 .Case("has_virtual_destructor", LangOpts.CPlusPlus)
719 .Case("is_abstract", LangOpts.CPlusPlus)
720 .Case("is_base_of", LangOpts.CPlusPlus)
721 .Case("is_class", LangOpts.CPlusPlus)
722 .Case("is_convertible_to", LangOpts.CPlusPlus)
723 // __is_empty is available only if the horrible
724 // "struct __is_empty" parsing hack hasn't been needed in this
725 // translation unit. If it has, __is_empty reverts to a normal
726 // identifier and __has_feature(is_empty) evaluates false.
727 .Case("is_empty", LangOpts.CPlusPlus)
728 .Case("is_enum", LangOpts.CPlusPlus)
729 .Case("is_final", LangOpts.CPlusPlus)
730 .Case("is_literal", LangOpts.CPlusPlus)
731 .Case("is_standard_layout", LangOpts.CPlusPlus)
732 .Case("is_pod", LangOpts.CPlusPlus)
733 .Case("is_polymorphic", LangOpts.CPlusPlus)
734 .Case("is_trivial", LangOpts.CPlusPlus)
735 .Case("is_trivially_assignable", LangOpts.CPlusPlus)
736 .Case("is_trivially_constructible", LangOpts.CPlusPlus)
737 .Case("is_trivially_copyable", LangOpts.CPlusPlus)
738 .Case("is_union", LangOpts.CPlusPlus)
739 .Case("modules", LangOpts.Modules)
740 .Case("tls", PP.getTargetInfo().isTLSSupported())
741 .Case("underlying_type", LangOpts.CPlusPlus)
742 .Default(false);
743}
744
745/// HasExtension - Return true if we recognize and implement the feature
746/// specified by the identifier, either as an extension or a standard language
747/// feature.
748static bool HasExtension(const Preprocessor &PP, const IdentifierInfo *II) {
749 if (HasFeature(PP, II))
750 return true;
751
752 // If the use of an extension results in an error diagnostic, extensions are
753 // effectively unavailable, so just return false here.
754 if (PP.getDiagnostics().getExtensionHandlingBehavior() ==
755 DiagnosticsEngine::Ext_Error)
756 return false;
757
758 const LangOptions &LangOpts = PP.getLangOpts();
759 StringRef Extension = II->getName();
760
761 // Normalize the extension name, __foo__ becomes foo.
762 if (Extension.startswith("__") && Extension.endswith("__") &&
763 Extension.size() >= 4)
764 Extension = Extension.substr(2, Extension.size() - 4);
765
766 // Because we inherit the feature list from HasFeature, this string switch
767 // must be less restrictive than HasFeature's.
768 return llvm::StringSwitch<bool>(Extension)
769 // C11 features supported by other languages as extensions.
770 .Case("c_alignas", true)
771 .Case("c_atomic", true)
772 .Case("c_generic_selections", true)
773 .Case("c_static_assert", true)
774 // C++0x features supported by other languages as extensions.
775 .Case("cxx_atomic", LangOpts.CPlusPlus)
776 .Case("cxx_deleted_functions", LangOpts.CPlusPlus)
777 .Case("cxx_explicit_conversions", LangOpts.CPlusPlus)
778 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus)
779 .Case("cxx_local_type_template_args", LangOpts.CPlusPlus)
780 .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus)
781 .Case("cxx_override_control", LangOpts.CPlusPlus)
782 .Case("cxx_range_for", LangOpts.CPlusPlus)
783 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus)
784 .Case("cxx_rvalue_references", LangOpts.CPlusPlus)
785 .Default(false);
786}
787
788/// HasAttribute - Return true if we recognize and implement the attribute
789/// specified by the given identifier.
790static bool HasAttribute(const IdentifierInfo *II) {
791 StringRef Name = II->getName();
792 // Normalize the attribute name, __foo__ becomes foo.
793 if (Name.startswith("__") && Name.endswith("__") && Name.size() >= 4)
794 Name = Name.substr(2, Name.size() - 4);
795
796 // FIXME: Do we need to handle namespaces here?
797 return llvm::StringSwitch<bool>(Name)
798#include "clang/Lex/AttrSpellings.inc"
799 .Default(false);
800}
801
802/// EvaluateHasIncludeCommon - Process a '__has_include("path")'
803/// or '__has_include_next("path")' expression.
804/// Returns true if successful.
805static bool EvaluateHasIncludeCommon(Token &Tok,
806 IdentifierInfo *II, Preprocessor &PP,
807 const DirectoryLookup *LookupFrom) {
808 SourceLocation LParenLoc;
809
810 // Get '('.
811 PP.LexNonComment(Tok);
812
813 // Ensure we have a '('.
814 if (Tok.isNot(tok::l_paren)) {
815 PP.Diag(Tok.getLocation(), diag::err_pp_missing_lparen) << II->getName();
816 return false;
817 }
818
819 // Save '(' location for possible missing ')' message.
820 LParenLoc = Tok.getLocation();
821
822 // Get the file name.
823 PP.getCurrentLexer()->LexIncludeFilename(Tok);
824
825 // Reserve a buffer to get the spelling.
826 SmallString<128> FilenameBuffer;
827 StringRef Filename;
828 SourceLocation EndLoc;
829
830 switch (Tok.getKind()) {
831 case tok::eod:
832 // If the token kind is EOD, the error has already been diagnosed.
833 return false;
834
835 case tok::angle_string_literal:
836 case tok::string_literal: {
837 bool Invalid = false;
838 Filename = PP.getSpelling(Tok, FilenameBuffer, &Invalid);
839 if (Invalid)
840 return false;
841 break;
842 }
843
844 case tok::less:
845 // This could be a <foo/bar.h> file coming from a macro expansion. In this
846 // case, glue the tokens together into FilenameBuffer and interpret those.
847 FilenameBuffer.push_back('<');
848 if (PP.ConcatenateIncludeName(FilenameBuffer, EndLoc))
849 return false; // Found <eod> but no ">"? Diagnostic already emitted.
850 Filename = FilenameBuffer.str();
851 break;
852 default:
853 PP.Diag(Tok.getLocation(), diag::err_pp_expects_filename);
854 return false;
855 }
856
857 // Get ')'.
858 PP.LexNonComment(Tok);
859
860 // Ensure we have a trailing ).
861 if (Tok.isNot(tok::r_paren)) {
862 PP.Diag(Tok.getLocation(), diag::err_pp_missing_rparen) << II->getName();
863 PP.Diag(LParenLoc, diag::note_matching) << "(";
864 return false;
865 }
866
867 bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename);
868 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
869 // error.
870 if (Filename.empty())
871 return false;
872
873 // Search include directories.
874 const DirectoryLookup *CurDir;
875 const FileEntry *File =
876 PP.LookupFile(Filename, isAngled, LookupFrom, CurDir, NULL, NULL, NULL);
877
878 // Get the result value. A result of true means the file exists.
879 return File != 0;
880}
881
882/// EvaluateHasInclude - Process a '__has_include("path")' expression.
883/// Returns true if successful.
884static bool EvaluateHasInclude(Token &Tok, IdentifierInfo *II,
885 Preprocessor &PP) {
886 return EvaluateHasIncludeCommon(Tok, II, PP, NULL);
887}
888
889/// EvaluateHasIncludeNext - Process '__has_include_next("path")' expression.
890/// Returns true if successful.
891static bool EvaluateHasIncludeNext(Token &Tok,
892 IdentifierInfo *II, Preprocessor &PP) {
893 // __has_include_next is like __has_include, except that we start
894 // searching after the current found directory. If we can't do this,
895 // issue a diagnostic.
896 const DirectoryLookup *Lookup = PP.GetCurDirLookup();
897 if (PP.isInPrimaryFile()) {
898 Lookup = 0;
899 PP.Diag(Tok, diag::pp_include_next_in_primary);
900 } else if (Lookup == 0) {
901 PP.Diag(Tok, diag::pp_include_next_absolute_path);
902 } else {
903 // Start looking up in the next directory.
904 ++Lookup;
905 }
906
907 return EvaluateHasIncludeCommon(Tok, II, PP, Lookup);
908}
909
910/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
911/// as a builtin macro, handle it and return the next token as 'Tok'.
912void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
913 // Figure out which token this is.
914 IdentifierInfo *II = Tok.getIdentifierInfo();
915 assert(II && "Can't be a macro without id info!");
916
917 // If this is an _Pragma or Microsoft __pragma directive, expand it,
918 // invoke the pragma handler, then lex the token after it.
919 if (II == Ident_Pragma)
920 return Handle_Pragma(Tok);
921 else if (II == Ident__pragma) // in non-MS mode this is null
922 return HandleMicrosoft__pragma(Tok);
923
924 ++NumBuiltinMacroExpanded;
925
926 SmallString<128> TmpBuffer;
927 llvm::raw_svector_ostream OS(TmpBuffer);
928
929 // Set up the return result.
930 Tok.setIdentifierInfo(0);
931 Tok.clearFlag(Token::NeedsCleaning);
932
933 if (II == Ident__LINE__) {
934 // C99 6.10.8: "__LINE__: The presumed line number (within the current
935 // source file) of the current source line (an integer constant)". This can
936 // be affected by #line.
937 SourceLocation Loc = Tok.getLocation();
938
939 // Advance to the location of the first _, this might not be the first byte
940 // of the token if it starts with an escaped newline.
941 Loc = AdvanceToTokenCharacter(Loc, 0);
942
943 // One wrinkle here is that GCC expands __LINE__ to location of the *end* of
944 // a macro expansion. This doesn't matter for object-like macros, but
945 // can matter for a function-like macro that expands to contain __LINE__.
946 // Skip down through expansion points until we find a file loc for the
947 // end of the expansion history.
948 Loc = SourceMgr.getExpansionRange(Loc).second;
949 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc);
950
951 // __LINE__ expands to a simple numeric value.
952 OS << (PLoc.isValid()? PLoc.getLine() : 1);
953 Tok.setKind(tok::numeric_constant);
954 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
955 // C99 6.10.8: "__FILE__: The presumed name of the current source file (a
956 // character string literal)". This can be affected by #line.
957 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
958
959 // __BASE_FILE__ is a GNU extension that returns the top of the presumed
960 // #include stack instead of the current file.
961 if (II == Ident__BASE_FILE__ && PLoc.isValid()) {
962 SourceLocation NextLoc = PLoc.getIncludeLoc();
963 while (NextLoc.isValid()) {
964 PLoc = SourceMgr.getPresumedLoc(NextLoc);
965 if (PLoc.isInvalid())
966 break;
967
968 NextLoc = PLoc.getIncludeLoc();
969 }
970 }
971
972 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
973 SmallString<128> FN;
974 if (PLoc.isValid()) {
975 FN += PLoc.getFilename();
976 Lexer::Stringify(FN);
977 OS << '"' << FN.str() << '"';
978 }
979 Tok.setKind(tok::string_literal);
980 } else if (II == Ident__DATE__) {
981 if (!DATELoc.isValid())
982 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
983 Tok.setKind(tok::string_literal);
984 Tok.setLength(strlen("\"Mmm dd yyyy\""));
985 Tok.setLocation(SourceMgr.createExpansionLoc(DATELoc, Tok.getLocation(),
986 Tok.getLocation(),
987 Tok.getLength()));
988 return;
989 } else if (II == Ident__TIME__) {
990 if (!TIMELoc.isValid())
991 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
992 Tok.setKind(tok::string_literal);
993 Tok.setLength(strlen("\"hh:mm:ss\""));
994 Tok.setLocation(SourceMgr.createExpansionLoc(TIMELoc, Tok.getLocation(),
995 Tok.getLocation(),
996 Tok.getLength()));
997 return;
998 } else if (II == Ident__INCLUDE_LEVEL__) {
999 // Compute the presumed include depth of this token. This can be affected
1000 // by GNU line markers.
1001 unsigned Depth = 0;
1002
1003 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
1004 if (PLoc.isValid()) {
1005 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
1006 for (; PLoc.isValid(); ++Depth)
1007 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
1008 }
1009
1010 // __INCLUDE_LEVEL__ expands to a simple numeric value.
1011 OS << Depth;
1012 Tok.setKind(tok::numeric_constant);
1013 } else if (II == Ident__TIMESTAMP__) {
1014 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
1015 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
1016
1017 // Get the file that we are lexing out of. If we're currently lexing from
1018 // a macro, dig into the include stack.
1019 const FileEntry *CurFile = 0;
1020 PreprocessorLexer *TheLexer = getCurrentFileLexer();
1021
1022 if (TheLexer)
1023 CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID());
1024
1025 const char *Result;
1026 if (CurFile) {
1027 time_t TT = CurFile->getModificationTime();
1028 struct tm *TM = localtime(&TT);
1029 Result = asctime(TM);
1030 } else {
1031 Result = "??? ??? ?? ??:??:?? ????\n";
1032 }
1033 // Surround the string with " and strip the trailing newline.
1034 OS << '"' << StringRef(Result, strlen(Result)-1) << '"';
1035 Tok.setKind(tok::string_literal);
1036 } else if (II == Ident__COUNTER__) {
1037 // __COUNTER__ expands to a simple numeric value.
1038 OS << CounterValue++;
1039 Tok.setKind(tok::numeric_constant);
1040 } else if (II == Ident__has_feature ||
1041 II == Ident__has_extension ||
1042 II == Ident__has_builtin ||
1043 II == Ident__has_attribute) {
1044 // The argument to these builtins should be a parenthesized identifier.
1045 SourceLocation StartLoc = Tok.getLocation();
1046
1047 bool IsValid = false;
1048 IdentifierInfo *FeatureII = 0;
1049
1050 // Read the '('.
1051 Lex(Tok);
1052 if (Tok.is(tok::l_paren)) {
1053 // Read the identifier
1054 Lex(Tok);
1055 if (Tok.is(tok::identifier) || Tok.is(tok::kw_const)) {
1056 FeatureII = Tok.getIdentifierInfo();
1057
1058 // Read the ')'.
1059 Lex(Tok);
1060 if (Tok.is(tok::r_paren))
1061 IsValid = true;
1062 }
1063 }
1064
1065 bool Value = false;
1066 if (!IsValid)
1067 Diag(StartLoc, diag::err_feature_check_malformed);
1068 else if (II == Ident__has_builtin) {
1069 // Check for a builtin is trivial.
1070 Value = FeatureII->getBuiltinID() != 0;
1071 } else if (II == Ident__has_attribute)
1072 Value = HasAttribute(FeatureII);
1073 else if (II == Ident__has_extension)
1074 Value = HasExtension(*this, FeatureII);
1075 else {
1076 assert(II == Ident__has_feature && "Must be feature check");
1077 Value = HasFeature(*this, FeatureII);
1078 }
1079
1080 OS << (int)Value;
1081 if (IsValid)
1082 Tok.setKind(tok::numeric_constant);
1083 } else if (II == Ident__has_include ||
1084 II == Ident__has_include_next) {
1085 // The argument to these two builtins should be a parenthesized
1086 // file name string literal using angle brackets (<>) or
1087 // double-quotes ("").
1088 bool Value;
1089 if (II == Ident__has_include)
1090 Value = EvaluateHasInclude(Tok, II, *this);
1091 else
1092 Value = EvaluateHasIncludeNext(Tok, II, *this);
1093 OS << (int)Value;
1094 Tok.setKind(tok::numeric_constant);
1095 } else if (II == Ident__has_warning) {
1096 // The argument should be a parenthesized string literal.
1097 // The argument to these builtins should be a parenthesized identifier.
1098 SourceLocation StartLoc = Tok.getLocation();
1099 bool IsValid = false;
1100 bool Value = false;
1101 // Read the '('.
1102 Lex(Tok);
1103 do {
1104 if (Tok.is(tok::l_paren)) {
1105 // Read the string.
1106 Lex(Tok);
1107
1108 // We need at least one string literal.
1109 if (!Tok.is(tok::string_literal)) {
1110 StartLoc = Tok.getLocation();
1111 IsValid = false;
1112 // Eat tokens until ')'.
1113 do Lex(Tok); while (!(Tok.is(tok::r_paren) || Tok.is(tok::eod)));
1114 break;
1115 }
1116
1117 // String concatenation allows multiple strings, which can even come
1118 // from macro expansion.
1119 SmallVector<Token, 4> StrToks;
1120 while (Tok.is(tok::string_literal)) {
1121 // Complain about, and drop, any ud-suffix.
1122 if (Tok.hasUDSuffix())
1123 Diag(Tok, diag::err_invalid_string_udl);
1124 StrToks.push_back(Tok);
1125 LexUnexpandedToken(Tok);
1126 }
1127
1128 // Is the end a ')'?
1129 if (!(IsValid = Tok.is(tok::r_paren)))
1130 break;
1131
1132 // Concatenate and parse the strings.
1133 StringLiteralParser Literal(&StrToks[0], StrToks.size(), *this);
1134 assert(Literal.isAscii() && "Didn't allow wide strings in");
1135 if (Literal.hadError)
1136 break;
1137 if (Literal.Pascal) {
1138 Diag(Tok, diag::warn_pragma_diagnostic_invalid);
1139 break;
1140 }
1141
1142 StringRef WarningName(Literal.GetString());
1143
1144 if (WarningName.size() < 3 || WarningName[0] != '-' ||
1145 WarningName[1] != 'W') {
1146 Diag(StrToks[0].getLocation(), diag::warn_has_warning_invalid_option);
1147 break;
1148 }
1149
1150 // Finally, check if the warning flags maps to a diagnostic group.
1151 // We construct a SmallVector here to talk to getDiagnosticIDs().
1152 // Although we don't use the result, this isn't a hot path, and not
1153 // worth special casing.
1154 llvm::SmallVector<diag::kind, 10> Diags;
1155 Value = !getDiagnostics().getDiagnosticIDs()->
1156 getDiagnosticsInGroup(WarningName.substr(2), Diags);
1157 }
1158 } while (false);
1159
1160 if (!IsValid)
1161 Diag(StartLoc, diag::err_warning_check_malformed);
1162
1163 OS << (int)Value;
1164 Tok.setKind(tok::numeric_constant);
1165 } else {
1166 llvm_unreachable("Unknown identifier!");
1167 }
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +00001168 CreateString(OS.str(), Tok, Tok.getLocation(), Tok.getLocation());
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001169}
1170
1171void Preprocessor::markMacroAsUsed(MacroInfo *MI) {
1172 // If the 'used' status changed, and the macro requires 'unused' warning,
1173 // remove its SourceLocation from the warn-for-unused-macro locations.
1174 if (MI->isWarnIfUnused() && !MI->isUsed())
1175 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
1176 MI->setIsUsed(true);
1177}