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