blob: b7ea30e83cf0b7195325962f3f3c2e231626c583 [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
Alexander Kornienko4d7e0ce2012-09-25 17:18:14 +000035MacroInfo *Preprocessor::getMacroInfoHistory(IdentifierInfo *II) const {
36 assert(II->hadMacroDefinition() && "Identifier has not been not a macro!");
Joao Matos3e1ec722012-08-31 21:34:27 +000037
38 macro_iterator Pos = Macros.find(II);
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
Douglas Gregor3ab50fe2012-10-11 17:41:54 +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?");
62 assert(!MI->getPreviousDefinition() && "Macro already in chain?");
63
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()) {
82 MI->setPreviousDefinition(StoredMI);
83 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.
115 MI->setPreviousDefinition(Prev->getPreviousDefinition());
116 Prev->setPreviousDefinition(MI);
117 return;
118 }
119
120 // The macro is not a definition; put it at the end of the list.
Douglas Gregor3ab50fe2012-10-11 17:41:54 +0000121 MacroInfo *Prev = Hint? Hint : StoredMI;
Douglas Gregor6c6c54a2012-10-11 00:46:49 +0000122 while (Prev->getPreviousDefinition())
123 Prev = Prev->getPreviousDefinition();
124 Prev->setPreviousDefinition(MI);
125}
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
380 // If the macro definition is ambiguous, complain.
381 if (MI->isAmbiguous()) {
382 Diag(Identifier, diag::warn_pp_ambiguous_macro)
383 << Identifier.getIdentifierInfo();
384 Diag(MI->getDefinitionLoc(), diag::note_pp_ambiguous_macro_chosen)
385 << Identifier.getIdentifierInfo();
386 for (MacroInfo *PrevMI = MI->getPreviousDefinition();
387 PrevMI && PrevMI->isDefined();
388 PrevMI = PrevMI->getPreviousDefinition()) {
389 if (PrevMI->isAmbiguous()) {
390 Diag(PrevMI->getDefinitionLoc(), diag::note_pp_ambiguous_macro_other)
391 << Identifier.getIdentifierInfo();
392 }
393 }
394 }
395
Joao Matos3e1ec722012-08-31 21:34:27 +0000396 // If we started lexing a macro, enter the macro expansion body.
397
398 // If this macro expands to no tokens, don't bother to push it onto the
399 // expansion stack, only to take it right back off.
400 if (MI->getNumTokens() == 0) {
401 // No need for arg info.
402 if (Args) Args->destroy(*this);
403
404 // Ignore this macro use, just return the next token in the current
405 // buffer.
406 bool HadLeadingSpace = Identifier.hasLeadingSpace();
407 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
408
409 Lex(Identifier);
410
411 // If the identifier isn't on some OTHER line, inherit the leading
412 // whitespace/first-on-a-line property of this token. This handles
413 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
414 // empty.
415 if (!Identifier.isAtStartOfLine()) {
416 if (IsAtStartOfLine) Identifier.setFlag(Token::StartOfLine);
417 if (HadLeadingSpace) Identifier.setFlag(Token::LeadingSpace);
418 }
419 Identifier.setFlag(Token::LeadingEmptyMacro);
420 ++NumFastMacroExpanded;
421 return false;
422
423 } else if (MI->getNumTokens() == 1 &&
424 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
425 *this)) {
426 // Otherwise, if this macro expands into a single trivially-expanded
427 // token: expand it now. This handles common cases like
428 // "#define VAL 42".
429
430 // No need for arg info.
431 if (Args) Args->destroy(*this);
432
433 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
434 // identifier to the expanded token.
435 bool isAtStartOfLine = Identifier.isAtStartOfLine();
436 bool hasLeadingSpace = Identifier.hasLeadingSpace();
437
438 // Replace the result token.
439 Identifier = MI->getReplacementToken(0);
440
441 // Restore the StartOfLine/LeadingSpace markers.
442 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
443 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
444
445 // Update the tokens location to include both its expansion and physical
446 // locations.
447 SourceLocation Loc =
448 SourceMgr.createExpansionLoc(Identifier.getLocation(), ExpandLoc,
449 ExpansionEnd,Identifier.getLength());
450 Identifier.setLocation(Loc);
451
452 // If this is a disabled macro or #define X X, we must mark the result as
453 // unexpandable.
454 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo()) {
455 if (MacroInfo *NewMI = getMacroInfo(NewII))
456 if (!NewMI->isEnabled() || NewMI == MI) {
457 Identifier.setFlag(Token::DisableExpand);
458 Diag(Identifier, diag::pp_disabled_macro_expansion);
459 }
460 }
461
462 // Since this is not an identifier token, it can't be macro expanded, so
463 // we're done.
464 ++NumFastMacroExpanded;
465 return false;
466 }
467
468 // Start expanding the macro.
469 EnterMacro(Identifier, ExpansionEnd, MI, Args);
470
471 // Now that the macro is at the top of the include stack, ask the
472 // preprocessor to read the next token from it.
473 Lex(Identifier);
474 return false;
475}
476
477/// ReadFunctionLikeMacroArgs - After reading "MACRO" and knowing that the next
478/// token is the '(' of the macro, this method is invoked to read all of the
479/// actual arguments specified for the macro invocation. This returns null on
480/// error.
481MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
482 MacroInfo *MI,
483 SourceLocation &MacroEnd) {
484 // The number of fixed arguments to parse.
485 unsigned NumFixedArgsLeft = MI->getNumArgs();
486 bool isVariadic = MI->isVariadic();
487
488 // Outer loop, while there are more arguments, keep reading them.
489 Token Tok;
490
491 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
492 // an argument value in a macro could expand to ',' or '(' or ')'.
493 LexUnexpandedToken(Tok);
494 assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
495
496 // ArgTokens - Build up a list of tokens that make up each argument. Each
497 // argument is separated by an EOF token. Use a SmallVector so we can avoid
498 // heap allocations in the common case.
499 SmallVector<Token, 64> ArgTokens;
Argyrios Kyrtzidiscd0fd182012-12-21 01:17:20 +0000500 bool ContainsCodeCompletionTok = false;
Joao Matos3e1ec722012-08-31 21:34:27 +0000501
502 unsigned NumActuals = 0;
503 while (Tok.isNot(tok::r_paren)) {
Argyrios Kyrtzidiscd0fd182012-12-21 01:17:20 +0000504 if (ContainsCodeCompletionTok && (Tok.is(tok::eof) || Tok.is(tok::eod)))
505 break;
506
Joao Matos3e1ec722012-08-31 21:34:27 +0000507 assert((Tok.is(tok::l_paren) || Tok.is(tok::comma)) &&
508 "only expect argument separators here");
509
510 unsigned ArgTokenStart = ArgTokens.size();
511 SourceLocation ArgStartLoc = Tok.getLocation();
512
513 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
514 // that we already consumed the first one.
515 unsigned NumParens = 0;
516
517 while (1) {
518 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
519 // an argument value in a macro could expand to ',' or '(' or ')'.
520 LexUnexpandedToken(Tok);
521
522 if (Tok.is(tok::eof) || Tok.is(tok::eod)) { // "#if f(<eof>" & "#if f(\n"
Argyrios Kyrtzidiscd0fd182012-12-21 01:17:20 +0000523 if (!ContainsCodeCompletionTok) {
524 Diag(MacroName, diag::err_unterm_macro_invoc);
525 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
526 << MacroName.getIdentifierInfo();
527 // Do not lose the EOF/EOD. Return it to the client.
528 MacroName = Tok;
529 return 0;
530 } else {
531 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)
599 Diag(Tok, LangOpts.CPlusPlus0x ?
600 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())
817 .Case("objc_weak_class", LangOpts.ObjCRuntime.hasWeakClassImport())
818 .Case("ownership_holds", true)
819 .Case("ownership_returns", true)
820 .Case("ownership_takes", true)
821 .Case("objc_bool", true)
822 .Case("objc_subscripting", LangOpts.ObjCRuntime.isNonFragile())
823 .Case("objc_array_literals", LangOpts.ObjC2)
824 .Case("objc_dictionary_literals", LangOpts.ObjC2)
825 .Case("objc_boxed_expressions", LangOpts.ObjC2)
826 .Case("arc_cf_code_audited", true)
827 // C11 features
828 .Case("c_alignas", LangOpts.C11)
829 .Case("c_atomic", LangOpts.C11)
830 .Case("c_generic_selections", LangOpts.C11)
831 .Case("c_static_assert", LangOpts.C11)
832 // C++11 features
833 .Case("cxx_access_control_sfinae", LangOpts.CPlusPlus0x)
834 .Case("cxx_alias_templates", LangOpts.CPlusPlus0x)
835 .Case("cxx_alignas", LangOpts.CPlusPlus0x)
836 .Case("cxx_atomic", LangOpts.CPlusPlus0x)
837 .Case("cxx_attributes", LangOpts.CPlusPlus0x)
838 .Case("cxx_auto_type", LangOpts.CPlusPlus0x)
839 .Case("cxx_constexpr", LangOpts.CPlusPlus0x)
840 .Case("cxx_decltype", LangOpts.CPlusPlus0x)
841 .Case("cxx_decltype_incomplete_return_types", LangOpts.CPlusPlus0x)
842 .Case("cxx_default_function_template_args", LangOpts.CPlusPlus0x)
843 .Case("cxx_defaulted_functions", LangOpts.CPlusPlus0x)
844 .Case("cxx_delegating_constructors", LangOpts.CPlusPlus0x)
845 .Case("cxx_deleted_functions", LangOpts.CPlusPlus0x)
846 .Case("cxx_explicit_conversions", LangOpts.CPlusPlus0x)
847 .Case("cxx_generalized_initializers", LangOpts.CPlusPlus0x)
848 .Case("cxx_implicit_moves", LangOpts.CPlusPlus0x)
849 //.Case("cxx_inheriting_constructors", false)
850 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus0x)
851 .Case("cxx_lambdas", LangOpts.CPlusPlus0x)
852 .Case("cxx_local_type_template_args", LangOpts.CPlusPlus0x)
853 .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus0x)
854 .Case("cxx_noexcept", LangOpts.CPlusPlus0x)
855 .Case("cxx_nullptr", LangOpts.CPlusPlus0x)
856 .Case("cxx_override_control", LangOpts.CPlusPlus0x)
857 .Case("cxx_range_for", LangOpts.CPlusPlus0x)
858 .Case("cxx_raw_string_literals", LangOpts.CPlusPlus0x)
859 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus0x)
860 .Case("cxx_rvalue_references", LangOpts.CPlusPlus0x)
861 .Case("cxx_strong_enums", LangOpts.CPlusPlus0x)
862 .Case("cxx_static_assert", LangOpts.CPlusPlus0x)
863 .Case("cxx_trailing_return", LangOpts.CPlusPlus0x)
864 .Case("cxx_unicode_literals", LangOpts.CPlusPlus0x)
865 .Case("cxx_unrestricted_unions", LangOpts.CPlusPlus0x)
866 .Case("cxx_user_literals", LangOpts.CPlusPlus0x)
867 .Case("cxx_variadic_templates", LangOpts.CPlusPlus0x)
868 // Type traits
869 .Case("has_nothrow_assign", LangOpts.CPlusPlus)
870 .Case("has_nothrow_copy", LangOpts.CPlusPlus)
871 .Case("has_nothrow_constructor", LangOpts.CPlusPlus)
872 .Case("has_trivial_assign", LangOpts.CPlusPlus)
873 .Case("has_trivial_copy", LangOpts.CPlusPlus)
874 .Case("has_trivial_constructor", LangOpts.CPlusPlus)
875 .Case("has_trivial_destructor", LangOpts.CPlusPlus)
876 .Case("has_virtual_destructor", LangOpts.CPlusPlus)
877 .Case("is_abstract", LangOpts.CPlusPlus)
878 .Case("is_base_of", LangOpts.CPlusPlus)
879 .Case("is_class", LangOpts.CPlusPlus)
880 .Case("is_convertible_to", LangOpts.CPlusPlus)
Joao Matos3e1ec722012-08-31 21:34:27 +0000881 .Case("is_empty", LangOpts.CPlusPlus)
882 .Case("is_enum", LangOpts.CPlusPlus)
883 .Case("is_final", LangOpts.CPlusPlus)
884 .Case("is_literal", LangOpts.CPlusPlus)
885 .Case("is_standard_layout", LangOpts.CPlusPlus)
886 .Case("is_pod", LangOpts.CPlusPlus)
887 .Case("is_polymorphic", LangOpts.CPlusPlus)
888 .Case("is_trivial", LangOpts.CPlusPlus)
889 .Case("is_trivially_assignable", LangOpts.CPlusPlus)
890 .Case("is_trivially_constructible", LangOpts.CPlusPlus)
891 .Case("is_trivially_copyable", LangOpts.CPlusPlus)
892 .Case("is_union", LangOpts.CPlusPlus)
893 .Case("modules", LangOpts.Modules)
894 .Case("tls", PP.getTargetInfo().isTLSSupported())
895 .Case("underlying_type", LangOpts.CPlusPlus)
896 .Default(false);
897}
898
899/// HasExtension - Return true if we recognize and implement the feature
900/// specified by the identifier, either as an extension or a standard language
901/// feature.
902static bool HasExtension(const Preprocessor &PP, const IdentifierInfo *II) {
903 if (HasFeature(PP, II))
904 return true;
905
906 // If the use of an extension results in an error diagnostic, extensions are
907 // effectively unavailable, so just return false here.
908 if (PP.getDiagnostics().getExtensionHandlingBehavior() ==
909 DiagnosticsEngine::Ext_Error)
910 return false;
911
912 const LangOptions &LangOpts = PP.getLangOpts();
913 StringRef Extension = II->getName();
914
915 // Normalize the extension name, __foo__ becomes foo.
916 if (Extension.startswith("__") && Extension.endswith("__") &&
917 Extension.size() >= 4)
918 Extension = Extension.substr(2, Extension.size() - 4);
919
920 // Because we inherit the feature list from HasFeature, this string switch
921 // must be less restrictive than HasFeature's.
922 return llvm::StringSwitch<bool>(Extension)
923 // C11 features supported by other languages as extensions.
924 .Case("c_alignas", true)
925 .Case("c_atomic", true)
926 .Case("c_generic_selections", true)
927 .Case("c_static_assert", true)
928 // C++0x features supported by other languages as extensions.
929 .Case("cxx_atomic", LangOpts.CPlusPlus)
930 .Case("cxx_deleted_functions", LangOpts.CPlusPlus)
931 .Case("cxx_explicit_conversions", LangOpts.CPlusPlus)
932 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus)
933 .Case("cxx_local_type_template_args", LangOpts.CPlusPlus)
934 .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus)
935 .Case("cxx_override_control", LangOpts.CPlusPlus)
936 .Case("cxx_range_for", LangOpts.CPlusPlus)
937 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus)
938 .Case("cxx_rvalue_references", LangOpts.CPlusPlus)
939 .Default(false);
940}
941
942/// HasAttribute - Return true if we recognize and implement the attribute
943/// specified by the given identifier.
944static bool HasAttribute(const IdentifierInfo *II) {
945 StringRef Name = II->getName();
946 // Normalize the attribute name, __foo__ becomes foo.
947 if (Name.startswith("__") && Name.endswith("__") && Name.size() >= 4)
948 Name = Name.substr(2, Name.size() - 4);
949
950 // FIXME: Do we need to handle namespaces here?
951 return llvm::StringSwitch<bool>(Name)
952#include "clang/Lex/AttrSpellings.inc"
953 .Default(false);
954}
955
956/// EvaluateHasIncludeCommon - Process a '__has_include("path")'
957/// or '__has_include_next("path")' expression.
958/// Returns true if successful.
959static bool EvaluateHasIncludeCommon(Token &Tok,
960 IdentifierInfo *II, Preprocessor &PP,
961 const DirectoryLookup *LookupFrom) {
Richard Trieu97bc3d52012-10-22 20:28:48 +0000962 // Save the location of the current token. If a '(' is later found, use
963 // that location. If no, use the end of this location instead.
964 SourceLocation LParenLoc = Tok.getLocation();
Joao Matos3e1ec722012-08-31 21:34:27 +0000965
966 // Get '('.
967 PP.LexNonComment(Tok);
968
969 // Ensure we have a '('.
970 if (Tok.isNot(tok::l_paren)) {
Richard Trieu97bc3d52012-10-22 20:28:48 +0000971 // No '(', use end of last token.
972 LParenLoc = PP.getLocForEndOfToken(LParenLoc);
973 PP.Diag(LParenLoc, diag::err_pp_missing_lparen) << II->getName();
974 // If the next token looks like a filename or the start of one,
975 // assume it is and process it as such.
976 if (!Tok.is(tok::angle_string_literal) && !Tok.is(tok::string_literal) &&
977 !Tok.is(tok::less))
978 return false;
979 } else {
980 // Save '(' location for possible missing ')' message.
981 LParenLoc = Tok.getLocation();
982
983 // Get the file name.
984 PP.getCurrentLexer()->LexIncludeFilename(Tok);
Joao Matos3e1ec722012-08-31 21:34:27 +0000985 }
986
Joao Matos3e1ec722012-08-31 21:34:27 +0000987 // Reserve a buffer to get the spelling.
988 SmallString<128> FilenameBuffer;
989 StringRef Filename;
990 SourceLocation EndLoc;
991
992 switch (Tok.getKind()) {
993 case tok::eod:
994 // If the token kind is EOD, the error has already been diagnosed.
995 return false;
996
997 case tok::angle_string_literal:
998 case tok::string_literal: {
999 bool Invalid = false;
1000 Filename = PP.getSpelling(Tok, FilenameBuffer, &Invalid);
1001 if (Invalid)
1002 return false;
1003 break;
1004 }
1005
1006 case tok::less:
1007 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1008 // case, glue the tokens together into FilenameBuffer and interpret those.
1009 FilenameBuffer.push_back('<');
Richard Trieu97bc3d52012-10-22 20:28:48 +00001010 if (PP.ConcatenateIncludeName(FilenameBuffer, EndLoc)) {
1011 // Let the caller know a <eod> was found by changing the Token kind.
1012 Tok.setKind(tok::eod);
Joao Matos3e1ec722012-08-31 21:34:27 +00001013 return false; // Found <eod> but no ">"? Diagnostic already emitted.
Richard Trieu97bc3d52012-10-22 20:28:48 +00001014 }
Joao Matos3e1ec722012-08-31 21:34:27 +00001015 Filename = FilenameBuffer.str();
1016 break;
1017 default:
1018 PP.Diag(Tok.getLocation(), diag::err_pp_expects_filename);
1019 return false;
1020 }
1021
Richard Trieu97bc3d52012-10-22 20:28:48 +00001022 SourceLocation FilenameLoc = Tok.getLocation();
1023
Joao Matos3e1ec722012-08-31 21:34:27 +00001024 // Get ')'.
1025 PP.LexNonComment(Tok);
1026
1027 // Ensure we have a trailing ).
1028 if (Tok.isNot(tok::r_paren)) {
Richard Trieu97bc3d52012-10-22 20:28:48 +00001029 PP.Diag(PP.getLocForEndOfToken(FilenameLoc), diag::err_pp_missing_rparen)
1030 << II->getName();
Joao Matos3e1ec722012-08-31 21:34:27 +00001031 PP.Diag(LParenLoc, diag::note_matching) << "(";
1032 return false;
1033 }
1034
1035 bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename);
1036 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1037 // error.
1038 if (Filename.empty())
1039 return false;
1040
1041 // Search include directories.
1042 const DirectoryLookup *CurDir;
1043 const FileEntry *File =
1044 PP.LookupFile(Filename, isAngled, LookupFrom, CurDir, NULL, NULL, NULL);
1045
1046 // Get the result value. A result of true means the file exists.
1047 return File != 0;
1048}
1049
1050/// EvaluateHasInclude - Process a '__has_include("path")' expression.
1051/// Returns true if successful.
1052static bool EvaluateHasInclude(Token &Tok, IdentifierInfo *II,
1053 Preprocessor &PP) {
1054 return EvaluateHasIncludeCommon(Tok, II, PP, NULL);
1055}
1056
1057/// EvaluateHasIncludeNext - Process '__has_include_next("path")' expression.
1058/// Returns true if successful.
1059static bool EvaluateHasIncludeNext(Token &Tok,
1060 IdentifierInfo *II, Preprocessor &PP) {
1061 // __has_include_next is like __has_include, except that we start
1062 // searching after the current found directory. If we can't do this,
1063 // issue a diagnostic.
1064 const DirectoryLookup *Lookup = PP.GetCurDirLookup();
1065 if (PP.isInPrimaryFile()) {
1066 Lookup = 0;
1067 PP.Diag(Tok, diag::pp_include_next_in_primary);
1068 } else if (Lookup == 0) {
1069 PP.Diag(Tok, diag::pp_include_next_absolute_path);
1070 } else {
1071 // Start looking up in the next directory.
1072 ++Lookup;
1073 }
1074
1075 return EvaluateHasIncludeCommon(Tok, II, PP, Lookup);
1076}
1077
Douglas Gregorb09de512012-09-25 15:44:52 +00001078/// \brief Process __building_module(identifier) expression.
1079/// \returns true if we are building the named module, false otherwise.
1080static bool EvaluateBuildingModule(Token &Tok,
1081 IdentifierInfo *II, Preprocessor &PP) {
1082 // Get '('.
1083 PP.LexNonComment(Tok);
1084
1085 // Ensure we have a '('.
1086 if (Tok.isNot(tok::l_paren)) {
1087 PP.Diag(Tok.getLocation(), diag::err_pp_missing_lparen) << II->getName();
1088 return false;
1089 }
1090
1091 // Save '(' location for possible missing ')' message.
1092 SourceLocation LParenLoc = Tok.getLocation();
1093
1094 // Get the module name.
1095 PP.LexNonComment(Tok);
1096
1097 // Ensure that we have an identifier.
1098 if (Tok.isNot(tok::identifier)) {
1099 PP.Diag(Tok.getLocation(), diag::err_expected_id_building_module);
1100 return false;
1101 }
1102
1103 bool Result
1104 = Tok.getIdentifierInfo()->getName() == PP.getLangOpts().CurrentModule;
1105
1106 // Get ')'.
1107 PP.LexNonComment(Tok);
1108
1109 // Ensure we have a trailing ).
1110 if (Tok.isNot(tok::r_paren)) {
1111 PP.Diag(Tok.getLocation(), diag::err_pp_missing_rparen) << II->getName();
1112 PP.Diag(LParenLoc, diag::note_matching) << "(";
1113 return false;
1114 }
1115
1116 return Result;
1117}
1118
Joao Matos3e1ec722012-08-31 21:34:27 +00001119/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
1120/// as a builtin macro, handle it and return the next token as 'Tok'.
1121void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
1122 // Figure out which token this is.
1123 IdentifierInfo *II = Tok.getIdentifierInfo();
1124 assert(II && "Can't be a macro without id info!");
1125
1126 // If this is an _Pragma or Microsoft __pragma directive, expand it,
1127 // invoke the pragma handler, then lex the token after it.
1128 if (II == Ident_Pragma)
1129 return Handle_Pragma(Tok);
1130 else if (II == Ident__pragma) // in non-MS mode this is null
1131 return HandleMicrosoft__pragma(Tok);
1132
1133 ++NumBuiltinMacroExpanded;
1134
1135 SmallString<128> TmpBuffer;
1136 llvm::raw_svector_ostream OS(TmpBuffer);
1137
1138 // Set up the return result.
1139 Tok.setIdentifierInfo(0);
1140 Tok.clearFlag(Token::NeedsCleaning);
1141
1142 if (II == Ident__LINE__) {
1143 // C99 6.10.8: "__LINE__: The presumed line number (within the current
1144 // source file) of the current source line (an integer constant)". This can
1145 // be affected by #line.
1146 SourceLocation Loc = Tok.getLocation();
1147
1148 // Advance to the location of the first _, this might not be the first byte
1149 // of the token if it starts with an escaped newline.
1150 Loc = AdvanceToTokenCharacter(Loc, 0);
1151
1152 // One wrinkle here is that GCC expands __LINE__ to location of the *end* of
1153 // a macro expansion. This doesn't matter for object-like macros, but
1154 // can matter for a function-like macro that expands to contain __LINE__.
1155 // Skip down through expansion points until we find a file loc for the
1156 // end of the expansion history.
1157 Loc = SourceMgr.getExpansionRange(Loc).second;
1158 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc);
1159
1160 // __LINE__ expands to a simple numeric value.
1161 OS << (PLoc.isValid()? PLoc.getLine() : 1);
1162 Tok.setKind(tok::numeric_constant);
1163 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
1164 // C99 6.10.8: "__FILE__: The presumed name of the current source file (a
1165 // character string literal)". This can be affected by #line.
1166 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
1167
1168 // __BASE_FILE__ is a GNU extension that returns the top of the presumed
1169 // #include stack instead of the current file.
1170 if (II == Ident__BASE_FILE__ && PLoc.isValid()) {
1171 SourceLocation NextLoc = PLoc.getIncludeLoc();
1172 while (NextLoc.isValid()) {
1173 PLoc = SourceMgr.getPresumedLoc(NextLoc);
1174 if (PLoc.isInvalid())
1175 break;
1176
1177 NextLoc = PLoc.getIncludeLoc();
1178 }
1179 }
1180
1181 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
1182 SmallString<128> FN;
1183 if (PLoc.isValid()) {
1184 FN += PLoc.getFilename();
1185 Lexer::Stringify(FN);
1186 OS << '"' << FN.str() << '"';
1187 }
1188 Tok.setKind(tok::string_literal);
1189 } else if (II == Ident__DATE__) {
1190 if (!DATELoc.isValid())
1191 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1192 Tok.setKind(tok::string_literal);
1193 Tok.setLength(strlen("\"Mmm dd yyyy\""));
1194 Tok.setLocation(SourceMgr.createExpansionLoc(DATELoc, Tok.getLocation(),
1195 Tok.getLocation(),
1196 Tok.getLength()));
1197 return;
1198 } else if (II == Ident__TIME__) {
1199 if (!TIMELoc.isValid())
1200 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1201 Tok.setKind(tok::string_literal);
1202 Tok.setLength(strlen("\"hh:mm:ss\""));
1203 Tok.setLocation(SourceMgr.createExpansionLoc(TIMELoc, Tok.getLocation(),
1204 Tok.getLocation(),
1205 Tok.getLength()));
1206 return;
1207 } else if (II == Ident__INCLUDE_LEVEL__) {
1208 // Compute the presumed include depth of this token. This can be affected
1209 // by GNU line markers.
1210 unsigned Depth = 0;
1211
1212 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
1213 if (PLoc.isValid()) {
1214 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
1215 for (; PLoc.isValid(); ++Depth)
1216 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
1217 }
1218
1219 // __INCLUDE_LEVEL__ expands to a simple numeric value.
1220 OS << Depth;
1221 Tok.setKind(tok::numeric_constant);
1222 } else if (II == Ident__TIMESTAMP__) {
1223 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
1224 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
1225
1226 // Get the file that we are lexing out of. If we're currently lexing from
1227 // a macro, dig into the include stack.
1228 const FileEntry *CurFile = 0;
1229 PreprocessorLexer *TheLexer = getCurrentFileLexer();
1230
1231 if (TheLexer)
1232 CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID());
1233
1234 const char *Result;
1235 if (CurFile) {
1236 time_t TT = CurFile->getModificationTime();
1237 struct tm *TM = localtime(&TT);
1238 Result = asctime(TM);
1239 } else {
1240 Result = "??? ??? ?? ??:??:?? ????\n";
1241 }
1242 // Surround the string with " and strip the trailing newline.
1243 OS << '"' << StringRef(Result, strlen(Result)-1) << '"';
1244 Tok.setKind(tok::string_literal);
1245 } else if (II == Ident__COUNTER__) {
1246 // __COUNTER__ expands to a simple numeric value.
1247 OS << CounterValue++;
1248 Tok.setKind(tok::numeric_constant);
1249 } else if (II == Ident__has_feature ||
1250 II == Ident__has_extension ||
1251 II == Ident__has_builtin ||
1252 II == Ident__has_attribute) {
1253 // The argument to these builtins should be a parenthesized identifier.
1254 SourceLocation StartLoc = Tok.getLocation();
1255
1256 bool IsValid = false;
1257 IdentifierInfo *FeatureII = 0;
1258
1259 // Read the '('.
Andy Gibbs3f03b582012-11-17 19:18:27 +00001260 LexUnexpandedToken(Tok);
Joao Matos3e1ec722012-08-31 21:34:27 +00001261 if (Tok.is(tok::l_paren)) {
1262 // Read the identifier
Andy Gibbs3f03b582012-11-17 19:18:27 +00001263 LexUnexpandedToken(Tok);
Joao Matos3e1ec722012-08-31 21:34:27 +00001264 if (Tok.is(tok::identifier) || Tok.is(tok::kw_const)) {
1265 FeatureII = Tok.getIdentifierInfo();
1266
1267 // Read the ')'.
Andy Gibbs3f03b582012-11-17 19:18:27 +00001268 LexUnexpandedToken(Tok);
Joao Matos3e1ec722012-08-31 21:34:27 +00001269 if (Tok.is(tok::r_paren))
1270 IsValid = true;
1271 }
1272 }
1273
1274 bool Value = false;
1275 if (!IsValid)
1276 Diag(StartLoc, diag::err_feature_check_malformed);
1277 else if (II == Ident__has_builtin) {
1278 // Check for a builtin is trivial.
1279 Value = FeatureII->getBuiltinID() != 0;
1280 } else if (II == Ident__has_attribute)
1281 Value = HasAttribute(FeatureII);
1282 else if (II == Ident__has_extension)
1283 Value = HasExtension(*this, FeatureII);
1284 else {
1285 assert(II == Ident__has_feature && "Must be feature check");
1286 Value = HasFeature(*this, FeatureII);
1287 }
1288
1289 OS << (int)Value;
1290 if (IsValid)
1291 Tok.setKind(tok::numeric_constant);
1292 } else if (II == Ident__has_include ||
1293 II == Ident__has_include_next) {
1294 // The argument to these two builtins should be a parenthesized
1295 // file name string literal using angle brackets (<>) or
1296 // double-quotes ("").
1297 bool Value;
1298 if (II == Ident__has_include)
1299 Value = EvaluateHasInclude(Tok, II, *this);
1300 else
1301 Value = EvaluateHasIncludeNext(Tok, II, *this);
1302 OS << (int)Value;
Richard Trieu97bc3d52012-10-22 20:28:48 +00001303 if (Tok.is(tok::r_paren))
1304 Tok.setKind(tok::numeric_constant);
Joao Matos3e1ec722012-08-31 21:34:27 +00001305 } else if (II == Ident__has_warning) {
1306 // The argument should be a parenthesized string literal.
1307 // The argument to these builtins should be a parenthesized identifier.
1308 SourceLocation StartLoc = Tok.getLocation();
1309 bool IsValid = false;
1310 bool Value = false;
1311 // Read the '('.
Andy Gibbs02a17682012-11-17 19:15:38 +00001312 LexUnexpandedToken(Tok);
Joao Matos3e1ec722012-08-31 21:34:27 +00001313 do {
Andy Gibbs02a17682012-11-17 19:15:38 +00001314 if (Tok.isNot(tok::l_paren)) {
1315 Diag(StartLoc, diag::err_warning_check_malformed);
1316 break;
Joao Matos3e1ec722012-08-31 21:34:27 +00001317 }
Andy Gibbs02a17682012-11-17 19:15:38 +00001318
1319 LexUnexpandedToken(Tok);
1320 std::string WarningName;
1321 SourceLocation StrStartLoc = Tok.getLocation();
Andy Gibbs97f84612012-11-17 19:16:52 +00001322 if (!FinishLexStringLiteral(Tok, WarningName, "'__has_warning'",
1323 /*MacroExpansion=*/false)) {
Andy Gibbs02a17682012-11-17 19:15:38 +00001324 // Eat tokens until ')'.
Andy Gibbs6d534d42012-11-17 22:17:28 +00001325 while (Tok.isNot(tok::r_paren) && Tok.isNot(tok::eod) &&
1326 Tok.isNot(tok::eof))
Andy Gibbs02a17682012-11-17 19:15:38 +00001327 LexUnexpandedToken(Tok);
1328 break;
1329 }
1330
1331 // Is the end a ')'?
1332 if (!(IsValid = Tok.is(tok::r_paren))) {
1333 Diag(StartLoc, diag::err_warning_check_malformed);
1334 break;
1335 }
1336
1337 if (WarningName.size() < 3 || WarningName[0] != '-' ||
1338 WarningName[1] != 'W') {
1339 Diag(StrStartLoc, diag::warn_has_warning_invalid_option);
1340 break;
1341 }
1342
1343 // Finally, check if the warning flags maps to a diagnostic group.
1344 // We construct a SmallVector here to talk to getDiagnosticIDs().
1345 // Although we don't use the result, this isn't a hot path, and not
1346 // worth special casing.
1347 llvm::SmallVector<diag::kind, 10> Diags;
1348 Value = !getDiagnostics().getDiagnosticIDs()->
1349 getDiagnosticsInGroup(WarningName.substr(2), Diags);
Joao Matos3e1ec722012-08-31 21:34:27 +00001350 } while (false);
Joao Matos3e1ec722012-08-31 21:34:27 +00001351
1352 OS << (int)Value;
Andy Gibbsb9971ba2012-11-17 19:14:53 +00001353 if (IsValid)
1354 Tok.setKind(tok::numeric_constant);
Douglas Gregorb09de512012-09-25 15:44:52 +00001355 } else if (II == Ident__building_module) {
1356 // The argument to this builtin should be an identifier. The
1357 // builtin evaluates to 1 when that identifier names the module we are
1358 // currently building.
1359 OS << (int)EvaluateBuildingModule(Tok, II, *this);
1360 Tok.setKind(tok::numeric_constant);
1361 } else if (II == Ident__MODULE__) {
1362 // The current module as an identifier.
1363 OS << getLangOpts().CurrentModule;
1364 IdentifierInfo *ModuleII = getIdentifierInfo(getLangOpts().CurrentModule);
1365 Tok.setIdentifierInfo(ModuleII);
1366 Tok.setKind(ModuleII->getTokenID());
Joao Matos3e1ec722012-08-31 21:34:27 +00001367 } else {
1368 llvm_unreachable("Unknown identifier!");
1369 }
Dmitri Gribenko374b3832012-09-24 21:07:17 +00001370 CreateString(OS.str(), Tok, Tok.getLocation(), Tok.getLocation());
Joao Matos3e1ec722012-08-31 21:34:27 +00001371}
1372
1373void Preprocessor::markMacroAsUsed(MacroInfo *MI) {
1374 // If the 'used' status changed, and the macro requires 'unused' warning,
1375 // remove its SourceLocation from the warn-for-unused-macro locations.
1376 if (MI->isWarnIfUnused() && !MI->isUsed())
1377 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
1378 MI->setIsUsed(true);
1379}