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