blob: bda31ed294a06801532c797639ab043dd2a19c17 [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"
Joao Matos3e1ec722012-08-31 21:34:27 +000017#include "clang/Basic/FileManager.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000018#include "clang/Basic/SourceManager.h"
Joao Matos3e1ec722012-08-31 21:34:27 +000019#include "clang/Basic/TargetInfo.h"
Joao Matos3e1ec722012-08-31 21:34:27 +000020#include "clang/Lex/CodeCompletionHandler.h"
21#include "clang/Lex/ExternalPreprocessorSource.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000022#include "clang/Lex/LexDiagnostic.h"
23#include "clang/Lex/MacroInfo.h"
24#include "llvm/ADT/STLExtras.h"
Andy Gibbs02a17682012-11-17 19:15:38 +000025#include "llvm/ADT/SmallString.h"
Joao Matos3e1ec722012-08-31 21:34:27 +000026#include "llvm/ADT/StringSwitch.h"
Joao Matos3e1ec722012-08-31 21:34:27 +000027#include "llvm/Config/llvm-config.h"
Joao Matos3e1ec722012-08-31 21:34:27 +000028#include "llvm/Support/ErrorHandling.h"
Dmitri Gribenko33d054b2012-09-24 20:56:28 +000029#include "llvm/Support/Format.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000030#include "llvm/Support/raw_ostream.h"
Joao Matos3e1ec722012-08-31 21:34:27 +000031#include <cstdio>
32#include <ctime>
33using namespace clang;
34
Dmitri Gribenkob3958472013-01-14 00:36:42 +000035MacroInfo *Preprocessor::getMacroInfoHistory(const IdentifierInfo *II) const {
Alexander Kornienko4d7e0ce2012-09-25 17:18:14 +000036 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);
Joao Matos3e1ec722012-08-31 21:34:27 +000039 assert(Pos != Macros.end() && "Identifier macro info is missing!");
Joao Matos3e1ec722012-08-31 21:34:27 +000040 return Pos->second;
41}
42
43/// setMacroInfo - Specify a macro for this identifier.
44///
Douglas Gregor6c6c54a2012-10-11 00:46:49 +000045void Preprocessor::setMacroInfo(IdentifierInfo *II, MacroInfo *MI) {
Joao Matos3e1ec722012-08-31 21:34:27 +000046 assert(MI && "MacroInfo should be non-zero!");
Douglas Gregor6c6c54a2012-10-11 00:46:49 +000047 assert(MI->getUndefLoc().isInvalid() &&
48 "Undefined macros cannot be registered");
49
50 MacroInfo *&StoredMI = Macros[II];
51 MI->setPreviousDefinition(StoredMI);
52 StoredMI = MI;
Alexander Kornienko4d7e0ce2012-09-25 17:18:14 +000053 II->setHasMacroDefinition(MI->getUndefLoc().isInvalid());
Douglas Gregor6c6c54a2012-10-11 00:46:49 +000054 if (II->isFromAST())
Joao Matos3e1ec722012-08-31 21:34:27 +000055 II->setChangedSinceDeserialization();
56}
57
Argyrios Kyrtzidisdc1088f2013-01-19 03:14:56 +000058void Preprocessor::addLoadedMacroInfo(IdentifierInfo *II, MacroInfo *MI,
59 MacroInfo *Hint) {
Douglas Gregor6c6c54a2012-10-11 00:46:49 +000060 assert(MI && "Missing macro?");
61 assert(MI->isFromAST() && "Macro is not from an AST?");
Argyrios Kyrtzidisdc1088f2013-01-19 03:14:56 +000062 assert(!MI->getPreviousDefinition() && "Macro already in chain?");
Douglas Gregor6c6c54a2012-10-11 00:46:49 +000063
64 MacroInfo *&StoredMI = Macros[II];
65
66 // Easy case: this is the first macro definition for this macro.
67 if (!StoredMI) {
68 StoredMI = MI;
69
70 if (MI->isDefined())
71 II->setHasMacroDefinition(true);
72 return;
73 }
74
75 // If this macro is a definition and this identifier has been neither
76 // defined nor undef'd in the current translation unit, add this macro
77 // to the end of the chain of definitions.
78 if (MI->isDefined() && StoredMI->isFromAST()) {
79 // Simple case: if this is the first actual definition, just put it at
80 // th beginning.
81 if (!StoredMI->isDefined()) {
Argyrios Kyrtzidisdc1088f2013-01-19 03:14:56 +000082 MI->setPreviousDefinition(StoredMI);
Douglas Gregor6c6c54a2012-10-11 00:46:49 +000083 StoredMI = MI;
84
85 II->setHasMacroDefinition(true);
86 return;
87 }
88
89 // Find the end of the definition chain.
Douglas Gregor54c8a402012-10-12 00:16:50 +000090 MacroInfo *Prev;
91 MacroInfo *PrevPrev = StoredMI;
Douglas Gregore8219a62012-10-11 21:07:39 +000092 bool Ambiguous = StoredMI->isAmbiguous();
93 bool MatchedOther = false;
Douglas Gregor6c6c54a2012-10-11 00:46:49 +000094 do {
Douglas Gregor54c8a402012-10-12 00:16:50 +000095 Prev = PrevPrev;
96
Douglas Gregor6c6c54a2012-10-11 00:46:49 +000097 // If the macros are not identical, we have an ambiguity.
Douglas Gregore8219a62012-10-11 21:07:39 +000098 if (!Prev->isIdenticalTo(*MI, *this)) {
99 if (!Ambiguous) {
100 Ambiguous = true;
101 StoredMI->setAmbiguous(true);
102 }
103 } else {
104 MatchedOther = true;
105 }
Douglas Gregor6c6c54a2012-10-11 00:46:49 +0000106 } while ((PrevPrev = Prev->getPreviousDefinition()) &&
107 PrevPrev->isDefined());
108
Douglas Gregore8219a62012-10-11 21:07:39 +0000109 // If there are ambiguous definitions, and we didn't match any other
110 // definition, then mark us as ambiguous.
111 if (Ambiguous && !MatchedOther)
112 MI->setAmbiguous(true);
Douglas Gregor7097be92012-10-11 00:48:48 +0000113
Douglas Gregor6c6c54a2012-10-11 00:46:49 +0000114 // Wire this macro information into the chain.
Argyrios Kyrtzidisdc1088f2013-01-19 03:14:56 +0000115 MI->setPreviousDefinition(Prev->getPreviousDefinition());
Douglas Gregor6c6c54a2012-10-11 00:46:49 +0000116 Prev->setPreviousDefinition(MI);
117 return;
118 }
119
120 // The macro is not a definition; put it at the end of the list.
Argyrios Kyrtzidisdc1088f2013-01-19 03:14:56 +0000121 MacroInfo *Prev = Hint? Hint : StoredMI;
122 while (Prev->getPreviousDefinition())
123 Prev = Prev->getPreviousDefinition();
124 Prev->setPreviousDefinition(MI);
Douglas Gregor6c6c54a2012-10-11 00:46:49 +0000125}
126
127void Preprocessor::makeLoadedMacroInfoVisible(IdentifierInfo *II,
128 MacroInfo *MI) {
129 assert(MI->isFromAST() && "Macro must be from the AST");
Douglas Gregor6c6c54a2012-10-11 00:46:49 +0000130
131 MacroInfo *&StoredMI = Macros[II];
132 if (StoredMI == MI) {
133 // Easy case: this is the first macro anyway.
Douglas Gregor54c8a402012-10-12 00:16:50 +0000134 II->setHasMacroDefinition(MI->isDefined());
Douglas Gregor6c6c54a2012-10-11 00:46:49 +0000135 return;
136 }
137
138 // Go find the macro and pull it out of the list.
Douglas Gregor54c8a402012-10-12 00:16:50 +0000139 // FIXME: Yes, this is O(N), and making a pile of macros visible or hidden
140 // would be quadratic, but it's extremely rare.
Douglas Gregor6c6c54a2012-10-11 00:46:49 +0000141 MacroInfo *Prev = StoredMI;
142 while (Prev->getPreviousDefinition() != MI)
143 Prev = Prev->getPreviousDefinition();
144 Prev->setPreviousDefinition(MI->getPreviousDefinition());
Douglas Gregor54c8a402012-10-12 00:16:50 +0000145 MI->setPreviousDefinition(0);
Douglas Gregor6c6c54a2012-10-11 00:46:49 +0000146
147 // Add the macro back to the list.
148 addLoadedMacroInfo(II, MI);
Douglas Gregor54c8a402012-10-12 00:16:50 +0000149
150 II->setHasMacroDefinition(StoredMI->isDefined());
151 if (II->isFromAST())
152 II->setChangedSinceDeserialization();
Douglas Gregor6c6c54a2012-10-11 00:46:49 +0000153}
154
Joao Matos3e1ec722012-08-31 21:34:27 +0000155/// \brief Undefine a macro for this identifier.
156void Preprocessor::clearMacroInfo(IdentifierInfo *II) {
157 assert(II->hasMacroDefinition() && "Macro is not defined!");
158 assert(Macros[II]->getUndefLoc().isValid() && "Macro is still defined!");
159 II->setHasMacroDefinition(false);
160 if (II->isFromAST())
161 II->setChangedSinceDeserialization();
162}
163
164/// RegisterBuiltinMacro - Register the specified identifier in the identifier
165/// table and mark it as a builtin macro to be expanded.
166static IdentifierInfo *RegisterBuiltinMacro(Preprocessor &PP, const char *Name){
167 // Get the identifier.
168 IdentifierInfo *Id = PP.getIdentifierInfo(Name);
169
170 // Mark it as being a macro that is builtin.
171 MacroInfo *MI = PP.AllocateMacroInfo(SourceLocation());
172 MI->setIsBuiltinMacro();
173 PP.setMacroInfo(Id, MI);
174 return Id;
175}
176
177
178/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
179/// identifier table.
180void Preprocessor::RegisterBuiltinMacros() {
181 Ident__LINE__ = RegisterBuiltinMacro(*this, "__LINE__");
182 Ident__FILE__ = RegisterBuiltinMacro(*this, "__FILE__");
183 Ident__DATE__ = RegisterBuiltinMacro(*this, "__DATE__");
184 Ident__TIME__ = RegisterBuiltinMacro(*this, "__TIME__");
185 Ident__COUNTER__ = RegisterBuiltinMacro(*this, "__COUNTER__");
186 Ident_Pragma = RegisterBuiltinMacro(*this, "_Pragma");
187
188 // GCC Extensions.
189 Ident__BASE_FILE__ = RegisterBuiltinMacro(*this, "__BASE_FILE__");
190 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro(*this, "__INCLUDE_LEVEL__");
191 Ident__TIMESTAMP__ = RegisterBuiltinMacro(*this, "__TIMESTAMP__");
192
193 // Clang Extensions.
194 Ident__has_feature = RegisterBuiltinMacro(*this, "__has_feature");
195 Ident__has_extension = RegisterBuiltinMacro(*this, "__has_extension");
196 Ident__has_builtin = RegisterBuiltinMacro(*this, "__has_builtin");
197 Ident__has_attribute = RegisterBuiltinMacro(*this, "__has_attribute");
198 Ident__has_include = RegisterBuiltinMacro(*this, "__has_include");
199 Ident__has_include_next = RegisterBuiltinMacro(*this, "__has_include_next");
200 Ident__has_warning = RegisterBuiltinMacro(*this, "__has_warning");
201
Douglas Gregorb09de512012-09-25 15:44:52 +0000202 // Modules.
203 if (LangOpts.Modules) {
204 Ident__building_module = RegisterBuiltinMacro(*this, "__building_module");
205
206 // __MODULE__
207 if (!LangOpts.CurrentModule.empty())
208 Ident__MODULE__ = RegisterBuiltinMacro(*this, "__MODULE__");
209 else
210 Ident__MODULE__ = 0;
211 } else {
212 Ident__building_module = 0;
213 Ident__MODULE__ = 0;
214 }
215
Joao Matos3e1ec722012-08-31 21:34:27 +0000216 // Microsoft Extensions.
217 if (LangOpts.MicrosoftExt)
218 Ident__pragma = RegisterBuiltinMacro(*this, "__pragma");
219 else
220 Ident__pragma = 0;
221}
222
223/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
224/// in its expansion, currently expands to that token literally.
225static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
226 const IdentifierInfo *MacroIdent,
227 Preprocessor &PP) {
228 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
229
230 // If the token isn't an identifier, it's always literally expanded.
231 if (II == 0) return true;
232
233 // If the information about this identifier is out of date, update it from
234 // the external source.
235 if (II->isOutOfDate())
236 PP.getExternalSource()->updateOutOfDateIdentifier(*II);
237
238 // If the identifier is a macro, and if that macro is enabled, it may be
239 // expanded so it's not a trivial expansion.
240 if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled() &&
241 // Fast expanding "#define X X" is ok, because X would be disabled.
242 II != MacroIdent)
243 return false;
244
245 // If this is an object-like macro invocation, it is safe to trivially expand
246 // it.
247 if (MI->isObjectLike()) return true;
248
249 // If this is a function-like macro invocation, it's safe to trivially expand
250 // as long as the identifier is not a macro argument.
251 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
252 I != E; ++I)
253 if (*I == II)
254 return false; // Identifier is a macro argument.
255
256 return true;
257}
258
259
260/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
261/// lexed is a '('. If so, consume the token and return true, if not, this
262/// method should have no observable side-effect on the lexed tokens.
263bool Preprocessor::isNextPPTokenLParen() {
264 // Do some quick tests for rejection cases.
265 unsigned Val;
266 if (CurLexer)
267 Val = CurLexer->isNextPPTokenLParen();
268 else if (CurPTHLexer)
269 Val = CurPTHLexer->isNextPPTokenLParen();
270 else
271 Val = CurTokenLexer->isNextTokenLParen();
272
273 if (Val == 2) {
274 // We have run off the end. If it's a source file we don't
275 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the
276 // macro stack.
277 if (CurPPLexer)
278 return false;
279 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
280 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
281 if (Entry.TheLexer)
282 Val = Entry.TheLexer->isNextPPTokenLParen();
283 else if (Entry.ThePTHLexer)
284 Val = Entry.ThePTHLexer->isNextPPTokenLParen();
285 else
286 Val = Entry.TheTokenLexer->isNextTokenLParen();
287
288 if (Val != 2)
289 break;
290
291 // Ran off the end of a source file?
292 if (Entry.ThePPLexer)
293 return false;
294 }
295 }
296
297 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
298 // have found something that isn't a '(' or we found the end of the
299 // translation unit. In either case, return false.
300 return Val == 1;
301}
302
303/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
304/// expanded as a macro, handle it and return the next token as 'Identifier'.
305bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
306 MacroInfo *MI) {
307 // If this is a macro expansion in the "#if !defined(x)" line for the file,
308 // then the macro could expand to different things in other contexts, we need
309 // to disable the optimization in this case.
310 if (CurPPLexer) CurPPLexer->MIOpt.ExpandedMacro();
311
312 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
313 if (MI->isBuiltinMacro()) {
314 if (Callbacks) Callbacks->MacroExpands(Identifier, MI,
315 Identifier.getLocation());
316 ExpandBuiltinMacro(Identifier);
317 return false;
318 }
319
320 /// Args - If this is a function-like macro expansion, this contains,
321 /// for each macro argument, the list of tokens that were provided to the
322 /// invocation.
323 MacroArgs *Args = 0;
324
325 // Remember where the end of the expansion occurred. For an object-like
326 // macro, this is the identifier. For a function-like macro, this is the ')'.
327 SourceLocation ExpansionEnd = Identifier.getLocation();
328
329 // If this is a function-like macro, read the arguments.
330 if (MI->isFunctionLike()) {
331 // C99 6.10.3p10: If the preprocessing token immediately after the macro
332 // name isn't a '(', this macro should not be expanded.
333 if (!isNextPPTokenLParen())
334 return true;
335
336 // Remember that we are now parsing the arguments to a macro invocation.
337 // Preprocessor directives used inside macro arguments are not portable, and
338 // this enables the warning.
339 InMacroArgs = true;
340 Args = ReadFunctionLikeMacroArgs(Identifier, MI, ExpansionEnd);
341
342 // Finished parsing args.
343 InMacroArgs = false;
344
345 // If there was an error parsing the arguments, bail out.
346 if (Args == 0) return false;
347
348 ++NumFnMacroExpanded;
349 } else {
350 ++NumMacroExpanded;
351 }
352
353 // Notice that this macro has been used.
354 markMacroAsUsed(MI);
355
356 // Remember where the token is expanded.
357 SourceLocation ExpandLoc = Identifier.getLocation();
358 SourceRange ExpansionRange(ExpandLoc, ExpansionEnd);
359
360 if (Callbacks) {
361 if (InMacroArgs) {
362 // We can have macro expansion inside a conditional directive while
363 // reading the function macro arguments. To ensure, in that case, that
364 // MacroExpands callbacks still happen in source order, queue this
365 // callback to have it happen after the function macro callback.
366 DelayedMacroExpandsCallbacks.push_back(
367 MacroExpandsInfo(Identifier, MI, ExpansionRange));
368 } else {
369 Callbacks->MacroExpands(Identifier, MI, ExpansionRange);
370 if (!DelayedMacroExpandsCallbacks.empty()) {
371 for (unsigned i=0, e = DelayedMacroExpandsCallbacks.size(); i!=e; ++i) {
372 MacroExpandsInfo &Info = DelayedMacroExpandsCallbacks[i];
373 Callbacks->MacroExpands(Info.Tok, Info.MI, Info.Range);
374 }
375 DelayedMacroExpandsCallbacks.clear();
376 }
377 }
378 }
Douglas Gregore8219a62012-10-11 21:07:39 +0000379
Argyrios Kyrtzidis0c06cbc2013-01-23 18:21:56 +0000380 // FIXME: Temporarily disable this warning that is currently bogus with a PCH
381 // that redefined a macro without undef'ing it first (test/PCH/macro-redef.c).
382#if 0
Douglas Gregore8219a62012-10-11 21:07:39 +0000383 // If the macro definition is ambiguous, complain.
384 if (MI->isAmbiguous()) {
385 Diag(Identifier, diag::warn_pp_ambiguous_macro)
386 << Identifier.getIdentifierInfo();
387 Diag(MI->getDefinitionLoc(), diag::note_pp_ambiguous_macro_chosen)
388 << Identifier.getIdentifierInfo();
389 for (MacroInfo *PrevMI = MI->getPreviousDefinition();
390 PrevMI && PrevMI->isDefined();
391 PrevMI = PrevMI->getPreviousDefinition()) {
392 if (PrevMI->isAmbiguous()) {
393 Diag(PrevMI->getDefinitionLoc(), diag::note_pp_ambiguous_macro_other)
394 << Identifier.getIdentifierInfo();
395 }
396 }
397 }
Argyrios Kyrtzidis0c06cbc2013-01-23 18:21:56 +0000398#endif
Douglas Gregore8219a62012-10-11 21:07:39 +0000399
Joao Matos3e1ec722012-08-31 21:34:27 +0000400 // If we started lexing a macro, enter the macro expansion body.
401
402 // If this macro expands to no tokens, don't bother to push it onto the
403 // expansion stack, only to take it right back off.
404 if (MI->getNumTokens() == 0) {
405 // No need for arg info.
406 if (Args) Args->destroy(*this);
407
408 // Ignore this macro use, just return the next token in the current
409 // buffer.
410 bool HadLeadingSpace = Identifier.hasLeadingSpace();
411 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
412
413 Lex(Identifier);
414
415 // If the identifier isn't on some OTHER line, inherit the leading
416 // whitespace/first-on-a-line property of this token. This handles
417 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
418 // empty.
419 if (!Identifier.isAtStartOfLine()) {
420 if (IsAtStartOfLine) Identifier.setFlag(Token::StartOfLine);
421 if (HadLeadingSpace) Identifier.setFlag(Token::LeadingSpace);
422 }
423 Identifier.setFlag(Token::LeadingEmptyMacro);
424 ++NumFastMacroExpanded;
425 return false;
426
427 } else if (MI->getNumTokens() == 1 &&
428 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
429 *this)) {
430 // Otherwise, if this macro expands into a single trivially-expanded
431 // token: expand it now. This handles common cases like
432 // "#define VAL 42".
433
434 // No need for arg info.
435 if (Args) Args->destroy(*this);
436
437 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
438 // identifier to the expanded token.
439 bool isAtStartOfLine = Identifier.isAtStartOfLine();
440 bool hasLeadingSpace = Identifier.hasLeadingSpace();
441
442 // Replace the result token.
443 Identifier = MI->getReplacementToken(0);
444
445 // Restore the StartOfLine/LeadingSpace markers.
446 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
447 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
448
449 // Update the tokens location to include both its expansion and physical
450 // locations.
451 SourceLocation Loc =
452 SourceMgr.createExpansionLoc(Identifier.getLocation(), ExpandLoc,
453 ExpansionEnd,Identifier.getLength());
454 Identifier.setLocation(Loc);
455
456 // If this is a disabled macro or #define X X, we must mark the result as
457 // unexpandable.
458 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo()) {
459 if (MacroInfo *NewMI = getMacroInfo(NewII))
460 if (!NewMI->isEnabled() || NewMI == MI) {
461 Identifier.setFlag(Token::DisableExpand);
Douglas Gregor40f56e52013-01-30 23:10:17 +0000462 // Don't warn for "#define X X" like "#define bool bool" from
463 // stdbool.h.
464 if (NewMI != MI || MI->isFunctionLike())
465 Diag(Identifier, diag::pp_disabled_macro_expansion);
Joao Matos3e1ec722012-08-31 21:34:27 +0000466 }
467 }
468
469 // Since this is not an identifier token, it can't be macro expanded, so
470 // we're done.
471 ++NumFastMacroExpanded;
472 return false;
473 }
474
475 // Start expanding the macro.
476 EnterMacro(Identifier, ExpansionEnd, MI, Args);
477
478 // Now that the macro is at the top of the include stack, ask the
479 // preprocessor to read the next token from it.
480 Lex(Identifier);
481 return false;
482}
483
484/// ReadFunctionLikeMacroArgs - After reading "MACRO" and knowing that the next
485/// token is the '(' of the macro, this method is invoked to read all of the
486/// actual arguments specified for the macro invocation. This returns null on
487/// error.
488MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
489 MacroInfo *MI,
490 SourceLocation &MacroEnd) {
491 // The number of fixed arguments to parse.
492 unsigned NumFixedArgsLeft = MI->getNumArgs();
493 bool isVariadic = MI->isVariadic();
494
495 // Outer loop, while there are more arguments, keep reading them.
496 Token Tok;
497
498 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
499 // an argument value in a macro could expand to ',' or '(' or ')'.
500 LexUnexpandedToken(Tok);
501 assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
502
503 // ArgTokens - Build up a list of tokens that make up each argument. Each
504 // argument is separated by an EOF token. Use a SmallVector so we can avoid
505 // heap allocations in the common case.
506 SmallVector<Token, 64> ArgTokens;
Argyrios Kyrtzidiscd0fd182012-12-21 01:17:20 +0000507 bool ContainsCodeCompletionTok = false;
Joao Matos3e1ec722012-08-31 21:34:27 +0000508
509 unsigned NumActuals = 0;
510 while (Tok.isNot(tok::r_paren)) {
Argyrios Kyrtzidiscd0fd182012-12-21 01:17:20 +0000511 if (ContainsCodeCompletionTok && (Tok.is(tok::eof) || Tok.is(tok::eod)))
512 break;
513
Joao Matos3e1ec722012-08-31 21:34:27 +0000514 assert((Tok.is(tok::l_paren) || Tok.is(tok::comma)) &&
515 "only expect argument separators here");
516
517 unsigned ArgTokenStart = ArgTokens.size();
518 SourceLocation ArgStartLoc = Tok.getLocation();
519
520 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
521 // that we already consumed the first one.
522 unsigned NumParens = 0;
523
524 while (1) {
525 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
526 // an argument value in a macro could expand to ',' or '(' or ')'.
527 LexUnexpandedToken(Tok);
528
529 if (Tok.is(tok::eof) || Tok.is(tok::eod)) { // "#if f(<eof>" & "#if f(\n"
Argyrios Kyrtzidiscd0fd182012-12-21 01:17:20 +0000530 if (!ContainsCodeCompletionTok) {
531 Diag(MacroName, diag::err_unterm_macro_invoc);
532 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
533 << MacroName.getIdentifierInfo();
534 // Do not lose the EOF/EOD. Return it to the client.
535 MacroName = Tok;
536 return 0;
537 } else {
Argyrios Kyrtzidisbb06b502012-12-22 04:48:10 +0000538 // Do not lose the EOF/EOD.
539 Token *Toks = new Token[1];
540 Toks[0] = Tok;
541 EnterTokenStream(Toks, 1, true, true);
Argyrios Kyrtzidiscd0fd182012-12-21 01:17:20 +0000542 break;
543 }
Joao Matos3e1ec722012-08-31 21:34:27 +0000544 } else if (Tok.is(tok::r_paren)) {
545 // If we found the ) token, the macro arg list is done.
546 if (NumParens-- == 0) {
547 MacroEnd = Tok.getLocation();
548 break;
549 }
550 } else if (Tok.is(tok::l_paren)) {
551 ++NumParens;
Nico Weber93dec512012-09-26 08:19:01 +0000552 } else if (Tok.is(tok::comma) && NumParens == 0) {
Joao Matos3e1ec722012-08-31 21:34:27 +0000553 // Comma ends this argument if there are more fixed arguments expected.
554 // However, if this is a variadic macro, and this is part of the
555 // variadic part, then the comma is just an argument token.
556 if (!isVariadic) break;
557 if (NumFixedArgsLeft > 1)
558 break;
559 } else if (Tok.is(tok::comment) && !KeepMacroComments) {
560 // If this is a comment token in the argument list and we're just in
561 // -C mode (not -CC mode), discard the comment.
562 continue;
563 } else if (Tok.getIdentifierInfo() != 0) {
564 // Reading macro arguments can cause macros that we are currently
565 // expanding from to be popped off the expansion stack. Doing so causes
566 // them to be reenabled for expansion. Here we record whether any
567 // identifiers we lex as macro arguments correspond to disabled macros.
568 // If so, we mark the token as noexpand. This is a subtle aspect of
569 // C99 6.10.3.4p2.
570 if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
571 if (!MI->isEnabled())
572 Tok.setFlag(Token::DisableExpand);
573 } else if (Tok.is(tok::code_completion)) {
Argyrios Kyrtzidiscd0fd182012-12-21 01:17:20 +0000574 ContainsCodeCompletionTok = true;
Joao Matos3e1ec722012-08-31 21:34:27 +0000575 if (CodeComplete)
576 CodeComplete->CodeCompleteMacroArgument(MacroName.getIdentifierInfo(),
577 MI, NumActuals);
578 // Don't mark that we reached the code-completion point because the
579 // parser is going to handle the token and there will be another
580 // code-completion callback.
581 }
582
583 ArgTokens.push_back(Tok);
584 }
585
586 // If this was an empty argument list foo(), don't add this as an empty
587 // argument.
588 if (ArgTokens.empty() && Tok.getKind() == tok::r_paren)
589 break;
590
591 // If this is not a variadic macro, and too many args were specified, emit
592 // an error.
593 if (!isVariadic && NumFixedArgsLeft == 0) {
594 if (ArgTokens.size() != ArgTokenStart)
595 ArgStartLoc = ArgTokens[ArgTokenStart].getLocation();
596
Argyrios Kyrtzidiscd0fd182012-12-21 01:17:20 +0000597 if (!ContainsCodeCompletionTok) {
598 // Emit the diagnostic at the macro name in case there is a missing ).
599 // Emitting it at the , could be far away from the macro name.
600 Diag(ArgStartLoc, diag::err_too_many_args_in_macro_invoc);
601 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
602 << MacroName.getIdentifierInfo();
603 return 0;
604 }
Joao Matos3e1ec722012-08-31 21:34:27 +0000605 }
606
607 // Empty arguments are standard in C99 and C++0x, and are supported as an extension in
608 // other modes.
609 if (ArgTokens.size() == ArgTokenStart && !LangOpts.C99)
Richard Smith80ad52f2013-01-02 11:42:31 +0000610 Diag(Tok, LangOpts.CPlusPlus11 ?
Joao Matos3e1ec722012-08-31 21:34:27 +0000611 diag::warn_cxx98_compat_empty_fnmacro_arg :
612 diag::ext_empty_fnmacro_arg);
613
614 // Add a marker EOF token to the end of the token list for this argument.
615 Token EOFTok;
616 EOFTok.startToken();
617 EOFTok.setKind(tok::eof);
618 EOFTok.setLocation(Tok.getLocation());
619 EOFTok.setLength(0);
620 ArgTokens.push_back(EOFTok);
621 ++NumActuals;
622 assert(NumFixedArgsLeft != 0 && "Too many arguments parsed");
623 --NumFixedArgsLeft;
624 }
625
626 // Okay, we either found the r_paren. Check to see if we parsed too few
627 // arguments.
628 unsigned MinArgsExpected = MI->getNumArgs();
629
630 // See MacroArgs instance var for description of this.
631 bool isVarargsElided = false;
632
Argyrios Kyrtzidisf1e5b152012-12-21 01:51:12 +0000633 if (ContainsCodeCompletionTok) {
634 // Recover from not-fully-formed macro invocation during code-completion.
635 Token EOFTok;
636 EOFTok.startToken();
637 EOFTok.setKind(tok::eof);
638 EOFTok.setLocation(Tok.getLocation());
639 EOFTok.setLength(0);
640 for (; NumActuals < MinArgsExpected; ++NumActuals)
641 ArgTokens.push_back(EOFTok);
642 }
643
Joao Matos3e1ec722012-08-31 21:34:27 +0000644 if (NumActuals < MinArgsExpected) {
645 // There are several cases where too few arguments is ok, handle them now.
646 if (NumActuals == 0 && MinArgsExpected == 1) {
647 // #define A(X) or #define A(...) ---> A()
648
649 // If there is exactly one argument, and that argument is missing,
650 // then we have an empty "()" argument empty list. This is fine, even if
651 // the macro expects one argument (the argument is just empty).
652 isVarargsElided = MI->isVariadic();
653 } else if (MI->isVariadic() &&
654 (NumActuals+1 == MinArgsExpected || // A(x, ...) -> A(X)
655 (NumActuals == 0 && MinArgsExpected == 2))) {// A(x,...) -> A()
656 // Varargs where the named vararg parameter is missing: OK as extension.
657 // #define A(x, ...)
658 // A("blah")
Eli Friedman4fa4b482012-11-14 02:18:46 +0000659 //
660 // If the macro contains the comma pasting extension, the diagnostic
661 // is suppressed; we know we'll get another diagnostic later.
662 if (!MI->hasCommaPasting()) {
663 Diag(Tok, diag::ext_missing_varargs_arg);
664 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
665 << MacroName.getIdentifierInfo();
666 }
Joao Matos3e1ec722012-08-31 21:34:27 +0000667
668 // Remember this occurred, allowing us to elide the comma when used for
669 // cases like:
670 // #define A(x, foo...) blah(a, ## foo)
671 // #define B(x, ...) blah(a, ## __VA_ARGS__)
672 // #define C(...) blah(a, ## __VA_ARGS__)
673 // A(x) B(x) C()
674 isVarargsElided = true;
Argyrios Kyrtzidiscd0fd182012-12-21 01:17:20 +0000675 } else if (!ContainsCodeCompletionTok) {
Joao Matos3e1ec722012-08-31 21:34:27 +0000676 // Otherwise, emit the error.
677 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
Argyrios Kyrtzidis0ee8de72012-12-14 18:53:47 +0000678 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
679 << MacroName.getIdentifierInfo();
Joao Matos3e1ec722012-08-31 21:34:27 +0000680 return 0;
681 }
682
683 // Add a marker EOF token to the end of the token list for this argument.
684 SourceLocation EndLoc = Tok.getLocation();
685 Tok.startToken();
686 Tok.setKind(tok::eof);
687 Tok.setLocation(EndLoc);
688 Tok.setLength(0);
689 ArgTokens.push_back(Tok);
690
691 // If we expect two arguments, add both as empty.
692 if (NumActuals == 0 && MinArgsExpected == 2)
693 ArgTokens.push_back(Tok);
694
Argyrios Kyrtzidiscd0fd182012-12-21 01:17:20 +0000695 } else if (NumActuals > MinArgsExpected && !MI->isVariadic() &&
696 !ContainsCodeCompletionTok) {
Joao Matos3e1ec722012-08-31 21:34:27 +0000697 // Emit the diagnostic at the macro name in case there is a missing ).
698 // Emitting it at the , could be far away from the macro name.
699 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
Argyrios Kyrtzidis0ee8de72012-12-14 18:53:47 +0000700 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
701 << MacroName.getIdentifierInfo();
Joao Matos3e1ec722012-08-31 21:34:27 +0000702 return 0;
703 }
704
705 return MacroArgs::create(MI, ArgTokens, isVarargsElided, *this);
706}
707
708/// \brief Keeps macro expanded tokens for TokenLexers.
709//
710/// Works like a stack; a TokenLexer adds the macro expanded tokens that is
711/// going to lex in the cache and when it finishes the tokens are removed
712/// from the end of the cache.
713Token *Preprocessor::cacheMacroExpandedTokens(TokenLexer *tokLexer,
714 ArrayRef<Token> tokens) {
715 assert(tokLexer);
716 if (tokens.empty())
717 return 0;
718
719 size_t newIndex = MacroExpandedTokens.size();
720 bool cacheNeedsToGrow = tokens.size() >
721 MacroExpandedTokens.capacity()-MacroExpandedTokens.size();
722 MacroExpandedTokens.append(tokens.begin(), tokens.end());
723
724 if (cacheNeedsToGrow) {
725 // Go through all the TokenLexers whose 'Tokens' pointer points in the
726 // buffer and update the pointers to the (potential) new buffer array.
727 for (unsigned i = 0, e = MacroExpandingLexersStack.size(); i != e; ++i) {
728 TokenLexer *prevLexer;
729 size_t tokIndex;
730 llvm::tie(prevLexer, tokIndex) = MacroExpandingLexersStack[i];
731 prevLexer->Tokens = MacroExpandedTokens.data() + tokIndex;
732 }
733 }
734
735 MacroExpandingLexersStack.push_back(std::make_pair(tokLexer, newIndex));
736 return MacroExpandedTokens.data() + newIndex;
737}
738
739void Preprocessor::removeCachedMacroExpandedTokensOfLastLexer() {
740 assert(!MacroExpandingLexersStack.empty());
741 size_t tokIndex = MacroExpandingLexersStack.back().second;
742 assert(tokIndex < MacroExpandedTokens.size());
743 // Pop the cached macro expanded tokens from the end.
744 MacroExpandedTokens.resize(tokIndex);
745 MacroExpandingLexersStack.pop_back();
746}
747
748/// ComputeDATE_TIME - Compute the current time, enter it into the specified
749/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
750/// the identifier tokens inserted.
751static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
752 Preprocessor &PP) {
753 time_t TT = time(0);
754 struct tm *TM = localtime(&TT);
755
756 static const char * const Months[] = {
757 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
758 };
759
Dmitri Gribenko33d054b2012-09-24 20:56:28 +0000760 {
761 SmallString<32> TmpBuffer;
762 llvm::raw_svector_ostream TmpStream(TmpBuffer);
763 TmpStream << llvm::format("\"%s %2d %4d\"", Months[TM->tm_mon],
764 TM->tm_mday, TM->tm_year + 1900);
Dmitri Gribenko33d054b2012-09-24 20:56:28 +0000765 Token TmpTok;
766 TmpTok.startToken();
Dmitri Gribenko374b3832012-09-24 21:07:17 +0000767 PP.CreateString(TmpStream.str(), TmpTok);
Dmitri Gribenko33d054b2012-09-24 20:56:28 +0000768 DATELoc = TmpTok.getLocation();
769 }
Joao Matos3e1ec722012-08-31 21:34:27 +0000770
Dmitri Gribenko33d054b2012-09-24 20:56:28 +0000771 {
772 SmallString<32> TmpBuffer;
773 llvm::raw_svector_ostream TmpStream(TmpBuffer);
774 TmpStream << llvm::format("\"%02d:%02d:%02d\"",
775 TM->tm_hour, TM->tm_min, TM->tm_sec);
Dmitri Gribenko33d054b2012-09-24 20:56:28 +0000776 Token TmpTok;
777 TmpTok.startToken();
Dmitri Gribenko374b3832012-09-24 21:07:17 +0000778 PP.CreateString(TmpStream.str(), TmpTok);
Dmitri Gribenko33d054b2012-09-24 20:56:28 +0000779 TIMELoc = TmpTok.getLocation();
780 }
Joao Matos3e1ec722012-08-31 21:34:27 +0000781}
782
783
784/// HasFeature - Return true if we recognize and implement the feature
785/// specified by the identifier as a standard language feature.
786static bool HasFeature(const Preprocessor &PP, const IdentifierInfo *II) {
787 const LangOptions &LangOpts = PP.getLangOpts();
788 StringRef Feature = II->getName();
789
790 // Normalize the feature name, __foo__ becomes foo.
791 if (Feature.startswith("__") && Feature.endswith("__") && Feature.size() >= 4)
792 Feature = Feature.substr(2, Feature.size() - 4);
793
794 return llvm::StringSwitch<bool>(Feature)
Will Dietz4f45bc02013-01-18 11:30:38 +0000795 .Case("address_sanitizer", LangOpts.Sanitize.Address)
Joao Matos3e1ec722012-08-31 21:34:27 +0000796 .Case("attribute_analyzer_noreturn", true)
797 .Case("attribute_availability", true)
798 .Case("attribute_availability_with_message", true)
799 .Case("attribute_cf_returns_not_retained", true)
800 .Case("attribute_cf_returns_retained", true)
801 .Case("attribute_deprecated_with_message", true)
802 .Case("attribute_ext_vector_type", true)
803 .Case("attribute_ns_returns_not_retained", true)
804 .Case("attribute_ns_returns_retained", true)
805 .Case("attribute_ns_consumes_self", true)
806 .Case("attribute_ns_consumed", true)
807 .Case("attribute_cf_consumed", true)
808 .Case("attribute_objc_ivar_unused", true)
809 .Case("attribute_objc_method_family", true)
810 .Case("attribute_overloadable", true)
811 .Case("attribute_unavailable_with_message", true)
812 .Case("attribute_unused_on_fields", true)
813 .Case("blocks", LangOpts.Blocks)
814 .Case("cxx_exceptions", LangOpts.Exceptions)
815 .Case("cxx_rtti", LangOpts.RTTI)
816 .Case("enumerator_attributes", true)
Will Dietz4f45bc02013-01-18 11:30:38 +0000817 .Case("memory_sanitizer", LangOpts.Sanitize.Memory)
818 .Case("thread_sanitizer", LangOpts.Sanitize.Thread)
Joao Matos3e1ec722012-08-31 21:34:27 +0000819 // Objective-C features
820 .Case("objc_arr", LangOpts.ObjCAutoRefCount) // FIXME: REMOVE?
821 .Case("objc_arc", LangOpts.ObjCAutoRefCount)
822 .Case("objc_arc_weak", LangOpts.ObjCARCWeak)
823 .Case("objc_default_synthesize_properties", LangOpts.ObjC2)
824 .Case("objc_fixed_enum", LangOpts.ObjC2)
825 .Case("objc_instancetype", LangOpts.ObjC2)
826 .Case("objc_modules", LangOpts.ObjC2 && LangOpts.Modules)
827 .Case("objc_nonfragile_abi", LangOpts.ObjCRuntime.isNonFragile())
Ted Kremeneke4057c22013-01-04 19:04:44 +0000828 .Case("objc_property_explicit_atomic", true) // Does clang support explicit "atomic" keyword?
Joao Matos3e1ec722012-08-31 21:34:27 +0000829 .Case("objc_weak_class", LangOpts.ObjCRuntime.hasWeakClassImport())
830 .Case("ownership_holds", true)
831 .Case("ownership_returns", true)
832 .Case("ownership_takes", true)
833 .Case("objc_bool", true)
834 .Case("objc_subscripting", LangOpts.ObjCRuntime.isNonFragile())
835 .Case("objc_array_literals", LangOpts.ObjC2)
836 .Case("objc_dictionary_literals", LangOpts.ObjC2)
837 .Case("objc_boxed_expressions", LangOpts.ObjC2)
838 .Case("arc_cf_code_audited", true)
839 // C11 features
840 .Case("c_alignas", LangOpts.C11)
841 .Case("c_atomic", LangOpts.C11)
842 .Case("c_generic_selections", LangOpts.C11)
843 .Case("c_static_assert", LangOpts.C11)
844 // C++11 features
Richard Smith80ad52f2013-01-02 11:42:31 +0000845 .Case("cxx_access_control_sfinae", LangOpts.CPlusPlus11)
846 .Case("cxx_alias_templates", LangOpts.CPlusPlus11)
847 .Case("cxx_alignas", LangOpts.CPlusPlus11)
848 .Case("cxx_atomic", LangOpts.CPlusPlus11)
849 .Case("cxx_attributes", LangOpts.CPlusPlus11)
850 .Case("cxx_auto_type", LangOpts.CPlusPlus11)
851 .Case("cxx_constexpr", LangOpts.CPlusPlus11)
852 .Case("cxx_decltype", LangOpts.CPlusPlus11)
853 .Case("cxx_decltype_incomplete_return_types", LangOpts.CPlusPlus11)
854 .Case("cxx_default_function_template_args", LangOpts.CPlusPlus11)
855 .Case("cxx_defaulted_functions", LangOpts.CPlusPlus11)
856 .Case("cxx_delegating_constructors", LangOpts.CPlusPlus11)
857 .Case("cxx_deleted_functions", LangOpts.CPlusPlus11)
858 .Case("cxx_explicit_conversions", LangOpts.CPlusPlus11)
859 .Case("cxx_generalized_initializers", LangOpts.CPlusPlus11)
860 .Case("cxx_implicit_moves", LangOpts.CPlusPlus11)
Joao Matos3e1ec722012-08-31 21:34:27 +0000861 //.Case("cxx_inheriting_constructors", false)
Richard Smith80ad52f2013-01-02 11:42:31 +0000862 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus11)
863 .Case("cxx_lambdas", LangOpts.CPlusPlus11)
864 .Case("cxx_local_type_template_args", LangOpts.CPlusPlus11)
865 .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus11)
866 .Case("cxx_noexcept", LangOpts.CPlusPlus11)
867 .Case("cxx_nullptr", LangOpts.CPlusPlus11)
868 .Case("cxx_override_control", LangOpts.CPlusPlus11)
869 .Case("cxx_range_for", LangOpts.CPlusPlus11)
870 .Case("cxx_raw_string_literals", LangOpts.CPlusPlus11)
871 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus11)
872 .Case("cxx_rvalue_references", LangOpts.CPlusPlus11)
873 .Case("cxx_strong_enums", LangOpts.CPlusPlus11)
874 .Case("cxx_static_assert", LangOpts.CPlusPlus11)
875 .Case("cxx_trailing_return", LangOpts.CPlusPlus11)
876 .Case("cxx_unicode_literals", LangOpts.CPlusPlus11)
877 .Case("cxx_unrestricted_unions", LangOpts.CPlusPlus11)
878 .Case("cxx_user_literals", LangOpts.CPlusPlus11)
879 .Case("cxx_variadic_templates", LangOpts.CPlusPlus11)
Joao Matos3e1ec722012-08-31 21:34:27 +0000880 // Type traits
881 .Case("has_nothrow_assign", LangOpts.CPlusPlus)
882 .Case("has_nothrow_copy", LangOpts.CPlusPlus)
883 .Case("has_nothrow_constructor", LangOpts.CPlusPlus)
884 .Case("has_trivial_assign", LangOpts.CPlusPlus)
885 .Case("has_trivial_copy", LangOpts.CPlusPlus)
886 .Case("has_trivial_constructor", LangOpts.CPlusPlus)
887 .Case("has_trivial_destructor", LangOpts.CPlusPlus)
888 .Case("has_virtual_destructor", LangOpts.CPlusPlus)
889 .Case("is_abstract", LangOpts.CPlusPlus)
890 .Case("is_base_of", LangOpts.CPlusPlus)
891 .Case("is_class", LangOpts.CPlusPlus)
892 .Case("is_convertible_to", LangOpts.CPlusPlus)
Joao Matos3e1ec722012-08-31 21:34:27 +0000893 .Case("is_empty", LangOpts.CPlusPlus)
894 .Case("is_enum", LangOpts.CPlusPlus)
895 .Case("is_final", LangOpts.CPlusPlus)
896 .Case("is_literal", LangOpts.CPlusPlus)
897 .Case("is_standard_layout", LangOpts.CPlusPlus)
898 .Case("is_pod", LangOpts.CPlusPlus)
899 .Case("is_polymorphic", LangOpts.CPlusPlus)
900 .Case("is_trivial", LangOpts.CPlusPlus)
901 .Case("is_trivially_assignable", LangOpts.CPlusPlus)
902 .Case("is_trivially_constructible", LangOpts.CPlusPlus)
903 .Case("is_trivially_copyable", LangOpts.CPlusPlus)
904 .Case("is_union", LangOpts.CPlusPlus)
905 .Case("modules", LangOpts.Modules)
906 .Case("tls", PP.getTargetInfo().isTLSSupported())
907 .Case("underlying_type", LangOpts.CPlusPlus)
908 .Default(false);
909}
910
911/// HasExtension - Return true if we recognize and implement the feature
912/// specified by the identifier, either as an extension or a standard language
913/// feature.
914static bool HasExtension(const Preprocessor &PP, const IdentifierInfo *II) {
915 if (HasFeature(PP, II))
916 return true;
917
918 // If the use of an extension results in an error diagnostic, extensions are
919 // effectively unavailable, so just return false here.
920 if (PP.getDiagnostics().getExtensionHandlingBehavior() ==
921 DiagnosticsEngine::Ext_Error)
922 return false;
923
924 const LangOptions &LangOpts = PP.getLangOpts();
925 StringRef Extension = II->getName();
926
927 // Normalize the extension name, __foo__ becomes foo.
928 if (Extension.startswith("__") && Extension.endswith("__") &&
929 Extension.size() >= 4)
930 Extension = Extension.substr(2, Extension.size() - 4);
931
932 // Because we inherit the feature list from HasFeature, this string switch
933 // must be less restrictive than HasFeature's.
934 return llvm::StringSwitch<bool>(Extension)
935 // C11 features supported by other languages as extensions.
936 .Case("c_alignas", true)
937 .Case("c_atomic", true)
938 .Case("c_generic_selections", true)
939 .Case("c_static_assert", true)
940 // C++0x features supported by other languages as extensions.
941 .Case("cxx_atomic", LangOpts.CPlusPlus)
942 .Case("cxx_deleted_functions", LangOpts.CPlusPlus)
943 .Case("cxx_explicit_conversions", LangOpts.CPlusPlus)
944 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus)
945 .Case("cxx_local_type_template_args", LangOpts.CPlusPlus)
946 .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus)
947 .Case("cxx_override_control", LangOpts.CPlusPlus)
948 .Case("cxx_range_for", LangOpts.CPlusPlus)
949 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus)
950 .Case("cxx_rvalue_references", LangOpts.CPlusPlus)
951 .Default(false);
952}
953
954/// HasAttribute - Return true if we recognize and implement the attribute
955/// specified by the given identifier.
956static bool HasAttribute(const IdentifierInfo *II) {
957 StringRef Name = II->getName();
958 // Normalize the attribute name, __foo__ becomes foo.
959 if (Name.startswith("__") && Name.endswith("__") && Name.size() >= 4)
960 Name = Name.substr(2, Name.size() - 4);
961
962 // FIXME: Do we need to handle namespaces here?
963 return llvm::StringSwitch<bool>(Name)
964#include "clang/Lex/AttrSpellings.inc"
965 .Default(false);
966}
967
968/// EvaluateHasIncludeCommon - Process a '__has_include("path")'
969/// or '__has_include_next("path")' expression.
970/// Returns true if successful.
971static bool EvaluateHasIncludeCommon(Token &Tok,
972 IdentifierInfo *II, Preprocessor &PP,
973 const DirectoryLookup *LookupFrom) {
Richard Trieu97bc3d52012-10-22 20:28:48 +0000974 // Save the location of the current token. If a '(' is later found, use
Aaron Ballman6b716c52013-01-15 21:59:46 +0000975 // that location. If not, use the end of this location instead.
Richard Trieu97bc3d52012-10-22 20:28:48 +0000976 SourceLocation LParenLoc = Tok.getLocation();
Joao Matos3e1ec722012-08-31 21:34:27 +0000977
Aaron Ballman31672b12013-01-16 19:32:21 +0000978 // These expressions are only allowed within a preprocessor directive.
979 if (!PP.isParsingIfOrElifDirective()) {
980 PP.Diag(LParenLoc, diag::err_pp_directive_required) << II->getName();
981 return false;
982 }
983
Joao Matos3e1ec722012-08-31 21:34:27 +0000984 // Get '('.
985 PP.LexNonComment(Tok);
986
987 // Ensure we have a '('.
988 if (Tok.isNot(tok::l_paren)) {
Richard Trieu97bc3d52012-10-22 20:28:48 +0000989 // No '(', use end of last token.
990 LParenLoc = PP.getLocForEndOfToken(LParenLoc);
991 PP.Diag(LParenLoc, diag::err_pp_missing_lparen) << II->getName();
992 // If the next token looks like a filename or the start of one,
993 // assume it is and process it as such.
994 if (!Tok.is(tok::angle_string_literal) && !Tok.is(tok::string_literal) &&
995 !Tok.is(tok::less))
996 return false;
997 } else {
998 // Save '(' location for possible missing ')' message.
999 LParenLoc = Tok.getLocation();
1000
Eli Friedmana0f2d022013-01-09 02:20:00 +00001001 if (PP.getCurrentLexer()) {
1002 // Get the file name.
1003 PP.getCurrentLexer()->LexIncludeFilename(Tok);
1004 } else {
1005 // We're in a macro, so we can't use LexIncludeFilename; just
1006 // grab the next token.
1007 PP.Lex(Tok);
1008 }
Joao Matos3e1ec722012-08-31 21:34:27 +00001009 }
1010
Joao Matos3e1ec722012-08-31 21:34:27 +00001011 // Reserve a buffer to get the spelling.
1012 SmallString<128> FilenameBuffer;
1013 StringRef Filename;
1014 SourceLocation EndLoc;
1015
1016 switch (Tok.getKind()) {
1017 case tok::eod:
1018 // If the token kind is EOD, the error has already been diagnosed.
1019 return false;
1020
1021 case tok::angle_string_literal:
1022 case tok::string_literal: {
1023 bool Invalid = false;
1024 Filename = PP.getSpelling(Tok, FilenameBuffer, &Invalid);
1025 if (Invalid)
1026 return false;
1027 break;
1028 }
1029
1030 case tok::less:
1031 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1032 // case, glue the tokens together into FilenameBuffer and interpret those.
1033 FilenameBuffer.push_back('<');
Richard Trieu97bc3d52012-10-22 20:28:48 +00001034 if (PP.ConcatenateIncludeName(FilenameBuffer, EndLoc)) {
1035 // Let the caller know a <eod> was found by changing the Token kind.
1036 Tok.setKind(tok::eod);
Joao Matos3e1ec722012-08-31 21:34:27 +00001037 return false; // Found <eod> but no ">"? Diagnostic already emitted.
Richard Trieu97bc3d52012-10-22 20:28:48 +00001038 }
Joao Matos3e1ec722012-08-31 21:34:27 +00001039 Filename = FilenameBuffer.str();
1040 break;
1041 default:
1042 PP.Diag(Tok.getLocation(), diag::err_pp_expects_filename);
1043 return false;
1044 }
1045
Richard Trieu97bc3d52012-10-22 20:28:48 +00001046 SourceLocation FilenameLoc = Tok.getLocation();
1047
Joao Matos3e1ec722012-08-31 21:34:27 +00001048 // Get ')'.
1049 PP.LexNonComment(Tok);
1050
1051 // Ensure we have a trailing ).
1052 if (Tok.isNot(tok::r_paren)) {
Richard Trieu97bc3d52012-10-22 20:28:48 +00001053 PP.Diag(PP.getLocForEndOfToken(FilenameLoc), diag::err_pp_missing_rparen)
1054 << II->getName();
Joao Matos3e1ec722012-08-31 21:34:27 +00001055 PP.Diag(LParenLoc, diag::note_matching) << "(";
1056 return false;
1057 }
1058
1059 bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename);
1060 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1061 // error.
1062 if (Filename.empty())
1063 return false;
1064
1065 // Search include directories.
1066 const DirectoryLookup *CurDir;
1067 const FileEntry *File =
1068 PP.LookupFile(Filename, isAngled, LookupFrom, CurDir, NULL, NULL, NULL);
1069
1070 // Get the result value. A result of true means the file exists.
1071 return File != 0;
1072}
1073
1074/// EvaluateHasInclude - Process a '__has_include("path")' expression.
1075/// Returns true if successful.
1076static bool EvaluateHasInclude(Token &Tok, IdentifierInfo *II,
1077 Preprocessor &PP) {
1078 return EvaluateHasIncludeCommon(Tok, II, PP, NULL);
1079}
1080
1081/// EvaluateHasIncludeNext - Process '__has_include_next("path")' expression.
1082/// Returns true if successful.
1083static bool EvaluateHasIncludeNext(Token &Tok,
1084 IdentifierInfo *II, Preprocessor &PP) {
1085 // __has_include_next is like __has_include, except that we start
1086 // searching after the current found directory. If we can't do this,
1087 // issue a diagnostic.
1088 const DirectoryLookup *Lookup = PP.GetCurDirLookup();
1089 if (PP.isInPrimaryFile()) {
1090 Lookup = 0;
1091 PP.Diag(Tok, diag::pp_include_next_in_primary);
1092 } else if (Lookup == 0) {
1093 PP.Diag(Tok, diag::pp_include_next_absolute_path);
1094 } else {
1095 // Start looking up in the next directory.
1096 ++Lookup;
1097 }
1098
1099 return EvaluateHasIncludeCommon(Tok, II, PP, Lookup);
1100}
1101
Douglas Gregorb09de512012-09-25 15:44:52 +00001102/// \brief Process __building_module(identifier) expression.
1103/// \returns true if we are building the named module, false otherwise.
1104static bool EvaluateBuildingModule(Token &Tok,
1105 IdentifierInfo *II, Preprocessor &PP) {
1106 // Get '('.
1107 PP.LexNonComment(Tok);
1108
1109 // Ensure we have a '('.
1110 if (Tok.isNot(tok::l_paren)) {
1111 PP.Diag(Tok.getLocation(), diag::err_pp_missing_lparen) << II->getName();
1112 return false;
1113 }
1114
1115 // Save '(' location for possible missing ')' message.
1116 SourceLocation LParenLoc = Tok.getLocation();
1117
1118 // Get the module name.
1119 PP.LexNonComment(Tok);
1120
1121 // Ensure that we have an identifier.
1122 if (Tok.isNot(tok::identifier)) {
1123 PP.Diag(Tok.getLocation(), diag::err_expected_id_building_module);
1124 return false;
1125 }
1126
1127 bool Result
1128 = Tok.getIdentifierInfo()->getName() == PP.getLangOpts().CurrentModule;
1129
1130 // Get ')'.
1131 PP.LexNonComment(Tok);
1132
1133 // Ensure we have a trailing ).
1134 if (Tok.isNot(tok::r_paren)) {
1135 PP.Diag(Tok.getLocation(), diag::err_pp_missing_rparen) << II->getName();
1136 PP.Diag(LParenLoc, diag::note_matching) << "(";
1137 return false;
1138 }
1139
1140 return Result;
1141}
1142
Joao Matos3e1ec722012-08-31 21:34:27 +00001143/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
1144/// as a builtin macro, handle it and return the next token as 'Tok'.
1145void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
1146 // Figure out which token this is.
1147 IdentifierInfo *II = Tok.getIdentifierInfo();
1148 assert(II && "Can't be a macro without id info!");
1149
1150 // If this is an _Pragma or Microsoft __pragma directive, expand it,
1151 // invoke the pragma handler, then lex the token after it.
1152 if (II == Ident_Pragma)
1153 return Handle_Pragma(Tok);
1154 else if (II == Ident__pragma) // in non-MS mode this is null
1155 return HandleMicrosoft__pragma(Tok);
1156
1157 ++NumBuiltinMacroExpanded;
1158
1159 SmallString<128> TmpBuffer;
1160 llvm::raw_svector_ostream OS(TmpBuffer);
1161
1162 // Set up the return result.
1163 Tok.setIdentifierInfo(0);
1164 Tok.clearFlag(Token::NeedsCleaning);
1165
1166 if (II == Ident__LINE__) {
1167 // C99 6.10.8: "__LINE__: The presumed line number (within the current
1168 // source file) of the current source line (an integer constant)". This can
1169 // be affected by #line.
1170 SourceLocation Loc = Tok.getLocation();
1171
1172 // Advance to the location of the first _, this might not be the first byte
1173 // of the token if it starts with an escaped newline.
1174 Loc = AdvanceToTokenCharacter(Loc, 0);
1175
1176 // One wrinkle here is that GCC expands __LINE__ to location of the *end* of
1177 // a macro expansion. This doesn't matter for object-like macros, but
1178 // can matter for a function-like macro that expands to contain __LINE__.
1179 // Skip down through expansion points until we find a file loc for the
1180 // end of the expansion history.
1181 Loc = SourceMgr.getExpansionRange(Loc).second;
1182 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc);
1183
1184 // __LINE__ expands to a simple numeric value.
1185 OS << (PLoc.isValid()? PLoc.getLine() : 1);
1186 Tok.setKind(tok::numeric_constant);
1187 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
1188 // C99 6.10.8: "__FILE__: The presumed name of the current source file (a
1189 // character string literal)". This can be affected by #line.
1190 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
1191
1192 // __BASE_FILE__ is a GNU extension that returns the top of the presumed
1193 // #include stack instead of the current file.
1194 if (II == Ident__BASE_FILE__ && PLoc.isValid()) {
1195 SourceLocation NextLoc = PLoc.getIncludeLoc();
1196 while (NextLoc.isValid()) {
1197 PLoc = SourceMgr.getPresumedLoc(NextLoc);
1198 if (PLoc.isInvalid())
1199 break;
1200
1201 NextLoc = PLoc.getIncludeLoc();
1202 }
1203 }
1204
1205 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
1206 SmallString<128> FN;
1207 if (PLoc.isValid()) {
1208 FN += PLoc.getFilename();
1209 Lexer::Stringify(FN);
1210 OS << '"' << FN.str() << '"';
1211 }
1212 Tok.setKind(tok::string_literal);
1213 } else if (II == Ident__DATE__) {
1214 if (!DATELoc.isValid())
1215 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1216 Tok.setKind(tok::string_literal);
1217 Tok.setLength(strlen("\"Mmm dd yyyy\""));
1218 Tok.setLocation(SourceMgr.createExpansionLoc(DATELoc, Tok.getLocation(),
1219 Tok.getLocation(),
1220 Tok.getLength()));
1221 return;
1222 } else if (II == Ident__TIME__) {
1223 if (!TIMELoc.isValid())
1224 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1225 Tok.setKind(tok::string_literal);
1226 Tok.setLength(strlen("\"hh:mm:ss\""));
1227 Tok.setLocation(SourceMgr.createExpansionLoc(TIMELoc, Tok.getLocation(),
1228 Tok.getLocation(),
1229 Tok.getLength()));
1230 return;
1231 } else if (II == Ident__INCLUDE_LEVEL__) {
1232 // Compute the presumed include depth of this token. This can be affected
1233 // by GNU line markers.
1234 unsigned Depth = 0;
1235
1236 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
1237 if (PLoc.isValid()) {
1238 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
1239 for (; PLoc.isValid(); ++Depth)
1240 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
1241 }
1242
1243 // __INCLUDE_LEVEL__ expands to a simple numeric value.
1244 OS << Depth;
1245 Tok.setKind(tok::numeric_constant);
1246 } else if (II == Ident__TIMESTAMP__) {
1247 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
1248 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
1249
1250 // Get the file that we are lexing out of. If we're currently lexing from
1251 // a macro, dig into the include stack.
1252 const FileEntry *CurFile = 0;
1253 PreprocessorLexer *TheLexer = getCurrentFileLexer();
1254
1255 if (TheLexer)
1256 CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID());
1257
1258 const char *Result;
1259 if (CurFile) {
1260 time_t TT = CurFile->getModificationTime();
1261 struct tm *TM = localtime(&TT);
1262 Result = asctime(TM);
1263 } else {
1264 Result = "??? ??? ?? ??:??:?? ????\n";
1265 }
1266 // Surround the string with " and strip the trailing newline.
1267 OS << '"' << StringRef(Result, strlen(Result)-1) << '"';
1268 Tok.setKind(tok::string_literal);
1269 } else if (II == Ident__COUNTER__) {
1270 // __COUNTER__ expands to a simple numeric value.
1271 OS << CounterValue++;
1272 Tok.setKind(tok::numeric_constant);
1273 } else if (II == Ident__has_feature ||
1274 II == Ident__has_extension ||
1275 II == Ident__has_builtin ||
1276 II == Ident__has_attribute) {
1277 // The argument to these builtins should be a parenthesized identifier.
1278 SourceLocation StartLoc = Tok.getLocation();
1279
1280 bool IsValid = false;
1281 IdentifierInfo *FeatureII = 0;
1282
1283 // Read the '('.
Andy Gibbs3f03b582012-11-17 19:18:27 +00001284 LexUnexpandedToken(Tok);
Joao Matos3e1ec722012-08-31 21:34:27 +00001285 if (Tok.is(tok::l_paren)) {
1286 // Read the identifier
Andy Gibbs3f03b582012-11-17 19:18:27 +00001287 LexUnexpandedToken(Tok);
Joao Matos3e1ec722012-08-31 21:34:27 +00001288 if (Tok.is(tok::identifier) || Tok.is(tok::kw_const)) {
1289 FeatureII = Tok.getIdentifierInfo();
1290
1291 // Read the ')'.
Andy Gibbs3f03b582012-11-17 19:18:27 +00001292 LexUnexpandedToken(Tok);
Joao Matos3e1ec722012-08-31 21:34:27 +00001293 if (Tok.is(tok::r_paren))
1294 IsValid = true;
1295 }
1296 }
1297
1298 bool Value = false;
1299 if (!IsValid)
1300 Diag(StartLoc, diag::err_feature_check_malformed);
1301 else if (II == Ident__has_builtin) {
1302 // Check for a builtin is trivial.
1303 Value = FeatureII->getBuiltinID() != 0;
1304 } else if (II == Ident__has_attribute)
1305 Value = HasAttribute(FeatureII);
1306 else if (II == Ident__has_extension)
1307 Value = HasExtension(*this, FeatureII);
1308 else {
1309 assert(II == Ident__has_feature && "Must be feature check");
1310 Value = HasFeature(*this, FeatureII);
1311 }
1312
1313 OS << (int)Value;
1314 if (IsValid)
1315 Tok.setKind(tok::numeric_constant);
1316 } else if (II == Ident__has_include ||
1317 II == Ident__has_include_next) {
1318 // The argument to these two builtins should be a parenthesized
1319 // file name string literal using angle brackets (<>) or
1320 // double-quotes ("").
1321 bool Value;
1322 if (II == Ident__has_include)
1323 Value = EvaluateHasInclude(Tok, II, *this);
1324 else
1325 Value = EvaluateHasIncludeNext(Tok, II, *this);
1326 OS << (int)Value;
Richard Trieu97bc3d52012-10-22 20:28:48 +00001327 if (Tok.is(tok::r_paren))
1328 Tok.setKind(tok::numeric_constant);
Joao Matos3e1ec722012-08-31 21:34:27 +00001329 } else if (II == Ident__has_warning) {
1330 // The argument should be a parenthesized string literal.
1331 // The argument to these builtins should be a parenthesized identifier.
1332 SourceLocation StartLoc = Tok.getLocation();
1333 bool IsValid = false;
1334 bool Value = false;
1335 // Read the '('.
Andy Gibbs02a17682012-11-17 19:15:38 +00001336 LexUnexpandedToken(Tok);
Joao Matos3e1ec722012-08-31 21:34:27 +00001337 do {
Andy Gibbs02a17682012-11-17 19:15:38 +00001338 if (Tok.isNot(tok::l_paren)) {
1339 Diag(StartLoc, diag::err_warning_check_malformed);
1340 break;
Joao Matos3e1ec722012-08-31 21:34:27 +00001341 }
Andy Gibbs02a17682012-11-17 19:15:38 +00001342
1343 LexUnexpandedToken(Tok);
1344 std::string WarningName;
1345 SourceLocation StrStartLoc = Tok.getLocation();
Andy Gibbs97f84612012-11-17 19:16:52 +00001346 if (!FinishLexStringLiteral(Tok, WarningName, "'__has_warning'",
1347 /*MacroExpansion=*/false)) {
Andy Gibbs02a17682012-11-17 19:15:38 +00001348 // Eat tokens until ')'.
Andy Gibbs6d534d42012-11-17 22:17:28 +00001349 while (Tok.isNot(tok::r_paren) && Tok.isNot(tok::eod) &&
1350 Tok.isNot(tok::eof))
Andy Gibbs02a17682012-11-17 19:15:38 +00001351 LexUnexpandedToken(Tok);
1352 break;
1353 }
1354
1355 // Is the end a ')'?
1356 if (!(IsValid = Tok.is(tok::r_paren))) {
1357 Diag(StartLoc, diag::err_warning_check_malformed);
1358 break;
1359 }
1360
1361 if (WarningName.size() < 3 || WarningName[0] != '-' ||
1362 WarningName[1] != 'W') {
1363 Diag(StrStartLoc, diag::warn_has_warning_invalid_option);
1364 break;
1365 }
1366
1367 // Finally, check if the warning flags maps to a diagnostic group.
1368 // We construct a SmallVector here to talk to getDiagnosticIDs().
1369 // Although we don't use the result, this isn't a hot path, and not
1370 // worth special casing.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001371 SmallVector<diag::kind, 10> Diags;
Andy Gibbs02a17682012-11-17 19:15:38 +00001372 Value = !getDiagnostics().getDiagnosticIDs()->
1373 getDiagnosticsInGroup(WarningName.substr(2), Diags);
Joao Matos3e1ec722012-08-31 21:34:27 +00001374 } while (false);
Joao Matos3e1ec722012-08-31 21:34:27 +00001375
1376 OS << (int)Value;
Andy Gibbsb9971ba2012-11-17 19:14:53 +00001377 if (IsValid)
1378 Tok.setKind(tok::numeric_constant);
Douglas Gregorb09de512012-09-25 15:44:52 +00001379 } else if (II == Ident__building_module) {
1380 // The argument to this builtin should be an identifier. The
1381 // builtin evaluates to 1 when that identifier names the module we are
1382 // currently building.
1383 OS << (int)EvaluateBuildingModule(Tok, II, *this);
1384 Tok.setKind(tok::numeric_constant);
1385 } else if (II == Ident__MODULE__) {
1386 // The current module as an identifier.
1387 OS << getLangOpts().CurrentModule;
1388 IdentifierInfo *ModuleII = getIdentifierInfo(getLangOpts().CurrentModule);
1389 Tok.setIdentifierInfo(ModuleII);
1390 Tok.setKind(ModuleII->getTokenID());
Joao Matos3e1ec722012-08-31 21:34:27 +00001391 } else {
1392 llvm_unreachable("Unknown identifier!");
1393 }
Dmitri Gribenko374b3832012-09-24 21:07:17 +00001394 CreateString(OS.str(), Tok, Tok.getLocation(), Tok.getLocation());
Joao Matos3e1ec722012-08-31 21:34:27 +00001395}
1396
1397void Preprocessor::markMacroAsUsed(MacroInfo *MI) {
1398 // If the 'used' status changed, and the macro requires 'unused' warning,
1399 // remove its SourceLocation from the warn-for-unused-macro locations.
1400 if (MI->isWarnIfUnused() && !MI->isUsed())
1401 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
1402 MI->setIsUsed(true);
1403}