blob: 06f14c24bdda3882c12e9e35a818c39d64cc9620 [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"
Argyrios Kyrtzidisdd08a0c2013-05-03 22:31:32 +000016#include "clang/Lex/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
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +000035MacroDirective *
36Preprocessor::getMacroDirectiveHistory(const IdentifierInfo *II) const {
Alexander Kornienko4d7e0ce2012-09-25 17:18:14 +000037 assert(II->hadMacroDefinition() && "Identifier has not been not a macro!");
Joao Matos3e1ec722012-08-31 21:34:27 +000038
39 macro_iterator Pos = Macros.find(II);
Joao Matos3e1ec722012-08-31 21:34:27 +000040 assert(Pos != Macros.end() && "Identifier macro info is missing!");
Joao Matos3e1ec722012-08-31 21:34:27 +000041 return Pos->second;
42}
43
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +000044void Preprocessor::appendMacroDirective(IdentifierInfo *II, MacroDirective *MD){
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +000045 assert(MD && "MacroDirective should be non-zero!");
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +000046 assert(!MD->getPrevious() && "Already attached to a MacroDirective history.");
Douglas Gregor6c6c54a2012-10-11 00:46:49 +000047
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +000048 MacroDirective *&StoredMD = Macros[II];
49 MD->setPrevious(StoredMD);
50 StoredMD = MD;
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +000051 II->setHasMacroDefinition(MD->isDefined());
52 bool isImportedMacro = isa<DefMacroDirective>(MD) &&
53 cast<DefMacroDirective>(MD)->isImported();
54 if (II->isFromAST() && !isImportedMacro)
Joao Matos3e1ec722012-08-31 21:34:27 +000055 II->setChangedSinceDeserialization();
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +000056}
Argyrios Kyrtzidisc5159782013-02-24 00:05:14 +000057
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +000058void Preprocessor::setLoadedMacroDirective(IdentifierInfo *II,
59 MacroDirective *MD) {
60 assert(II && MD);
61 MacroDirective *&StoredMD = Macros[II];
62 assert(!StoredMD &&
63 "the macro history was modified before initializing it from a pch");
64 StoredMD = MD;
65 // Setup the identifier as having associated macro history.
66 II->setHasMacroDefinition(true);
67 if (!MD->isDefined())
68 II->setHasMacroDefinition(false);
Joao Matos3e1ec722012-08-31 21:34:27 +000069}
70
Joao Matos3e1ec722012-08-31 21:34:27 +000071/// RegisterBuiltinMacro - Register the specified identifier in the identifier
72/// table and mark it as a builtin macro to be expanded.
73static IdentifierInfo *RegisterBuiltinMacro(Preprocessor &PP, const char *Name){
74 // Get the identifier.
75 IdentifierInfo *Id = PP.getIdentifierInfo(Name);
76
77 // Mark it as being a macro that is builtin.
78 MacroInfo *MI = PP.AllocateMacroInfo(SourceLocation());
79 MI->setIsBuiltinMacro();
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +000080 PP.appendDefMacroDirective(Id, MI);
Joao Matos3e1ec722012-08-31 21:34:27 +000081 return Id;
82}
83
84
85/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
86/// identifier table.
87void Preprocessor::RegisterBuiltinMacros() {
88 Ident__LINE__ = RegisterBuiltinMacro(*this, "__LINE__");
89 Ident__FILE__ = RegisterBuiltinMacro(*this, "__FILE__");
90 Ident__DATE__ = RegisterBuiltinMacro(*this, "__DATE__");
91 Ident__TIME__ = RegisterBuiltinMacro(*this, "__TIME__");
92 Ident__COUNTER__ = RegisterBuiltinMacro(*this, "__COUNTER__");
93 Ident_Pragma = RegisterBuiltinMacro(*this, "_Pragma");
94
95 // GCC Extensions.
96 Ident__BASE_FILE__ = RegisterBuiltinMacro(*this, "__BASE_FILE__");
97 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro(*this, "__INCLUDE_LEVEL__");
98 Ident__TIMESTAMP__ = RegisterBuiltinMacro(*this, "__TIMESTAMP__");
99
100 // Clang Extensions.
101 Ident__has_feature = RegisterBuiltinMacro(*this, "__has_feature");
102 Ident__has_extension = RegisterBuiltinMacro(*this, "__has_extension");
103 Ident__has_builtin = RegisterBuiltinMacro(*this, "__has_builtin");
104 Ident__has_attribute = RegisterBuiltinMacro(*this, "__has_attribute");
105 Ident__has_include = RegisterBuiltinMacro(*this, "__has_include");
106 Ident__has_include_next = RegisterBuiltinMacro(*this, "__has_include_next");
107 Ident__has_warning = RegisterBuiltinMacro(*this, "__has_warning");
108
Douglas Gregorb09de512012-09-25 15:44:52 +0000109 // Modules.
110 if (LangOpts.Modules) {
111 Ident__building_module = RegisterBuiltinMacro(*this, "__building_module");
112
113 // __MODULE__
114 if (!LangOpts.CurrentModule.empty())
115 Ident__MODULE__ = RegisterBuiltinMacro(*this, "__MODULE__");
116 else
117 Ident__MODULE__ = 0;
118 } else {
119 Ident__building_module = 0;
120 Ident__MODULE__ = 0;
121 }
122
Joao Matos3e1ec722012-08-31 21:34:27 +0000123 // Microsoft Extensions.
124 if (LangOpts.MicrosoftExt)
125 Ident__pragma = RegisterBuiltinMacro(*this, "__pragma");
126 else
127 Ident__pragma = 0;
128}
129
130/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
131/// in its expansion, currently expands to that token literally.
132static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
133 const IdentifierInfo *MacroIdent,
134 Preprocessor &PP) {
135 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
136
137 // If the token isn't an identifier, it's always literally expanded.
138 if (II == 0) return true;
139
140 // If the information about this identifier is out of date, update it from
141 // the external source.
142 if (II->isOutOfDate())
143 PP.getExternalSource()->updateOutOfDateIdentifier(*II);
144
145 // If the identifier is a macro, and if that macro is enabled, it may be
146 // expanded so it's not a trivial expansion.
147 if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled() &&
148 // Fast expanding "#define X X" is ok, because X would be disabled.
149 II != MacroIdent)
150 return false;
151
152 // If this is an object-like macro invocation, it is safe to trivially expand
153 // it.
154 if (MI->isObjectLike()) return true;
155
156 // If this is a function-like macro invocation, it's safe to trivially expand
157 // as long as the identifier is not a macro argument.
158 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
159 I != E; ++I)
160 if (*I == II)
161 return false; // Identifier is a macro argument.
162
163 return true;
164}
165
166
167/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
168/// lexed is a '('. If so, consume the token and return true, if not, this
169/// method should have no observable side-effect on the lexed tokens.
170bool Preprocessor::isNextPPTokenLParen() {
171 // Do some quick tests for rejection cases.
172 unsigned Val;
173 if (CurLexer)
174 Val = CurLexer->isNextPPTokenLParen();
175 else if (CurPTHLexer)
176 Val = CurPTHLexer->isNextPPTokenLParen();
177 else
178 Val = CurTokenLexer->isNextTokenLParen();
179
180 if (Val == 2) {
181 // We have run off the end. If it's a source file we don't
182 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the
183 // macro stack.
184 if (CurPPLexer)
185 return false;
186 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
187 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
188 if (Entry.TheLexer)
189 Val = Entry.TheLexer->isNextPPTokenLParen();
190 else if (Entry.ThePTHLexer)
191 Val = Entry.ThePTHLexer->isNextPPTokenLParen();
192 else
193 Val = Entry.TheTokenLexer->isNextTokenLParen();
194
195 if (Val != 2)
196 break;
197
198 // Ran off the end of a source file?
199 if (Entry.ThePPLexer)
200 return false;
201 }
202 }
203
204 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
205 // have found something that isn't a '(' or we found the end of the
206 // translation unit. In either case, return false.
207 return Val == 1;
208}
209
210/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
211/// expanded as a macro, handle it and return the next token as 'Identifier'.
212bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
Argyrios Kyrtzidisc5159782013-02-24 00:05:14 +0000213 MacroDirective *MD) {
Argyrios Kyrtzidis35803282013-03-27 01:25:19 +0000214 MacroDirective::DefInfo Def = MD->getDefinition();
215 assert(Def.isValid());
216 MacroInfo *MI = Def.getMacroInfo();
Argyrios Kyrtzidisc5159782013-02-24 00:05:14 +0000217
Joao Matos3e1ec722012-08-31 21:34:27 +0000218 // If this is a macro expansion in the "#if !defined(x)" line for the file,
219 // then the macro could expand to different things in other contexts, we need
220 // to disable the optimization in this case.
221 if (CurPPLexer) CurPPLexer->MIOpt.ExpandedMacro();
222
223 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
224 if (MI->isBuiltinMacro()) {
Argyrios Kyrtzidisc5159782013-02-24 00:05:14 +0000225 if (Callbacks) Callbacks->MacroExpands(Identifier, MD,
Argyrios Kyrtzidisdd08a0c2013-05-03 22:31:32 +0000226 Identifier.getLocation(),/*Args=*/0);
Joao Matos3e1ec722012-08-31 21:34:27 +0000227 ExpandBuiltinMacro(Identifier);
228 return false;
229 }
230
231 /// Args - If this is a function-like macro expansion, this contains,
232 /// for each macro argument, the list of tokens that were provided to the
233 /// invocation.
234 MacroArgs *Args = 0;
235
236 // Remember where the end of the expansion occurred. For an object-like
237 // macro, this is the identifier. For a function-like macro, this is the ')'.
238 SourceLocation ExpansionEnd = Identifier.getLocation();
239
240 // If this is a function-like macro, read the arguments.
241 if (MI->isFunctionLike()) {
242 // C99 6.10.3p10: If the preprocessing token immediately after the macro
243 // name isn't a '(', this macro should not be expanded.
244 if (!isNextPPTokenLParen())
245 return true;
246
247 // Remember that we are now parsing the arguments to a macro invocation.
248 // Preprocessor directives used inside macro arguments are not portable, and
249 // this enables the warning.
250 InMacroArgs = true;
251 Args = ReadFunctionLikeMacroArgs(Identifier, MI, ExpansionEnd);
252
253 // Finished parsing args.
254 InMacroArgs = false;
255
256 // If there was an error parsing the arguments, bail out.
257 if (Args == 0) return false;
258
259 ++NumFnMacroExpanded;
260 } else {
261 ++NumMacroExpanded;
262 }
263
264 // Notice that this macro has been used.
265 markMacroAsUsed(MI);
266
267 // Remember where the token is expanded.
268 SourceLocation ExpandLoc = Identifier.getLocation();
269 SourceRange ExpansionRange(ExpandLoc, ExpansionEnd);
270
271 if (Callbacks) {
272 if (InMacroArgs) {
273 // We can have macro expansion inside a conditional directive while
274 // reading the function macro arguments. To ensure, in that case, that
275 // MacroExpands callbacks still happen in source order, queue this
276 // callback to have it happen after the function macro callback.
277 DelayedMacroExpandsCallbacks.push_back(
Argyrios Kyrtzidisc5159782013-02-24 00:05:14 +0000278 MacroExpandsInfo(Identifier, MD, ExpansionRange));
Joao Matos3e1ec722012-08-31 21:34:27 +0000279 } else {
Argyrios Kyrtzidisdd08a0c2013-05-03 22:31:32 +0000280 Callbacks->MacroExpands(Identifier, MD, ExpansionRange, Args);
Joao Matos3e1ec722012-08-31 21:34:27 +0000281 if (!DelayedMacroExpandsCallbacks.empty()) {
282 for (unsigned i=0, e = DelayedMacroExpandsCallbacks.size(); i!=e; ++i) {
283 MacroExpandsInfo &Info = DelayedMacroExpandsCallbacks[i];
Argyrios Kyrtzidisdd08a0c2013-05-03 22:31:32 +0000284 // FIXME: We lose macro args info with delayed callback.
285 Callbacks->MacroExpands(Info.Tok, Info.MD, Info.Range, /*Args=*/0);
Joao Matos3e1ec722012-08-31 21:34:27 +0000286 }
287 DelayedMacroExpandsCallbacks.clear();
288 }
289 }
290 }
Douglas Gregore8219a62012-10-11 21:07:39 +0000291
292 // If the macro definition is ambiguous, complain.
Argyrios Kyrtzidis35803282013-03-27 01:25:19 +0000293 if (Def.getDirective()->isAmbiguous()) {
Douglas Gregore8219a62012-10-11 21:07:39 +0000294 Diag(Identifier, diag::warn_pp_ambiguous_macro)
295 << Identifier.getIdentifierInfo();
296 Diag(MI->getDefinitionLoc(), diag::note_pp_ambiguous_macro_chosen)
297 << Identifier.getIdentifierInfo();
Argyrios Kyrtzidis35803282013-03-27 01:25:19 +0000298 for (MacroDirective::DefInfo PrevDef = Def.getPreviousDefinition();
299 PrevDef && !PrevDef.isUndefined();
300 PrevDef = PrevDef.getPreviousDefinition()) {
301 if (PrevDef.getDirective()->isAmbiguous()) {
302 Diag(PrevDef.getMacroInfo()->getDefinitionLoc(),
303 diag::note_pp_ambiguous_macro_other)
Douglas Gregore8219a62012-10-11 21:07:39 +0000304 << Identifier.getIdentifierInfo();
305 }
306 }
307 }
308
Joao Matos3e1ec722012-08-31 21:34:27 +0000309 // If we started lexing a macro, enter the macro expansion body.
310
311 // If this macro expands to no tokens, don't bother to push it onto the
312 // expansion stack, only to take it right back off.
313 if (MI->getNumTokens() == 0) {
314 // No need for arg info.
315 if (Args) Args->destroy(*this);
316
317 // Ignore this macro use, just return the next token in the current
318 // buffer.
319 bool HadLeadingSpace = Identifier.hasLeadingSpace();
320 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
321
322 Lex(Identifier);
323
324 // If the identifier isn't on some OTHER line, inherit the leading
325 // whitespace/first-on-a-line property of this token. This handles
326 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
327 // empty.
328 if (!Identifier.isAtStartOfLine()) {
329 if (IsAtStartOfLine) Identifier.setFlag(Token::StartOfLine);
330 if (HadLeadingSpace) Identifier.setFlag(Token::LeadingSpace);
331 }
332 Identifier.setFlag(Token::LeadingEmptyMacro);
333 ++NumFastMacroExpanded;
334 return false;
335
336 } else if (MI->getNumTokens() == 1 &&
337 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
338 *this)) {
339 // Otherwise, if this macro expands into a single trivially-expanded
340 // token: expand it now. This handles common cases like
341 // "#define VAL 42".
342
343 // No need for arg info.
344 if (Args) Args->destroy(*this);
345
346 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
347 // identifier to the expanded token.
348 bool isAtStartOfLine = Identifier.isAtStartOfLine();
349 bool hasLeadingSpace = Identifier.hasLeadingSpace();
350
351 // Replace the result token.
352 Identifier = MI->getReplacementToken(0);
353
354 // Restore the StartOfLine/LeadingSpace markers.
355 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
356 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
357
358 // Update the tokens location to include both its expansion and physical
359 // locations.
360 SourceLocation Loc =
361 SourceMgr.createExpansionLoc(Identifier.getLocation(), ExpandLoc,
362 ExpansionEnd,Identifier.getLength());
363 Identifier.setLocation(Loc);
364
365 // If this is a disabled macro or #define X X, we must mark the result as
366 // unexpandable.
367 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo()) {
368 if (MacroInfo *NewMI = getMacroInfo(NewII))
369 if (!NewMI->isEnabled() || NewMI == MI) {
370 Identifier.setFlag(Token::DisableExpand);
Douglas Gregor40f56e52013-01-30 23:10:17 +0000371 // Don't warn for "#define X X" like "#define bool bool" from
372 // stdbool.h.
373 if (NewMI != MI || MI->isFunctionLike())
374 Diag(Identifier, diag::pp_disabled_macro_expansion);
Joao Matos3e1ec722012-08-31 21:34:27 +0000375 }
376 }
377
378 // Since this is not an identifier token, it can't be macro expanded, so
379 // we're done.
380 ++NumFastMacroExpanded;
381 return false;
382 }
383
384 // Start expanding the macro.
385 EnterMacro(Identifier, ExpansionEnd, MI, Args);
386
387 // Now that the macro is at the top of the include stack, ask the
388 // preprocessor to read the next token from it.
389 Lex(Identifier);
390 return false;
391}
392
393/// ReadFunctionLikeMacroArgs - After reading "MACRO" and knowing that the next
394/// token is the '(' of the macro, this method is invoked to read all of the
395/// actual arguments specified for the macro invocation. This returns null on
396/// error.
397MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
398 MacroInfo *MI,
399 SourceLocation &MacroEnd) {
400 // The number of fixed arguments to parse.
401 unsigned NumFixedArgsLeft = MI->getNumArgs();
402 bool isVariadic = MI->isVariadic();
403
404 // Outer loop, while there are more arguments, keep reading them.
405 Token Tok;
406
407 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
408 // an argument value in a macro could expand to ',' or '(' or ')'.
409 LexUnexpandedToken(Tok);
410 assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
411
412 // ArgTokens - Build up a list of tokens that make up each argument. Each
413 // argument is separated by an EOF token. Use a SmallVector so we can avoid
414 // heap allocations in the common case.
415 SmallVector<Token, 64> ArgTokens;
Argyrios Kyrtzidiscd0fd182012-12-21 01:17:20 +0000416 bool ContainsCodeCompletionTok = false;
Joao Matos3e1ec722012-08-31 21:34:27 +0000417
418 unsigned NumActuals = 0;
419 while (Tok.isNot(tok::r_paren)) {
Argyrios Kyrtzidiscd0fd182012-12-21 01:17:20 +0000420 if (ContainsCodeCompletionTok && (Tok.is(tok::eof) || Tok.is(tok::eod)))
421 break;
422
Joao Matos3e1ec722012-08-31 21:34:27 +0000423 assert((Tok.is(tok::l_paren) || Tok.is(tok::comma)) &&
424 "only expect argument separators here");
425
426 unsigned ArgTokenStart = ArgTokens.size();
427 SourceLocation ArgStartLoc = Tok.getLocation();
428
429 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
430 // that we already consumed the first one.
431 unsigned NumParens = 0;
432
433 while (1) {
434 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
435 // an argument value in a macro could expand to ',' or '(' or ')'.
436 LexUnexpandedToken(Tok);
437
438 if (Tok.is(tok::eof) || Tok.is(tok::eod)) { // "#if f(<eof>" & "#if f(\n"
Argyrios Kyrtzidiscd0fd182012-12-21 01:17:20 +0000439 if (!ContainsCodeCompletionTok) {
440 Diag(MacroName, diag::err_unterm_macro_invoc);
441 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
442 << MacroName.getIdentifierInfo();
443 // Do not lose the EOF/EOD. Return it to the client.
444 MacroName = Tok;
445 return 0;
446 } else {
Argyrios Kyrtzidisbb06b502012-12-22 04:48:10 +0000447 // Do not lose the EOF/EOD.
448 Token *Toks = new Token[1];
449 Toks[0] = Tok;
450 EnterTokenStream(Toks, 1, true, true);
Argyrios Kyrtzidiscd0fd182012-12-21 01:17:20 +0000451 break;
452 }
Joao Matos3e1ec722012-08-31 21:34:27 +0000453 } else if (Tok.is(tok::r_paren)) {
454 // If we found the ) token, the macro arg list is done.
455 if (NumParens-- == 0) {
456 MacroEnd = Tok.getLocation();
457 break;
458 }
459 } else if (Tok.is(tok::l_paren)) {
460 ++NumParens;
Reid Kleckner11be0642013-06-26 17:16:08 +0000461 } else if (Tok.is(tok::comma) && NumParens == 0 &&
462 !(Tok.getFlags() & Token::IgnoredComma)) {
463 // In Microsoft-compatibility mode, single commas from nested macro
464 // expansions should not be considered as argument separators. We test
465 // for this with the IgnoredComma token flag above.
466
Joao Matos3e1ec722012-08-31 21:34:27 +0000467 // Comma ends this argument if there are more fixed arguments expected.
468 // However, if this is a variadic macro, and this is part of the
469 // variadic part, then the comma is just an argument token.
470 if (!isVariadic) break;
471 if (NumFixedArgsLeft > 1)
472 break;
473 } else if (Tok.is(tok::comment) && !KeepMacroComments) {
474 // If this is a comment token in the argument list and we're just in
475 // -C mode (not -CC mode), discard the comment.
476 continue;
477 } else if (Tok.getIdentifierInfo() != 0) {
478 // Reading macro arguments can cause macros that we are currently
479 // expanding from to be popped off the expansion stack. Doing so causes
480 // them to be reenabled for expansion. Here we record whether any
481 // identifiers we lex as macro arguments correspond to disabled macros.
482 // If so, we mark the token as noexpand. This is a subtle aspect of
483 // C99 6.10.3.4p2.
484 if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
485 if (!MI->isEnabled())
486 Tok.setFlag(Token::DisableExpand);
487 } else if (Tok.is(tok::code_completion)) {
Argyrios Kyrtzidiscd0fd182012-12-21 01:17:20 +0000488 ContainsCodeCompletionTok = true;
Joao Matos3e1ec722012-08-31 21:34:27 +0000489 if (CodeComplete)
490 CodeComplete->CodeCompleteMacroArgument(MacroName.getIdentifierInfo(),
491 MI, NumActuals);
492 // Don't mark that we reached the code-completion point because the
493 // parser is going to handle the token and there will be another
494 // code-completion callback.
495 }
496
497 ArgTokens.push_back(Tok);
498 }
499
500 // If this was an empty argument list foo(), don't add this as an empty
501 // argument.
502 if (ArgTokens.empty() && Tok.getKind() == tok::r_paren)
503 break;
504
505 // If this is not a variadic macro, and too many args were specified, emit
506 // an error.
507 if (!isVariadic && NumFixedArgsLeft == 0) {
508 if (ArgTokens.size() != ArgTokenStart)
509 ArgStartLoc = ArgTokens[ArgTokenStart].getLocation();
510
Argyrios Kyrtzidiscd0fd182012-12-21 01:17:20 +0000511 if (!ContainsCodeCompletionTok) {
512 // Emit the diagnostic at the macro name in case there is a missing ).
513 // Emitting it at the , could be far away from the macro name.
514 Diag(ArgStartLoc, diag::err_too_many_args_in_macro_invoc);
515 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
516 << MacroName.getIdentifierInfo();
517 return 0;
518 }
Joao Matos3e1ec722012-08-31 21:34:27 +0000519 }
520
521 // Empty arguments are standard in C99 and C++0x, and are supported as an extension in
522 // other modes.
523 if (ArgTokens.size() == ArgTokenStart && !LangOpts.C99)
Richard Smith80ad52f2013-01-02 11:42:31 +0000524 Diag(Tok, LangOpts.CPlusPlus11 ?
Joao Matos3e1ec722012-08-31 21:34:27 +0000525 diag::warn_cxx98_compat_empty_fnmacro_arg :
526 diag::ext_empty_fnmacro_arg);
527
528 // Add a marker EOF token to the end of the token list for this argument.
529 Token EOFTok;
530 EOFTok.startToken();
531 EOFTok.setKind(tok::eof);
532 EOFTok.setLocation(Tok.getLocation());
533 EOFTok.setLength(0);
534 ArgTokens.push_back(EOFTok);
535 ++NumActuals;
Argyrios Kyrtzidisfdf57062013-02-22 22:28:58 +0000536 if (!ContainsCodeCompletionTok || NumFixedArgsLeft != 0) {
537 assert(NumFixedArgsLeft != 0 && "Too many arguments parsed");
538 --NumFixedArgsLeft;
539 }
Joao Matos3e1ec722012-08-31 21:34:27 +0000540 }
541
542 // Okay, we either found the r_paren. Check to see if we parsed too few
543 // arguments.
544 unsigned MinArgsExpected = MI->getNumArgs();
545
546 // See MacroArgs instance var for description of this.
547 bool isVarargsElided = false;
548
Argyrios Kyrtzidisf1e5b152012-12-21 01:51:12 +0000549 if (ContainsCodeCompletionTok) {
550 // Recover from not-fully-formed macro invocation during code-completion.
551 Token EOFTok;
552 EOFTok.startToken();
553 EOFTok.setKind(tok::eof);
554 EOFTok.setLocation(Tok.getLocation());
555 EOFTok.setLength(0);
556 for (; NumActuals < MinArgsExpected; ++NumActuals)
557 ArgTokens.push_back(EOFTok);
558 }
559
Joao Matos3e1ec722012-08-31 21:34:27 +0000560 if (NumActuals < MinArgsExpected) {
561 // There are several cases where too few arguments is ok, handle them now.
562 if (NumActuals == 0 && MinArgsExpected == 1) {
563 // #define A(X) or #define A(...) ---> A()
564
565 // If there is exactly one argument, and that argument is missing,
566 // then we have an empty "()" argument empty list. This is fine, even if
567 // the macro expects one argument (the argument is just empty).
568 isVarargsElided = MI->isVariadic();
569 } else if (MI->isVariadic() &&
570 (NumActuals+1 == MinArgsExpected || // A(x, ...) -> A(X)
571 (NumActuals == 0 && MinArgsExpected == 2))) {// A(x,...) -> A()
572 // Varargs where the named vararg parameter is missing: OK as extension.
573 // #define A(x, ...)
574 // A("blah")
Eli Friedman4fa4b482012-11-14 02:18:46 +0000575 //
576 // If the macro contains the comma pasting extension, the diagnostic
577 // is suppressed; we know we'll get another diagnostic later.
578 if (!MI->hasCommaPasting()) {
579 Diag(Tok, diag::ext_missing_varargs_arg);
580 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
581 << MacroName.getIdentifierInfo();
582 }
Joao Matos3e1ec722012-08-31 21:34:27 +0000583
584 // Remember this occurred, allowing us to elide the comma when used for
585 // cases like:
586 // #define A(x, foo...) blah(a, ## foo)
587 // #define B(x, ...) blah(a, ## __VA_ARGS__)
588 // #define C(...) blah(a, ## __VA_ARGS__)
589 // A(x) B(x) C()
590 isVarargsElided = true;
Argyrios Kyrtzidiscd0fd182012-12-21 01:17:20 +0000591 } else if (!ContainsCodeCompletionTok) {
Joao Matos3e1ec722012-08-31 21:34:27 +0000592 // Otherwise, emit the error.
593 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
Argyrios Kyrtzidis0ee8de72012-12-14 18:53:47 +0000594 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
595 << MacroName.getIdentifierInfo();
Joao Matos3e1ec722012-08-31 21:34:27 +0000596 return 0;
597 }
598
599 // Add a marker EOF token to the end of the token list for this argument.
600 SourceLocation EndLoc = Tok.getLocation();
601 Tok.startToken();
602 Tok.setKind(tok::eof);
603 Tok.setLocation(EndLoc);
604 Tok.setLength(0);
605 ArgTokens.push_back(Tok);
606
607 // If we expect two arguments, add both as empty.
608 if (NumActuals == 0 && MinArgsExpected == 2)
609 ArgTokens.push_back(Tok);
610
Argyrios Kyrtzidiscd0fd182012-12-21 01:17:20 +0000611 } else if (NumActuals > MinArgsExpected && !MI->isVariadic() &&
612 !ContainsCodeCompletionTok) {
Joao Matos3e1ec722012-08-31 21:34:27 +0000613 // Emit the diagnostic at the macro name in case there is a missing ).
614 // Emitting it at the , could be far away from the macro name.
615 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
Argyrios Kyrtzidis0ee8de72012-12-14 18:53:47 +0000616 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
617 << MacroName.getIdentifierInfo();
Joao Matos3e1ec722012-08-31 21:34:27 +0000618 return 0;
619 }
620
621 return MacroArgs::create(MI, ArgTokens, isVarargsElided, *this);
622}
623
624/// \brief Keeps macro expanded tokens for TokenLexers.
625//
626/// Works like a stack; a TokenLexer adds the macro expanded tokens that is
627/// going to lex in the cache and when it finishes the tokens are removed
628/// from the end of the cache.
629Token *Preprocessor::cacheMacroExpandedTokens(TokenLexer *tokLexer,
630 ArrayRef<Token> tokens) {
631 assert(tokLexer);
632 if (tokens.empty())
633 return 0;
634
635 size_t newIndex = MacroExpandedTokens.size();
636 bool cacheNeedsToGrow = tokens.size() >
637 MacroExpandedTokens.capacity()-MacroExpandedTokens.size();
638 MacroExpandedTokens.append(tokens.begin(), tokens.end());
639
640 if (cacheNeedsToGrow) {
641 // Go through all the TokenLexers whose 'Tokens' pointer points in the
642 // buffer and update the pointers to the (potential) new buffer array.
643 for (unsigned i = 0, e = MacroExpandingLexersStack.size(); i != e; ++i) {
644 TokenLexer *prevLexer;
645 size_t tokIndex;
646 llvm::tie(prevLexer, tokIndex) = MacroExpandingLexersStack[i];
647 prevLexer->Tokens = MacroExpandedTokens.data() + tokIndex;
648 }
649 }
650
651 MacroExpandingLexersStack.push_back(std::make_pair(tokLexer, newIndex));
652 return MacroExpandedTokens.data() + newIndex;
653}
654
655void Preprocessor::removeCachedMacroExpandedTokensOfLastLexer() {
656 assert(!MacroExpandingLexersStack.empty());
657 size_t tokIndex = MacroExpandingLexersStack.back().second;
658 assert(tokIndex < MacroExpandedTokens.size());
659 // Pop the cached macro expanded tokens from the end.
660 MacroExpandedTokens.resize(tokIndex);
661 MacroExpandingLexersStack.pop_back();
662}
663
664/// ComputeDATE_TIME - Compute the current time, enter it into the specified
665/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
666/// the identifier tokens inserted.
667static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
668 Preprocessor &PP) {
669 time_t TT = time(0);
670 struct tm *TM = localtime(&TT);
671
672 static const char * const Months[] = {
673 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
674 };
675
Dmitri Gribenko33d054b2012-09-24 20:56:28 +0000676 {
677 SmallString<32> TmpBuffer;
678 llvm::raw_svector_ostream TmpStream(TmpBuffer);
679 TmpStream << llvm::format("\"%s %2d %4d\"", Months[TM->tm_mon],
680 TM->tm_mday, TM->tm_year + 1900);
Dmitri Gribenko33d054b2012-09-24 20:56:28 +0000681 Token TmpTok;
682 TmpTok.startToken();
Dmitri Gribenko374b3832012-09-24 21:07:17 +0000683 PP.CreateString(TmpStream.str(), TmpTok);
Dmitri Gribenko33d054b2012-09-24 20:56:28 +0000684 DATELoc = TmpTok.getLocation();
685 }
Joao Matos3e1ec722012-08-31 21:34:27 +0000686
Dmitri Gribenko33d054b2012-09-24 20:56:28 +0000687 {
688 SmallString<32> TmpBuffer;
689 llvm::raw_svector_ostream TmpStream(TmpBuffer);
690 TmpStream << llvm::format("\"%02d:%02d:%02d\"",
691 TM->tm_hour, TM->tm_min, TM->tm_sec);
Dmitri Gribenko33d054b2012-09-24 20:56:28 +0000692 Token TmpTok;
693 TmpTok.startToken();
Dmitri Gribenko374b3832012-09-24 21:07:17 +0000694 PP.CreateString(TmpStream.str(), TmpTok);
Dmitri Gribenko33d054b2012-09-24 20:56:28 +0000695 TIMELoc = TmpTok.getLocation();
696 }
Joao Matos3e1ec722012-08-31 21:34:27 +0000697}
698
699
700/// HasFeature - Return true if we recognize and implement the feature
701/// specified by the identifier as a standard language feature.
702static bool HasFeature(const Preprocessor &PP, const IdentifierInfo *II) {
703 const LangOptions &LangOpts = PP.getLangOpts();
704 StringRef Feature = II->getName();
705
706 // Normalize the feature name, __foo__ becomes foo.
707 if (Feature.startswith("__") && Feature.endswith("__") && Feature.size() >= 4)
708 Feature = Feature.substr(2, Feature.size() - 4);
709
710 return llvm::StringSwitch<bool>(Feature)
Will Dietz4f45bc02013-01-18 11:30:38 +0000711 .Case("address_sanitizer", LangOpts.Sanitize.Address)
Joao Matos3e1ec722012-08-31 21:34:27 +0000712 .Case("attribute_analyzer_noreturn", true)
713 .Case("attribute_availability", true)
714 .Case("attribute_availability_with_message", true)
715 .Case("attribute_cf_returns_not_retained", true)
716 .Case("attribute_cf_returns_retained", true)
717 .Case("attribute_deprecated_with_message", true)
718 .Case("attribute_ext_vector_type", true)
719 .Case("attribute_ns_returns_not_retained", true)
720 .Case("attribute_ns_returns_retained", true)
721 .Case("attribute_ns_consumes_self", true)
722 .Case("attribute_ns_consumed", true)
723 .Case("attribute_cf_consumed", true)
724 .Case("attribute_objc_ivar_unused", true)
725 .Case("attribute_objc_method_family", true)
726 .Case("attribute_overloadable", true)
727 .Case("attribute_unavailable_with_message", true)
728 .Case("attribute_unused_on_fields", true)
729 .Case("blocks", LangOpts.Blocks)
730 .Case("cxx_exceptions", LangOpts.Exceptions)
731 .Case("cxx_rtti", LangOpts.RTTI)
732 .Case("enumerator_attributes", true)
Will Dietz4f45bc02013-01-18 11:30:38 +0000733 .Case("memory_sanitizer", LangOpts.Sanitize.Memory)
734 .Case("thread_sanitizer", LangOpts.Sanitize.Thread)
Joao Matos3e1ec722012-08-31 21:34:27 +0000735 // Objective-C features
736 .Case("objc_arr", LangOpts.ObjCAutoRefCount) // FIXME: REMOVE?
737 .Case("objc_arc", LangOpts.ObjCAutoRefCount)
738 .Case("objc_arc_weak", LangOpts.ObjCARCWeak)
739 .Case("objc_default_synthesize_properties", LangOpts.ObjC2)
740 .Case("objc_fixed_enum", LangOpts.ObjC2)
741 .Case("objc_instancetype", LangOpts.ObjC2)
742 .Case("objc_modules", LangOpts.ObjC2 && LangOpts.Modules)
743 .Case("objc_nonfragile_abi", LangOpts.ObjCRuntime.isNonFragile())
Ted Kremeneke4057c22013-01-04 19:04:44 +0000744 .Case("objc_property_explicit_atomic", true) // Does clang support explicit "atomic" keyword?
Joao Matos3e1ec722012-08-31 21:34:27 +0000745 .Case("objc_weak_class", LangOpts.ObjCRuntime.hasWeakClassImport())
746 .Case("ownership_holds", true)
747 .Case("ownership_returns", true)
748 .Case("ownership_takes", true)
749 .Case("objc_bool", true)
750 .Case("objc_subscripting", LangOpts.ObjCRuntime.isNonFragile())
751 .Case("objc_array_literals", LangOpts.ObjC2)
752 .Case("objc_dictionary_literals", LangOpts.ObjC2)
753 .Case("objc_boxed_expressions", LangOpts.ObjC2)
754 .Case("arc_cf_code_audited", true)
755 // C11 features
756 .Case("c_alignas", LangOpts.C11)
757 .Case("c_atomic", LangOpts.C11)
758 .Case("c_generic_selections", LangOpts.C11)
759 .Case("c_static_assert", LangOpts.C11)
Douglas Gregore87c5bd2013-05-02 05:28:32 +0000760 .Case("c_thread_local",
761 LangOpts.C11 && PP.getTargetInfo().isTLSSupported())
Joao Matos3e1ec722012-08-31 21:34:27 +0000762 // C++11 features
Richard Smith80ad52f2013-01-02 11:42:31 +0000763 .Case("cxx_access_control_sfinae", LangOpts.CPlusPlus11)
764 .Case("cxx_alias_templates", LangOpts.CPlusPlus11)
765 .Case("cxx_alignas", LangOpts.CPlusPlus11)
766 .Case("cxx_atomic", LangOpts.CPlusPlus11)
767 .Case("cxx_attributes", LangOpts.CPlusPlus11)
768 .Case("cxx_auto_type", LangOpts.CPlusPlus11)
769 .Case("cxx_constexpr", LangOpts.CPlusPlus11)
770 .Case("cxx_decltype", LangOpts.CPlusPlus11)
771 .Case("cxx_decltype_incomplete_return_types", LangOpts.CPlusPlus11)
772 .Case("cxx_default_function_template_args", LangOpts.CPlusPlus11)
773 .Case("cxx_defaulted_functions", LangOpts.CPlusPlus11)
774 .Case("cxx_delegating_constructors", LangOpts.CPlusPlus11)
775 .Case("cxx_deleted_functions", LangOpts.CPlusPlus11)
776 .Case("cxx_explicit_conversions", LangOpts.CPlusPlus11)
777 .Case("cxx_generalized_initializers", LangOpts.CPlusPlus11)
778 .Case("cxx_implicit_moves", LangOpts.CPlusPlus11)
Richard Smithe6e68b52013-04-19 17:00:31 +0000779 .Case("cxx_inheriting_constructors", LangOpts.CPlusPlus11)
Richard Smith80ad52f2013-01-02 11:42:31 +0000780 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus11)
781 .Case("cxx_lambdas", LangOpts.CPlusPlus11)
782 .Case("cxx_local_type_template_args", LangOpts.CPlusPlus11)
783 .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus11)
784 .Case("cxx_noexcept", LangOpts.CPlusPlus11)
785 .Case("cxx_nullptr", LangOpts.CPlusPlus11)
786 .Case("cxx_override_control", LangOpts.CPlusPlus11)
787 .Case("cxx_range_for", LangOpts.CPlusPlus11)
788 .Case("cxx_raw_string_literals", LangOpts.CPlusPlus11)
789 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus11)
790 .Case("cxx_rvalue_references", LangOpts.CPlusPlus11)
791 .Case("cxx_strong_enums", LangOpts.CPlusPlus11)
792 .Case("cxx_static_assert", LangOpts.CPlusPlus11)
Douglas Gregore87c5bd2013-05-02 05:28:32 +0000793 .Case("cxx_thread_local",
794 LangOpts.CPlusPlus11 && PP.getTargetInfo().isTLSSupported())
Richard Smith80ad52f2013-01-02 11:42:31 +0000795 .Case("cxx_trailing_return", LangOpts.CPlusPlus11)
796 .Case("cxx_unicode_literals", LangOpts.CPlusPlus11)
797 .Case("cxx_unrestricted_unions", LangOpts.CPlusPlus11)
798 .Case("cxx_user_literals", LangOpts.CPlusPlus11)
799 .Case("cxx_variadic_templates", LangOpts.CPlusPlus11)
Richard Smith7f0ffb32013-05-07 19:32:56 +0000800 // C++1y features
801 .Case("cxx_binary_literals", LangOpts.CPlusPlus1y)
802 //.Case("cxx_contextual_conversions", LangOpts.CPlusPlus1y)
803 //.Case("cxx_generalized_capture", LangOpts.CPlusPlus1y)
804 //.Case("cxx_generic_lambda", LangOpts.CPlusPlus1y)
805 //.Case("cxx_relaxed_constexpr", LangOpts.CPlusPlus1y)
Richard Smithf45c2992013-05-12 03:09:35 +0000806 .Case("cxx_return_type_deduction", LangOpts.CPlusPlus1y)
Richard Smith7f0ffb32013-05-07 19:32:56 +0000807 //.Case("cxx_runtime_array", LangOpts.CPlusPlus1y)
808 .Case("cxx_aggregate_nsdmi", LangOpts.CPlusPlus1y)
809 //.Case("cxx_variable_templates", LangOpts.CPlusPlus1y)
Joao Matos3e1ec722012-08-31 21:34:27 +0000810 // Type traits
811 .Case("has_nothrow_assign", LangOpts.CPlusPlus)
812 .Case("has_nothrow_copy", LangOpts.CPlusPlus)
813 .Case("has_nothrow_constructor", LangOpts.CPlusPlus)
814 .Case("has_trivial_assign", LangOpts.CPlusPlus)
815 .Case("has_trivial_copy", LangOpts.CPlusPlus)
816 .Case("has_trivial_constructor", LangOpts.CPlusPlus)
817 .Case("has_trivial_destructor", LangOpts.CPlusPlus)
818 .Case("has_virtual_destructor", LangOpts.CPlusPlus)
819 .Case("is_abstract", LangOpts.CPlusPlus)
820 .Case("is_base_of", LangOpts.CPlusPlus)
821 .Case("is_class", LangOpts.CPlusPlus)
822 .Case("is_convertible_to", LangOpts.CPlusPlus)
Joao Matos3e1ec722012-08-31 21:34:27 +0000823 .Case("is_empty", LangOpts.CPlusPlus)
824 .Case("is_enum", LangOpts.CPlusPlus)
825 .Case("is_final", LangOpts.CPlusPlus)
826 .Case("is_literal", LangOpts.CPlusPlus)
827 .Case("is_standard_layout", LangOpts.CPlusPlus)
828 .Case("is_pod", LangOpts.CPlusPlus)
829 .Case("is_polymorphic", LangOpts.CPlusPlus)
830 .Case("is_trivial", LangOpts.CPlusPlus)
831 .Case("is_trivially_assignable", LangOpts.CPlusPlus)
832 .Case("is_trivially_constructible", LangOpts.CPlusPlus)
833 .Case("is_trivially_copyable", LangOpts.CPlusPlus)
834 .Case("is_union", LangOpts.CPlusPlus)
835 .Case("modules", LangOpts.Modules)
836 .Case("tls", PP.getTargetInfo().isTLSSupported())
837 .Case("underlying_type", LangOpts.CPlusPlus)
838 .Default(false);
839}
840
841/// HasExtension - Return true if we recognize and implement the feature
842/// specified by the identifier, either as an extension or a standard language
843/// feature.
844static bool HasExtension(const Preprocessor &PP, const IdentifierInfo *II) {
845 if (HasFeature(PP, II))
846 return true;
847
848 // If the use of an extension results in an error diagnostic, extensions are
849 // effectively unavailable, so just return false here.
850 if (PP.getDiagnostics().getExtensionHandlingBehavior() ==
851 DiagnosticsEngine::Ext_Error)
852 return false;
853
854 const LangOptions &LangOpts = PP.getLangOpts();
855 StringRef Extension = II->getName();
856
857 // Normalize the extension name, __foo__ becomes foo.
858 if (Extension.startswith("__") && Extension.endswith("__") &&
859 Extension.size() >= 4)
860 Extension = Extension.substr(2, Extension.size() - 4);
861
862 // Because we inherit the feature list from HasFeature, this string switch
863 // must be less restrictive than HasFeature's.
864 return llvm::StringSwitch<bool>(Extension)
865 // C11 features supported by other languages as extensions.
866 .Case("c_alignas", true)
867 .Case("c_atomic", true)
868 .Case("c_generic_selections", true)
869 .Case("c_static_assert", true)
Richard Smith7f0ffb32013-05-07 19:32:56 +0000870 // C++11 features supported by other languages as extensions.
Joao Matos3e1ec722012-08-31 21:34:27 +0000871 .Case("cxx_atomic", LangOpts.CPlusPlus)
872 .Case("cxx_deleted_functions", LangOpts.CPlusPlus)
873 .Case("cxx_explicit_conversions", LangOpts.CPlusPlus)
874 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus)
875 .Case("cxx_local_type_template_args", LangOpts.CPlusPlus)
876 .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus)
877 .Case("cxx_override_control", LangOpts.CPlusPlus)
878 .Case("cxx_range_for", LangOpts.CPlusPlus)
879 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus)
880 .Case("cxx_rvalue_references", LangOpts.CPlusPlus)
Richard Smith7f0ffb32013-05-07 19:32:56 +0000881 // C++1y features supported by other languages as extensions.
882 .Case("cxx_binary_literals", true)
Joao Matos3e1ec722012-08-31 21:34:27 +0000883 .Default(false);
884}
885
886/// HasAttribute - Return true if we recognize and implement the attribute
887/// specified by the given identifier.
888static bool HasAttribute(const IdentifierInfo *II) {
889 StringRef Name = II->getName();
890 // Normalize the attribute name, __foo__ becomes foo.
891 if (Name.startswith("__") && Name.endswith("__") && Name.size() >= 4)
892 Name = Name.substr(2, Name.size() - 4);
893
894 // FIXME: Do we need to handle namespaces here?
895 return llvm::StringSwitch<bool>(Name)
896#include "clang/Lex/AttrSpellings.inc"
897 .Default(false);
898}
899
900/// EvaluateHasIncludeCommon - Process a '__has_include("path")'
901/// or '__has_include_next("path")' expression.
902/// Returns true if successful.
903static bool EvaluateHasIncludeCommon(Token &Tok,
904 IdentifierInfo *II, Preprocessor &PP,
905 const DirectoryLookup *LookupFrom) {
Richard Trieu97bc3d52012-10-22 20:28:48 +0000906 // Save the location of the current token. If a '(' is later found, use
Aaron Ballman6b716c52013-01-15 21:59:46 +0000907 // that location. If not, use the end of this location instead.
Richard Trieu97bc3d52012-10-22 20:28:48 +0000908 SourceLocation LParenLoc = Tok.getLocation();
Joao Matos3e1ec722012-08-31 21:34:27 +0000909
Aaron Ballman31672b12013-01-16 19:32:21 +0000910 // These expressions are only allowed within a preprocessor directive.
911 if (!PP.isParsingIfOrElifDirective()) {
912 PP.Diag(LParenLoc, diag::err_pp_directive_required) << II->getName();
913 return false;
914 }
915
Joao Matos3e1ec722012-08-31 21:34:27 +0000916 // Get '('.
917 PP.LexNonComment(Tok);
918
919 // Ensure we have a '('.
920 if (Tok.isNot(tok::l_paren)) {
Richard Trieu97bc3d52012-10-22 20:28:48 +0000921 // No '(', use end of last token.
922 LParenLoc = PP.getLocForEndOfToken(LParenLoc);
923 PP.Diag(LParenLoc, diag::err_pp_missing_lparen) << II->getName();
924 // If the next token looks like a filename or the start of one,
925 // assume it is and process it as such.
926 if (!Tok.is(tok::angle_string_literal) && !Tok.is(tok::string_literal) &&
927 !Tok.is(tok::less))
928 return false;
929 } else {
930 // Save '(' location for possible missing ')' message.
931 LParenLoc = Tok.getLocation();
932
Eli Friedmana0f2d022013-01-09 02:20:00 +0000933 if (PP.getCurrentLexer()) {
934 // Get the file name.
935 PP.getCurrentLexer()->LexIncludeFilename(Tok);
936 } else {
937 // We're in a macro, so we can't use LexIncludeFilename; just
938 // grab the next token.
939 PP.Lex(Tok);
940 }
Joao Matos3e1ec722012-08-31 21:34:27 +0000941 }
942
Joao Matos3e1ec722012-08-31 21:34:27 +0000943 // Reserve a buffer to get the spelling.
944 SmallString<128> FilenameBuffer;
945 StringRef Filename;
946 SourceLocation EndLoc;
947
948 switch (Tok.getKind()) {
949 case tok::eod:
950 // If the token kind is EOD, the error has already been diagnosed.
951 return false;
952
953 case tok::angle_string_literal:
954 case tok::string_literal: {
955 bool Invalid = false;
956 Filename = PP.getSpelling(Tok, FilenameBuffer, &Invalid);
957 if (Invalid)
958 return false;
959 break;
960 }
961
962 case tok::less:
963 // This could be a <foo/bar.h> file coming from a macro expansion. In this
964 // case, glue the tokens together into FilenameBuffer and interpret those.
965 FilenameBuffer.push_back('<');
Richard Trieu97bc3d52012-10-22 20:28:48 +0000966 if (PP.ConcatenateIncludeName(FilenameBuffer, EndLoc)) {
967 // Let the caller know a <eod> was found by changing the Token kind.
968 Tok.setKind(tok::eod);
Joao Matos3e1ec722012-08-31 21:34:27 +0000969 return false; // Found <eod> but no ">"? Diagnostic already emitted.
Richard Trieu97bc3d52012-10-22 20:28:48 +0000970 }
Joao Matos3e1ec722012-08-31 21:34:27 +0000971 Filename = FilenameBuffer.str();
972 break;
973 default:
974 PP.Diag(Tok.getLocation(), diag::err_pp_expects_filename);
975 return false;
976 }
977
Richard Trieu97bc3d52012-10-22 20:28:48 +0000978 SourceLocation FilenameLoc = Tok.getLocation();
979
Joao Matos3e1ec722012-08-31 21:34:27 +0000980 // Get ')'.
981 PP.LexNonComment(Tok);
982
983 // Ensure we have a trailing ).
984 if (Tok.isNot(tok::r_paren)) {
Richard Trieu97bc3d52012-10-22 20:28:48 +0000985 PP.Diag(PP.getLocForEndOfToken(FilenameLoc), diag::err_pp_missing_rparen)
986 << II->getName();
Joao Matos3e1ec722012-08-31 21:34:27 +0000987 PP.Diag(LParenLoc, diag::note_matching) << "(";
988 return false;
989 }
990
991 bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename);
992 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
993 // error.
994 if (Filename.empty())
995 return false;
996
997 // Search include directories.
998 const DirectoryLookup *CurDir;
999 const FileEntry *File =
Lawrence Crowlbc3f6282013-06-20 21:14:14 +00001000 PP.LookupFile(FilenameLoc, Filename, isAngled, LookupFrom, CurDir, NULL,
1001 NULL, NULL);
Joao Matos3e1ec722012-08-31 21:34:27 +00001002
1003 // Get the result value. A result of true means the file exists.
1004 return File != 0;
1005}
1006
1007/// EvaluateHasInclude - Process a '__has_include("path")' expression.
1008/// Returns true if successful.
1009static bool EvaluateHasInclude(Token &Tok, IdentifierInfo *II,
1010 Preprocessor &PP) {
1011 return EvaluateHasIncludeCommon(Tok, II, PP, NULL);
1012}
1013
1014/// EvaluateHasIncludeNext - Process '__has_include_next("path")' expression.
1015/// Returns true if successful.
1016static bool EvaluateHasIncludeNext(Token &Tok,
1017 IdentifierInfo *II, Preprocessor &PP) {
1018 // __has_include_next is like __has_include, except that we start
1019 // searching after the current found directory. If we can't do this,
1020 // issue a diagnostic.
1021 const DirectoryLookup *Lookup = PP.GetCurDirLookup();
1022 if (PP.isInPrimaryFile()) {
1023 Lookup = 0;
1024 PP.Diag(Tok, diag::pp_include_next_in_primary);
1025 } else if (Lookup == 0) {
1026 PP.Diag(Tok, diag::pp_include_next_absolute_path);
1027 } else {
1028 // Start looking up in the next directory.
1029 ++Lookup;
1030 }
1031
1032 return EvaluateHasIncludeCommon(Tok, II, PP, Lookup);
1033}
1034
Douglas Gregorb09de512012-09-25 15:44:52 +00001035/// \brief Process __building_module(identifier) expression.
1036/// \returns true if we are building the named module, false otherwise.
1037static bool EvaluateBuildingModule(Token &Tok,
1038 IdentifierInfo *II, Preprocessor &PP) {
1039 // Get '('.
1040 PP.LexNonComment(Tok);
1041
1042 // Ensure we have a '('.
1043 if (Tok.isNot(tok::l_paren)) {
1044 PP.Diag(Tok.getLocation(), diag::err_pp_missing_lparen) << II->getName();
1045 return false;
1046 }
1047
1048 // Save '(' location for possible missing ')' message.
1049 SourceLocation LParenLoc = Tok.getLocation();
1050
1051 // Get the module name.
1052 PP.LexNonComment(Tok);
1053
1054 // Ensure that we have an identifier.
1055 if (Tok.isNot(tok::identifier)) {
1056 PP.Diag(Tok.getLocation(), diag::err_expected_id_building_module);
1057 return false;
1058 }
1059
1060 bool Result
1061 = Tok.getIdentifierInfo()->getName() == PP.getLangOpts().CurrentModule;
1062
1063 // Get ')'.
1064 PP.LexNonComment(Tok);
1065
1066 // Ensure we have a trailing ).
1067 if (Tok.isNot(tok::r_paren)) {
1068 PP.Diag(Tok.getLocation(), diag::err_pp_missing_rparen) << II->getName();
1069 PP.Diag(LParenLoc, diag::note_matching) << "(";
1070 return false;
1071 }
1072
1073 return Result;
1074}
1075
Joao Matos3e1ec722012-08-31 21:34:27 +00001076/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
1077/// as a builtin macro, handle it and return the next token as 'Tok'.
1078void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
1079 // Figure out which token this is.
1080 IdentifierInfo *II = Tok.getIdentifierInfo();
1081 assert(II && "Can't be a macro without id info!");
1082
1083 // If this is an _Pragma or Microsoft __pragma directive, expand it,
1084 // invoke the pragma handler, then lex the token after it.
1085 if (II == Ident_Pragma)
1086 return Handle_Pragma(Tok);
1087 else if (II == Ident__pragma) // in non-MS mode this is null
1088 return HandleMicrosoft__pragma(Tok);
1089
1090 ++NumBuiltinMacroExpanded;
1091
1092 SmallString<128> TmpBuffer;
1093 llvm::raw_svector_ostream OS(TmpBuffer);
1094
1095 // Set up the return result.
1096 Tok.setIdentifierInfo(0);
1097 Tok.clearFlag(Token::NeedsCleaning);
1098
1099 if (II == Ident__LINE__) {
1100 // C99 6.10.8: "__LINE__: The presumed line number (within the current
1101 // source file) of the current source line (an integer constant)". This can
1102 // be affected by #line.
1103 SourceLocation Loc = Tok.getLocation();
1104
1105 // Advance to the location of the first _, this might not be the first byte
1106 // of the token if it starts with an escaped newline.
1107 Loc = AdvanceToTokenCharacter(Loc, 0);
1108
1109 // One wrinkle here is that GCC expands __LINE__ to location of the *end* of
1110 // a macro expansion. This doesn't matter for object-like macros, but
1111 // can matter for a function-like macro that expands to contain __LINE__.
1112 // Skip down through expansion points until we find a file loc for the
1113 // end of the expansion history.
1114 Loc = SourceMgr.getExpansionRange(Loc).second;
1115 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc);
1116
1117 // __LINE__ expands to a simple numeric value.
1118 OS << (PLoc.isValid()? PLoc.getLine() : 1);
1119 Tok.setKind(tok::numeric_constant);
1120 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
1121 // C99 6.10.8: "__FILE__: The presumed name of the current source file (a
1122 // character string literal)". This can be affected by #line.
1123 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
1124
1125 // __BASE_FILE__ is a GNU extension that returns the top of the presumed
1126 // #include stack instead of the current file.
1127 if (II == Ident__BASE_FILE__ && PLoc.isValid()) {
1128 SourceLocation NextLoc = PLoc.getIncludeLoc();
1129 while (NextLoc.isValid()) {
1130 PLoc = SourceMgr.getPresumedLoc(NextLoc);
1131 if (PLoc.isInvalid())
1132 break;
1133
1134 NextLoc = PLoc.getIncludeLoc();
1135 }
1136 }
1137
1138 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
1139 SmallString<128> FN;
1140 if (PLoc.isValid()) {
1141 FN += PLoc.getFilename();
1142 Lexer::Stringify(FN);
1143 OS << '"' << FN.str() << '"';
1144 }
1145 Tok.setKind(tok::string_literal);
1146 } else if (II == Ident__DATE__) {
1147 if (!DATELoc.isValid())
1148 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1149 Tok.setKind(tok::string_literal);
1150 Tok.setLength(strlen("\"Mmm dd yyyy\""));
1151 Tok.setLocation(SourceMgr.createExpansionLoc(DATELoc, Tok.getLocation(),
1152 Tok.getLocation(),
1153 Tok.getLength()));
1154 return;
1155 } else if (II == Ident__TIME__) {
1156 if (!TIMELoc.isValid())
1157 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1158 Tok.setKind(tok::string_literal);
1159 Tok.setLength(strlen("\"hh:mm:ss\""));
1160 Tok.setLocation(SourceMgr.createExpansionLoc(TIMELoc, Tok.getLocation(),
1161 Tok.getLocation(),
1162 Tok.getLength()));
1163 return;
1164 } else if (II == Ident__INCLUDE_LEVEL__) {
1165 // Compute the presumed include depth of this token. This can be affected
1166 // by GNU line markers.
1167 unsigned Depth = 0;
1168
1169 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
1170 if (PLoc.isValid()) {
1171 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
1172 for (; PLoc.isValid(); ++Depth)
1173 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
1174 }
1175
1176 // __INCLUDE_LEVEL__ expands to a simple numeric value.
1177 OS << Depth;
1178 Tok.setKind(tok::numeric_constant);
1179 } else if (II == Ident__TIMESTAMP__) {
1180 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
1181 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
1182
1183 // Get the file that we are lexing out of. If we're currently lexing from
1184 // a macro, dig into the include stack.
1185 const FileEntry *CurFile = 0;
1186 PreprocessorLexer *TheLexer = getCurrentFileLexer();
1187
1188 if (TheLexer)
1189 CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID());
1190
1191 const char *Result;
1192 if (CurFile) {
1193 time_t TT = CurFile->getModificationTime();
1194 struct tm *TM = localtime(&TT);
1195 Result = asctime(TM);
1196 } else {
1197 Result = "??? ??? ?? ??:??:?? ????\n";
1198 }
1199 // Surround the string with " and strip the trailing newline.
1200 OS << '"' << StringRef(Result, strlen(Result)-1) << '"';
1201 Tok.setKind(tok::string_literal);
1202 } else if (II == Ident__COUNTER__) {
1203 // __COUNTER__ expands to a simple numeric value.
1204 OS << CounterValue++;
1205 Tok.setKind(tok::numeric_constant);
1206 } else if (II == Ident__has_feature ||
1207 II == Ident__has_extension ||
1208 II == Ident__has_builtin ||
1209 II == Ident__has_attribute) {
1210 // The argument to these builtins should be a parenthesized identifier.
1211 SourceLocation StartLoc = Tok.getLocation();
1212
1213 bool IsValid = false;
1214 IdentifierInfo *FeatureII = 0;
1215
1216 // Read the '('.
Andy Gibbs3f03b582012-11-17 19:18:27 +00001217 LexUnexpandedToken(Tok);
Joao Matos3e1ec722012-08-31 21:34:27 +00001218 if (Tok.is(tok::l_paren)) {
1219 // Read the identifier
Andy Gibbs3f03b582012-11-17 19:18:27 +00001220 LexUnexpandedToken(Tok);
Joao Matos3e1ec722012-08-31 21:34:27 +00001221 if (Tok.is(tok::identifier) || Tok.is(tok::kw_const)) {
1222 FeatureII = Tok.getIdentifierInfo();
1223
1224 // Read the ')'.
Andy Gibbs3f03b582012-11-17 19:18:27 +00001225 LexUnexpandedToken(Tok);
Joao Matos3e1ec722012-08-31 21:34:27 +00001226 if (Tok.is(tok::r_paren))
1227 IsValid = true;
1228 }
1229 }
1230
1231 bool Value = false;
1232 if (!IsValid)
1233 Diag(StartLoc, diag::err_feature_check_malformed);
1234 else if (II == Ident__has_builtin) {
1235 // Check for a builtin is trivial.
1236 Value = FeatureII->getBuiltinID() != 0;
1237 } else if (II == Ident__has_attribute)
1238 Value = HasAttribute(FeatureII);
1239 else if (II == Ident__has_extension)
1240 Value = HasExtension(*this, FeatureII);
1241 else {
1242 assert(II == Ident__has_feature && "Must be feature check");
1243 Value = HasFeature(*this, FeatureII);
1244 }
1245
1246 OS << (int)Value;
1247 if (IsValid)
1248 Tok.setKind(tok::numeric_constant);
1249 } else if (II == Ident__has_include ||
1250 II == Ident__has_include_next) {
1251 // The argument to these two builtins should be a parenthesized
1252 // file name string literal using angle brackets (<>) or
1253 // double-quotes ("").
1254 bool Value;
1255 if (II == Ident__has_include)
1256 Value = EvaluateHasInclude(Tok, II, *this);
1257 else
1258 Value = EvaluateHasIncludeNext(Tok, II, *this);
1259 OS << (int)Value;
Richard Trieu97bc3d52012-10-22 20:28:48 +00001260 if (Tok.is(tok::r_paren))
1261 Tok.setKind(tok::numeric_constant);
Joao Matos3e1ec722012-08-31 21:34:27 +00001262 } else if (II == Ident__has_warning) {
1263 // The argument should be a parenthesized string literal.
1264 // The argument to these builtins should be a parenthesized identifier.
1265 SourceLocation StartLoc = Tok.getLocation();
1266 bool IsValid = false;
1267 bool Value = false;
1268 // Read the '('.
Andy Gibbs02a17682012-11-17 19:15:38 +00001269 LexUnexpandedToken(Tok);
Joao Matos3e1ec722012-08-31 21:34:27 +00001270 do {
Andy Gibbs02a17682012-11-17 19:15:38 +00001271 if (Tok.isNot(tok::l_paren)) {
1272 Diag(StartLoc, diag::err_warning_check_malformed);
1273 break;
Joao Matos3e1ec722012-08-31 21:34:27 +00001274 }
Andy Gibbs02a17682012-11-17 19:15:38 +00001275
1276 LexUnexpandedToken(Tok);
1277 std::string WarningName;
1278 SourceLocation StrStartLoc = Tok.getLocation();
Andy Gibbs97f84612012-11-17 19:16:52 +00001279 if (!FinishLexStringLiteral(Tok, WarningName, "'__has_warning'",
1280 /*MacroExpansion=*/false)) {
Andy Gibbs02a17682012-11-17 19:15:38 +00001281 // Eat tokens until ')'.
Andy Gibbs6d534d42012-11-17 22:17:28 +00001282 while (Tok.isNot(tok::r_paren) && Tok.isNot(tok::eod) &&
1283 Tok.isNot(tok::eof))
Andy Gibbs02a17682012-11-17 19:15:38 +00001284 LexUnexpandedToken(Tok);
1285 break;
1286 }
1287
1288 // Is the end a ')'?
1289 if (!(IsValid = Tok.is(tok::r_paren))) {
1290 Diag(StartLoc, diag::err_warning_check_malformed);
1291 break;
1292 }
1293
1294 if (WarningName.size() < 3 || WarningName[0] != '-' ||
1295 WarningName[1] != 'W') {
1296 Diag(StrStartLoc, diag::warn_has_warning_invalid_option);
1297 break;
1298 }
1299
1300 // Finally, check if the warning flags maps to a diagnostic group.
1301 // We construct a SmallVector here to talk to getDiagnosticIDs().
1302 // Although we don't use the result, this isn't a hot path, and not
1303 // worth special casing.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001304 SmallVector<diag::kind, 10> Diags;
Andy Gibbs02a17682012-11-17 19:15:38 +00001305 Value = !getDiagnostics().getDiagnosticIDs()->
1306 getDiagnosticsInGroup(WarningName.substr(2), Diags);
Joao Matos3e1ec722012-08-31 21:34:27 +00001307 } while (false);
Joao Matos3e1ec722012-08-31 21:34:27 +00001308
1309 OS << (int)Value;
Andy Gibbsb9971ba2012-11-17 19:14:53 +00001310 if (IsValid)
1311 Tok.setKind(tok::numeric_constant);
Douglas Gregorb09de512012-09-25 15:44:52 +00001312 } else if (II == Ident__building_module) {
1313 // The argument to this builtin should be an identifier. The
1314 // builtin evaluates to 1 when that identifier names the module we are
1315 // currently building.
1316 OS << (int)EvaluateBuildingModule(Tok, II, *this);
1317 Tok.setKind(tok::numeric_constant);
1318 } else if (II == Ident__MODULE__) {
1319 // The current module as an identifier.
1320 OS << getLangOpts().CurrentModule;
1321 IdentifierInfo *ModuleII = getIdentifierInfo(getLangOpts().CurrentModule);
1322 Tok.setIdentifierInfo(ModuleII);
1323 Tok.setKind(ModuleII->getTokenID());
Joao Matos3e1ec722012-08-31 21:34:27 +00001324 } else {
1325 llvm_unreachable("Unknown identifier!");
1326 }
Dmitri Gribenko374b3832012-09-24 21:07:17 +00001327 CreateString(OS.str(), Tok, Tok.getLocation(), Tok.getLocation());
Joao Matos3e1ec722012-08-31 21:34:27 +00001328}
1329
1330void Preprocessor::markMacroAsUsed(MacroInfo *MI) {
1331 // If the 'used' status changed, and the macro requires 'unused' warning,
1332 // remove its SourceLocation from the warn-for-unused-macro locations.
1333 if (MI->isWarnIfUnused() && !MI->isUsed())
1334 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
1335 MI->setIsUsed(true);
1336}