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