blob: e5b00d6bb88e9799a7a0ae6c0be38c04e6a5d0aa [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
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,
Joao Matos3e1ec722012-08-31 21:34:27 +0000226 Identifier.getLocation());
227 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 Kyrtzidisc5159782013-02-24 00:05:14 +0000280 Callbacks->MacroExpands(Identifier, MD, ExpansionRange);
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 Kyrtzidisc5159782013-02-24 00:05:14 +0000284 Callbacks->MacroExpands(Info.Tok, Info.MD, Info.Range);
Joao Matos3e1ec722012-08-31 21:34:27 +0000285 }
286 DelayedMacroExpandsCallbacks.clear();
287 }
288 }
289 }
Douglas Gregore8219a62012-10-11 21:07:39 +0000290
291 // If the macro definition is ambiguous, complain.
Argyrios Kyrtzidis35803282013-03-27 01:25:19 +0000292 if (Def.getDirective()->isAmbiguous()) {
Douglas Gregore8219a62012-10-11 21:07:39 +0000293 Diag(Identifier, diag::warn_pp_ambiguous_macro)
294 << Identifier.getIdentifierInfo();
295 Diag(MI->getDefinitionLoc(), diag::note_pp_ambiguous_macro_chosen)
296 << Identifier.getIdentifierInfo();
Argyrios Kyrtzidis35803282013-03-27 01:25:19 +0000297 for (MacroDirective::DefInfo PrevDef = Def.getPreviousDefinition();
298 PrevDef && !PrevDef.isUndefined();
299 PrevDef = PrevDef.getPreviousDefinition()) {
300 if (PrevDef.getDirective()->isAmbiguous()) {
301 Diag(PrevDef.getMacroInfo()->getDefinitionLoc(),
302 diag::note_pp_ambiguous_macro_other)
Douglas Gregore8219a62012-10-11 21:07:39 +0000303 << Identifier.getIdentifierInfo();
304 }
305 }
306 }
307
Joao Matos3e1ec722012-08-31 21:34:27 +0000308 // If we started lexing a macro, enter the macro expansion body.
309
310 // If this macro expands to no tokens, don't bother to push it onto the
311 // expansion stack, only to take it right back off.
312 if (MI->getNumTokens() == 0) {
313 // No need for arg info.
314 if (Args) Args->destroy(*this);
315
316 // Ignore this macro use, just return the next token in the current
317 // buffer.
318 bool HadLeadingSpace = Identifier.hasLeadingSpace();
319 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
320
321 Lex(Identifier);
322
323 // If the identifier isn't on some OTHER line, inherit the leading
324 // whitespace/first-on-a-line property of this token. This handles
325 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
326 // empty.
327 if (!Identifier.isAtStartOfLine()) {
328 if (IsAtStartOfLine) Identifier.setFlag(Token::StartOfLine);
329 if (HadLeadingSpace) Identifier.setFlag(Token::LeadingSpace);
330 }
331 Identifier.setFlag(Token::LeadingEmptyMacro);
332 ++NumFastMacroExpanded;
333 return false;
334
335 } else if (MI->getNumTokens() == 1 &&
336 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
337 *this)) {
338 // Otherwise, if this macro expands into a single trivially-expanded
339 // token: expand it now. This handles common cases like
340 // "#define VAL 42".
341
342 // No need for arg info.
343 if (Args) Args->destroy(*this);
344
345 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
346 // identifier to the expanded token.
347 bool isAtStartOfLine = Identifier.isAtStartOfLine();
348 bool hasLeadingSpace = Identifier.hasLeadingSpace();
349
350 // Replace the result token.
351 Identifier = MI->getReplacementToken(0);
352
353 // Restore the StartOfLine/LeadingSpace markers.
354 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
355 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
356
357 // Update the tokens location to include both its expansion and physical
358 // locations.
359 SourceLocation Loc =
360 SourceMgr.createExpansionLoc(Identifier.getLocation(), ExpandLoc,
361 ExpansionEnd,Identifier.getLength());
362 Identifier.setLocation(Loc);
363
364 // If this is a disabled macro or #define X X, we must mark the result as
365 // unexpandable.
366 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo()) {
367 if (MacroInfo *NewMI = getMacroInfo(NewII))
368 if (!NewMI->isEnabled() || NewMI == MI) {
369 Identifier.setFlag(Token::DisableExpand);
Douglas Gregor40f56e52013-01-30 23:10:17 +0000370 // Don't warn for "#define X X" like "#define bool bool" from
371 // stdbool.h.
372 if (NewMI != MI || MI->isFunctionLike())
373 Diag(Identifier, diag::pp_disabled_macro_expansion);
Joao Matos3e1ec722012-08-31 21:34:27 +0000374 }
375 }
376
377 // Since this is not an identifier token, it can't be macro expanded, so
378 // we're done.
379 ++NumFastMacroExpanded;
380 return false;
381 }
382
383 // Start expanding the macro.
384 EnterMacro(Identifier, ExpansionEnd, MI, Args);
385
386 // Now that the macro is at the top of the include stack, ask the
387 // preprocessor to read the next token from it.
388 Lex(Identifier);
389 return false;
390}
391
392/// ReadFunctionLikeMacroArgs - After reading "MACRO" and knowing that the next
393/// token is the '(' of the macro, this method is invoked to read all of the
394/// actual arguments specified for the macro invocation. This returns null on
395/// error.
396MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
397 MacroInfo *MI,
398 SourceLocation &MacroEnd) {
399 // The number of fixed arguments to parse.
400 unsigned NumFixedArgsLeft = MI->getNumArgs();
401 bool isVariadic = MI->isVariadic();
402
403 // Outer loop, while there are more arguments, keep reading them.
404 Token Tok;
405
406 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
407 // an argument value in a macro could expand to ',' or '(' or ')'.
408 LexUnexpandedToken(Tok);
409 assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
410
411 // ArgTokens - Build up a list of tokens that make up each argument. Each
412 // argument is separated by an EOF token. Use a SmallVector so we can avoid
413 // heap allocations in the common case.
414 SmallVector<Token, 64> ArgTokens;
Argyrios Kyrtzidiscd0fd182012-12-21 01:17:20 +0000415 bool ContainsCodeCompletionTok = false;
Joao Matos3e1ec722012-08-31 21:34:27 +0000416
417 unsigned NumActuals = 0;
418 while (Tok.isNot(tok::r_paren)) {
Argyrios Kyrtzidiscd0fd182012-12-21 01:17:20 +0000419 if (ContainsCodeCompletionTok && (Tok.is(tok::eof) || Tok.is(tok::eod)))
420 break;
421
Joao Matos3e1ec722012-08-31 21:34:27 +0000422 assert((Tok.is(tok::l_paren) || Tok.is(tok::comma)) &&
423 "only expect argument separators here");
424
425 unsigned ArgTokenStart = ArgTokens.size();
426 SourceLocation ArgStartLoc = Tok.getLocation();
427
428 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
429 // that we already consumed the first one.
430 unsigned NumParens = 0;
431
432 while (1) {
433 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
434 // an argument value in a macro could expand to ',' or '(' or ')'.
435 LexUnexpandedToken(Tok);
436
437 if (Tok.is(tok::eof) || Tok.is(tok::eod)) { // "#if f(<eof>" & "#if f(\n"
Argyrios Kyrtzidiscd0fd182012-12-21 01:17:20 +0000438 if (!ContainsCodeCompletionTok) {
439 Diag(MacroName, diag::err_unterm_macro_invoc);
440 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
441 << MacroName.getIdentifierInfo();
442 // Do not lose the EOF/EOD. Return it to the client.
443 MacroName = Tok;
444 return 0;
445 } else {
Argyrios Kyrtzidisbb06b502012-12-22 04:48:10 +0000446 // Do not lose the EOF/EOD.
447 Token *Toks = new Token[1];
448 Toks[0] = Tok;
449 EnterTokenStream(Toks, 1, true, true);
Argyrios Kyrtzidiscd0fd182012-12-21 01:17:20 +0000450 break;
451 }
Joao Matos3e1ec722012-08-31 21:34:27 +0000452 } else if (Tok.is(tok::r_paren)) {
453 // If we found the ) token, the macro arg list is done.
454 if (NumParens-- == 0) {
455 MacroEnd = Tok.getLocation();
456 break;
457 }
458 } else if (Tok.is(tok::l_paren)) {
459 ++NumParens;
Nico Weber93dec512012-09-26 08:19:01 +0000460 } else if (Tok.is(tok::comma) && NumParens == 0) {
Joao Matos3e1ec722012-08-31 21:34:27 +0000461 // Comma ends this argument if there are more fixed arguments expected.
462 // However, if this is a variadic macro, and this is part of the
463 // variadic part, then the comma is just an argument token.
464 if (!isVariadic) break;
465 if (NumFixedArgsLeft > 1)
466 break;
467 } else if (Tok.is(tok::comment) && !KeepMacroComments) {
468 // If this is a comment token in the argument list and we're just in
469 // -C mode (not -CC mode), discard the comment.
470 continue;
471 } else if (Tok.getIdentifierInfo() != 0) {
472 // Reading macro arguments can cause macros that we are currently
473 // expanding from to be popped off the expansion stack. Doing so causes
474 // them to be reenabled for expansion. Here we record whether any
475 // identifiers we lex as macro arguments correspond to disabled macros.
476 // If so, we mark the token as noexpand. This is a subtle aspect of
477 // C99 6.10.3.4p2.
478 if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
479 if (!MI->isEnabled())
480 Tok.setFlag(Token::DisableExpand);
481 } else if (Tok.is(tok::code_completion)) {
Argyrios Kyrtzidiscd0fd182012-12-21 01:17:20 +0000482 ContainsCodeCompletionTok = true;
Joao Matos3e1ec722012-08-31 21:34:27 +0000483 if (CodeComplete)
484 CodeComplete->CodeCompleteMacroArgument(MacroName.getIdentifierInfo(),
485 MI, NumActuals);
486 // Don't mark that we reached the code-completion point because the
487 // parser is going to handle the token and there will be another
488 // code-completion callback.
489 }
490
491 ArgTokens.push_back(Tok);
492 }
493
494 // If this was an empty argument list foo(), don't add this as an empty
495 // argument.
496 if (ArgTokens.empty() && Tok.getKind() == tok::r_paren)
497 break;
498
499 // If this is not a variadic macro, and too many args were specified, emit
500 // an error.
501 if (!isVariadic && NumFixedArgsLeft == 0) {
502 if (ArgTokens.size() != ArgTokenStart)
503 ArgStartLoc = ArgTokens[ArgTokenStart].getLocation();
504
Argyrios Kyrtzidiscd0fd182012-12-21 01:17:20 +0000505 if (!ContainsCodeCompletionTok) {
506 // Emit the diagnostic at the macro name in case there is a missing ).
507 // Emitting it at the , could be far away from the macro name.
508 Diag(ArgStartLoc, diag::err_too_many_args_in_macro_invoc);
509 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
510 << MacroName.getIdentifierInfo();
511 return 0;
512 }
Joao Matos3e1ec722012-08-31 21:34:27 +0000513 }
514
515 // Empty arguments are standard in C99 and C++0x, and are supported as an extension in
516 // other modes.
517 if (ArgTokens.size() == ArgTokenStart && !LangOpts.C99)
Richard Smith80ad52f2013-01-02 11:42:31 +0000518 Diag(Tok, LangOpts.CPlusPlus11 ?
Joao Matos3e1ec722012-08-31 21:34:27 +0000519 diag::warn_cxx98_compat_empty_fnmacro_arg :
520 diag::ext_empty_fnmacro_arg);
521
522 // Add a marker EOF token to the end of the token list for this argument.
523 Token EOFTok;
524 EOFTok.startToken();
525 EOFTok.setKind(tok::eof);
526 EOFTok.setLocation(Tok.getLocation());
527 EOFTok.setLength(0);
528 ArgTokens.push_back(EOFTok);
529 ++NumActuals;
Argyrios Kyrtzidisfdf57062013-02-22 22:28:58 +0000530 if (!ContainsCodeCompletionTok || NumFixedArgsLeft != 0) {
531 assert(NumFixedArgsLeft != 0 && "Too many arguments parsed");
532 --NumFixedArgsLeft;
533 }
Joao Matos3e1ec722012-08-31 21:34:27 +0000534 }
535
536 // Okay, we either found the r_paren. Check to see if we parsed too few
537 // arguments.
538 unsigned MinArgsExpected = MI->getNumArgs();
539
540 // See MacroArgs instance var for description of this.
541 bool isVarargsElided = false;
542
Argyrios Kyrtzidisf1e5b152012-12-21 01:51:12 +0000543 if (ContainsCodeCompletionTok) {
544 // Recover from not-fully-formed macro invocation during code-completion.
545 Token EOFTok;
546 EOFTok.startToken();
547 EOFTok.setKind(tok::eof);
548 EOFTok.setLocation(Tok.getLocation());
549 EOFTok.setLength(0);
550 for (; NumActuals < MinArgsExpected; ++NumActuals)
551 ArgTokens.push_back(EOFTok);
552 }
553
Joao Matos3e1ec722012-08-31 21:34:27 +0000554 if (NumActuals < MinArgsExpected) {
555 // There are several cases where too few arguments is ok, handle them now.
556 if (NumActuals == 0 && MinArgsExpected == 1) {
557 // #define A(X) or #define A(...) ---> A()
558
559 // If there is exactly one argument, and that argument is missing,
560 // then we have an empty "()" argument empty list. This is fine, even if
561 // the macro expects one argument (the argument is just empty).
562 isVarargsElided = MI->isVariadic();
563 } else if (MI->isVariadic() &&
564 (NumActuals+1 == MinArgsExpected || // A(x, ...) -> A(X)
565 (NumActuals == 0 && MinArgsExpected == 2))) {// A(x,...) -> A()
566 // Varargs where the named vararg parameter is missing: OK as extension.
567 // #define A(x, ...)
568 // A("blah")
Eli Friedman4fa4b482012-11-14 02:18:46 +0000569 //
570 // If the macro contains the comma pasting extension, the diagnostic
571 // is suppressed; we know we'll get another diagnostic later.
572 if (!MI->hasCommaPasting()) {
573 Diag(Tok, diag::ext_missing_varargs_arg);
574 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
575 << MacroName.getIdentifierInfo();
576 }
Joao Matos3e1ec722012-08-31 21:34:27 +0000577
578 // Remember this occurred, allowing us to elide the comma when used for
579 // cases like:
580 // #define A(x, foo...) blah(a, ## foo)
581 // #define B(x, ...) blah(a, ## __VA_ARGS__)
582 // #define C(...) blah(a, ## __VA_ARGS__)
583 // A(x) B(x) C()
584 isVarargsElided = true;
Argyrios Kyrtzidiscd0fd182012-12-21 01:17:20 +0000585 } else if (!ContainsCodeCompletionTok) {
Joao Matos3e1ec722012-08-31 21:34:27 +0000586 // Otherwise, emit the error.
587 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
Argyrios Kyrtzidis0ee8de72012-12-14 18:53:47 +0000588 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
589 << MacroName.getIdentifierInfo();
Joao Matos3e1ec722012-08-31 21:34:27 +0000590 return 0;
591 }
592
593 // Add a marker EOF token to the end of the token list for this argument.
594 SourceLocation EndLoc = Tok.getLocation();
595 Tok.startToken();
596 Tok.setKind(tok::eof);
597 Tok.setLocation(EndLoc);
598 Tok.setLength(0);
599 ArgTokens.push_back(Tok);
600
601 // If we expect two arguments, add both as empty.
602 if (NumActuals == 0 && MinArgsExpected == 2)
603 ArgTokens.push_back(Tok);
604
Argyrios Kyrtzidiscd0fd182012-12-21 01:17:20 +0000605 } else if (NumActuals > MinArgsExpected && !MI->isVariadic() &&
606 !ContainsCodeCompletionTok) {
Joao Matos3e1ec722012-08-31 21:34:27 +0000607 // Emit the diagnostic at the macro name in case there is a missing ).
608 // Emitting it at the , could be far away from the macro name.
609 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
Argyrios Kyrtzidis0ee8de72012-12-14 18:53:47 +0000610 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
611 << MacroName.getIdentifierInfo();
Joao Matos3e1ec722012-08-31 21:34:27 +0000612 return 0;
613 }
614
615 return MacroArgs::create(MI, ArgTokens, isVarargsElided, *this);
616}
617
618/// \brief Keeps macro expanded tokens for TokenLexers.
619//
620/// Works like a stack; a TokenLexer adds the macro expanded tokens that is
621/// going to lex in the cache and when it finishes the tokens are removed
622/// from the end of the cache.
623Token *Preprocessor::cacheMacroExpandedTokens(TokenLexer *tokLexer,
624 ArrayRef<Token> tokens) {
625 assert(tokLexer);
626 if (tokens.empty())
627 return 0;
628
629 size_t newIndex = MacroExpandedTokens.size();
630 bool cacheNeedsToGrow = tokens.size() >
631 MacroExpandedTokens.capacity()-MacroExpandedTokens.size();
632 MacroExpandedTokens.append(tokens.begin(), tokens.end());
633
634 if (cacheNeedsToGrow) {
635 // Go through all the TokenLexers whose 'Tokens' pointer points in the
636 // buffer and update the pointers to the (potential) new buffer array.
637 for (unsigned i = 0, e = MacroExpandingLexersStack.size(); i != e; ++i) {
638 TokenLexer *prevLexer;
639 size_t tokIndex;
640 llvm::tie(prevLexer, tokIndex) = MacroExpandingLexersStack[i];
641 prevLexer->Tokens = MacroExpandedTokens.data() + tokIndex;
642 }
643 }
644
645 MacroExpandingLexersStack.push_back(std::make_pair(tokLexer, newIndex));
646 return MacroExpandedTokens.data() + newIndex;
647}
648
649void Preprocessor::removeCachedMacroExpandedTokensOfLastLexer() {
650 assert(!MacroExpandingLexersStack.empty());
651 size_t tokIndex = MacroExpandingLexersStack.back().second;
652 assert(tokIndex < MacroExpandedTokens.size());
653 // Pop the cached macro expanded tokens from the end.
654 MacroExpandedTokens.resize(tokIndex);
655 MacroExpandingLexersStack.pop_back();
656}
657
658/// ComputeDATE_TIME - Compute the current time, enter it into the specified
659/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
660/// the identifier tokens inserted.
661static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
662 Preprocessor &PP) {
663 time_t TT = time(0);
664 struct tm *TM = localtime(&TT);
665
666 static const char * const Months[] = {
667 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
668 };
669
Dmitri Gribenko33d054b2012-09-24 20:56:28 +0000670 {
671 SmallString<32> TmpBuffer;
672 llvm::raw_svector_ostream TmpStream(TmpBuffer);
673 TmpStream << llvm::format("\"%s %2d %4d\"", Months[TM->tm_mon],
674 TM->tm_mday, TM->tm_year + 1900);
Dmitri Gribenko33d054b2012-09-24 20:56:28 +0000675 Token TmpTok;
676 TmpTok.startToken();
Dmitri Gribenko374b3832012-09-24 21:07:17 +0000677 PP.CreateString(TmpStream.str(), TmpTok);
Dmitri Gribenko33d054b2012-09-24 20:56:28 +0000678 DATELoc = TmpTok.getLocation();
679 }
Joao Matos3e1ec722012-08-31 21:34:27 +0000680
Dmitri Gribenko33d054b2012-09-24 20:56:28 +0000681 {
682 SmallString<32> TmpBuffer;
683 llvm::raw_svector_ostream TmpStream(TmpBuffer);
684 TmpStream << llvm::format("\"%02d:%02d:%02d\"",
685 TM->tm_hour, TM->tm_min, TM->tm_sec);
Dmitri Gribenko33d054b2012-09-24 20:56:28 +0000686 Token TmpTok;
687 TmpTok.startToken();
Dmitri Gribenko374b3832012-09-24 21:07:17 +0000688 PP.CreateString(TmpStream.str(), TmpTok);
Dmitri Gribenko33d054b2012-09-24 20:56:28 +0000689 TIMELoc = TmpTok.getLocation();
690 }
Joao Matos3e1ec722012-08-31 21:34:27 +0000691}
692
693
694/// HasFeature - Return true if we recognize and implement the feature
695/// specified by the identifier as a standard language feature.
696static bool HasFeature(const Preprocessor &PP, const IdentifierInfo *II) {
697 const LangOptions &LangOpts = PP.getLangOpts();
698 StringRef Feature = II->getName();
699
700 // Normalize the feature name, __foo__ becomes foo.
701 if (Feature.startswith("__") && Feature.endswith("__") && Feature.size() >= 4)
702 Feature = Feature.substr(2, Feature.size() - 4);
703
704 return llvm::StringSwitch<bool>(Feature)
Will Dietz4f45bc02013-01-18 11:30:38 +0000705 .Case("address_sanitizer", LangOpts.Sanitize.Address)
Joao Matos3e1ec722012-08-31 21:34:27 +0000706 .Case("attribute_analyzer_noreturn", true)
707 .Case("attribute_availability", true)
708 .Case("attribute_availability_with_message", true)
709 .Case("attribute_cf_returns_not_retained", true)
710 .Case("attribute_cf_returns_retained", true)
711 .Case("attribute_deprecated_with_message", true)
712 .Case("attribute_ext_vector_type", true)
713 .Case("attribute_ns_returns_not_retained", true)
714 .Case("attribute_ns_returns_retained", true)
715 .Case("attribute_ns_consumes_self", true)
716 .Case("attribute_ns_consumed", true)
717 .Case("attribute_cf_consumed", true)
718 .Case("attribute_objc_ivar_unused", true)
719 .Case("attribute_objc_method_family", true)
720 .Case("attribute_overloadable", true)
721 .Case("attribute_unavailable_with_message", true)
722 .Case("attribute_unused_on_fields", true)
723 .Case("blocks", LangOpts.Blocks)
724 .Case("cxx_exceptions", LangOpts.Exceptions)
725 .Case("cxx_rtti", LangOpts.RTTI)
726 .Case("enumerator_attributes", true)
Will Dietz4f45bc02013-01-18 11:30:38 +0000727 .Case("memory_sanitizer", LangOpts.Sanitize.Memory)
728 .Case("thread_sanitizer", LangOpts.Sanitize.Thread)
Joao Matos3e1ec722012-08-31 21:34:27 +0000729 // Objective-C features
730 .Case("objc_arr", LangOpts.ObjCAutoRefCount) // FIXME: REMOVE?
731 .Case("objc_arc", LangOpts.ObjCAutoRefCount)
732 .Case("objc_arc_weak", LangOpts.ObjCARCWeak)
733 .Case("objc_default_synthesize_properties", LangOpts.ObjC2)
734 .Case("objc_fixed_enum", LangOpts.ObjC2)
735 .Case("objc_instancetype", LangOpts.ObjC2)
736 .Case("objc_modules", LangOpts.ObjC2 && LangOpts.Modules)
737 .Case("objc_nonfragile_abi", LangOpts.ObjCRuntime.isNonFragile())
Ted Kremeneke4057c22013-01-04 19:04:44 +0000738 .Case("objc_property_explicit_atomic", true) // Does clang support explicit "atomic" keyword?
Joao Matos3e1ec722012-08-31 21:34:27 +0000739 .Case("objc_weak_class", LangOpts.ObjCRuntime.hasWeakClassImport())
740 .Case("ownership_holds", true)
741 .Case("ownership_returns", true)
742 .Case("ownership_takes", true)
743 .Case("objc_bool", true)
744 .Case("objc_subscripting", LangOpts.ObjCRuntime.isNonFragile())
745 .Case("objc_array_literals", LangOpts.ObjC2)
746 .Case("objc_dictionary_literals", LangOpts.ObjC2)
747 .Case("objc_boxed_expressions", LangOpts.ObjC2)
748 .Case("arc_cf_code_audited", true)
749 // C11 features
750 .Case("c_alignas", LangOpts.C11)
751 .Case("c_atomic", LangOpts.C11)
752 .Case("c_generic_selections", LangOpts.C11)
753 .Case("c_static_assert", LangOpts.C11)
Douglas Gregore87c5bd2013-05-02 05:28:32 +0000754 .Case("c_thread_local",
755 LangOpts.C11 && PP.getTargetInfo().isTLSSupported())
Joao Matos3e1ec722012-08-31 21:34:27 +0000756 // C++11 features
Richard Smith80ad52f2013-01-02 11:42:31 +0000757 .Case("cxx_access_control_sfinae", LangOpts.CPlusPlus11)
758 .Case("cxx_alias_templates", LangOpts.CPlusPlus11)
759 .Case("cxx_alignas", LangOpts.CPlusPlus11)
760 .Case("cxx_atomic", LangOpts.CPlusPlus11)
761 .Case("cxx_attributes", LangOpts.CPlusPlus11)
762 .Case("cxx_auto_type", LangOpts.CPlusPlus11)
763 .Case("cxx_constexpr", LangOpts.CPlusPlus11)
764 .Case("cxx_decltype", LangOpts.CPlusPlus11)
765 .Case("cxx_decltype_incomplete_return_types", LangOpts.CPlusPlus11)
766 .Case("cxx_default_function_template_args", LangOpts.CPlusPlus11)
767 .Case("cxx_defaulted_functions", LangOpts.CPlusPlus11)
768 .Case("cxx_delegating_constructors", LangOpts.CPlusPlus11)
769 .Case("cxx_deleted_functions", LangOpts.CPlusPlus11)
770 .Case("cxx_explicit_conversions", LangOpts.CPlusPlus11)
771 .Case("cxx_generalized_initializers", LangOpts.CPlusPlus11)
772 .Case("cxx_implicit_moves", LangOpts.CPlusPlus11)
Richard Smithe6e68b52013-04-19 17:00:31 +0000773 .Case("cxx_inheriting_constructors", LangOpts.CPlusPlus11)
Richard Smith80ad52f2013-01-02 11:42:31 +0000774 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus11)
775 .Case("cxx_lambdas", LangOpts.CPlusPlus11)
776 .Case("cxx_local_type_template_args", LangOpts.CPlusPlus11)
777 .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus11)
778 .Case("cxx_noexcept", LangOpts.CPlusPlus11)
779 .Case("cxx_nullptr", LangOpts.CPlusPlus11)
780 .Case("cxx_override_control", LangOpts.CPlusPlus11)
781 .Case("cxx_range_for", LangOpts.CPlusPlus11)
782 .Case("cxx_raw_string_literals", LangOpts.CPlusPlus11)
783 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus11)
784 .Case("cxx_rvalue_references", LangOpts.CPlusPlus11)
785 .Case("cxx_strong_enums", LangOpts.CPlusPlus11)
786 .Case("cxx_static_assert", LangOpts.CPlusPlus11)
Douglas Gregore87c5bd2013-05-02 05:28:32 +0000787 .Case("cxx_thread_local",
788 LangOpts.CPlusPlus11 && PP.getTargetInfo().isTLSSupported())
Richard Smith80ad52f2013-01-02 11:42:31 +0000789 .Case("cxx_trailing_return", LangOpts.CPlusPlus11)
790 .Case("cxx_unicode_literals", LangOpts.CPlusPlus11)
791 .Case("cxx_unrestricted_unions", LangOpts.CPlusPlus11)
792 .Case("cxx_user_literals", LangOpts.CPlusPlus11)
793 .Case("cxx_variadic_templates", LangOpts.CPlusPlus11)
Joao Matos3e1ec722012-08-31 21:34:27 +0000794 // Type traits
795 .Case("has_nothrow_assign", LangOpts.CPlusPlus)
796 .Case("has_nothrow_copy", LangOpts.CPlusPlus)
797 .Case("has_nothrow_constructor", LangOpts.CPlusPlus)
798 .Case("has_trivial_assign", LangOpts.CPlusPlus)
799 .Case("has_trivial_copy", LangOpts.CPlusPlus)
800 .Case("has_trivial_constructor", LangOpts.CPlusPlus)
801 .Case("has_trivial_destructor", LangOpts.CPlusPlus)
802 .Case("has_virtual_destructor", LangOpts.CPlusPlus)
803 .Case("is_abstract", LangOpts.CPlusPlus)
804 .Case("is_base_of", LangOpts.CPlusPlus)
805 .Case("is_class", LangOpts.CPlusPlus)
806 .Case("is_convertible_to", LangOpts.CPlusPlus)
Joao Matos3e1ec722012-08-31 21:34:27 +0000807 .Case("is_empty", LangOpts.CPlusPlus)
808 .Case("is_enum", LangOpts.CPlusPlus)
809 .Case("is_final", LangOpts.CPlusPlus)
810 .Case("is_literal", LangOpts.CPlusPlus)
811 .Case("is_standard_layout", LangOpts.CPlusPlus)
812 .Case("is_pod", LangOpts.CPlusPlus)
813 .Case("is_polymorphic", LangOpts.CPlusPlus)
814 .Case("is_trivial", LangOpts.CPlusPlus)
815 .Case("is_trivially_assignable", LangOpts.CPlusPlus)
816 .Case("is_trivially_constructible", LangOpts.CPlusPlus)
817 .Case("is_trivially_copyable", LangOpts.CPlusPlus)
818 .Case("is_union", LangOpts.CPlusPlus)
819 .Case("modules", LangOpts.Modules)
820 .Case("tls", PP.getTargetInfo().isTLSSupported())
821 .Case("underlying_type", LangOpts.CPlusPlus)
822 .Default(false);
823}
824
825/// HasExtension - Return true if we recognize and implement the feature
826/// specified by the identifier, either as an extension or a standard language
827/// feature.
828static bool HasExtension(const Preprocessor &PP, const IdentifierInfo *II) {
829 if (HasFeature(PP, II))
830 return true;
831
832 // If the use of an extension results in an error diagnostic, extensions are
833 // effectively unavailable, so just return false here.
834 if (PP.getDiagnostics().getExtensionHandlingBehavior() ==
835 DiagnosticsEngine::Ext_Error)
836 return false;
837
838 const LangOptions &LangOpts = PP.getLangOpts();
839 StringRef Extension = II->getName();
840
841 // Normalize the extension name, __foo__ becomes foo.
842 if (Extension.startswith("__") && Extension.endswith("__") &&
843 Extension.size() >= 4)
844 Extension = Extension.substr(2, Extension.size() - 4);
845
846 // Because we inherit the feature list from HasFeature, this string switch
847 // must be less restrictive than HasFeature's.
848 return llvm::StringSwitch<bool>(Extension)
849 // C11 features supported by other languages as extensions.
850 .Case("c_alignas", true)
851 .Case("c_atomic", true)
852 .Case("c_generic_selections", true)
853 .Case("c_static_assert", true)
854 // C++0x features supported by other languages as extensions.
855 .Case("cxx_atomic", LangOpts.CPlusPlus)
856 .Case("cxx_deleted_functions", LangOpts.CPlusPlus)
857 .Case("cxx_explicit_conversions", LangOpts.CPlusPlus)
858 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus)
859 .Case("cxx_local_type_template_args", LangOpts.CPlusPlus)
860 .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus)
861 .Case("cxx_override_control", LangOpts.CPlusPlus)
862 .Case("cxx_range_for", LangOpts.CPlusPlus)
863 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus)
864 .Case("cxx_rvalue_references", LangOpts.CPlusPlus)
865 .Default(false);
866}
867
868/// HasAttribute - Return true if we recognize and implement the attribute
869/// specified by the given identifier.
870static bool HasAttribute(const IdentifierInfo *II) {
871 StringRef Name = II->getName();
872 // Normalize the attribute name, __foo__ becomes foo.
873 if (Name.startswith("__") && Name.endswith("__") && Name.size() >= 4)
874 Name = Name.substr(2, Name.size() - 4);
875
876 // FIXME: Do we need to handle namespaces here?
877 return llvm::StringSwitch<bool>(Name)
878#include "clang/Lex/AttrSpellings.inc"
879 .Default(false);
880}
881
882/// EvaluateHasIncludeCommon - Process a '__has_include("path")'
883/// or '__has_include_next("path")' expression.
884/// Returns true if successful.
885static bool EvaluateHasIncludeCommon(Token &Tok,
886 IdentifierInfo *II, Preprocessor &PP,
887 const DirectoryLookup *LookupFrom) {
Richard Trieu97bc3d52012-10-22 20:28:48 +0000888 // Save the location of the current token. If a '(' is later found, use
Aaron Ballman6b716c52013-01-15 21:59:46 +0000889 // that location. If not, use the end of this location instead.
Richard Trieu97bc3d52012-10-22 20:28:48 +0000890 SourceLocation LParenLoc = Tok.getLocation();
Joao Matos3e1ec722012-08-31 21:34:27 +0000891
Aaron Ballman31672b12013-01-16 19:32:21 +0000892 // These expressions are only allowed within a preprocessor directive.
893 if (!PP.isParsingIfOrElifDirective()) {
894 PP.Diag(LParenLoc, diag::err_pp_directive_required) << II->getName();
895 return false;
896 }
897
Joao Matos3e1ec722012-08-31 21:34:27 +0000898 // Get '('.
899 PP.LexNonComment(Tok);
900
901 // Ensure we have a '('.
902 if (Tok.isNot(tok::l_paren)) {
Richard Trieu97bc3d52012-10-22 20:28:48 +0000903 // No '(', use end of last token.
904 LParenLoc = PP.getLocForEndOfToken(LParenLoc);
905 PP.Diag(LParenLoc, diag::err_pp_missing_lparen) << II->getName();
906 // If the next token looks like a filename or the start of one,
907 // assume it is and process it as such.
908 if (!Tok.is(tok::angle_string_literal) && !Tok.is(tok::string_literal) &&
909 !Tok.is(tok::less))
910 return false;
911 } else {
912 // Save '(' location for possible missing ')' message.
913 LParenLoc = Tok.getLocation();
914
Eli Friedmana0f2d022013-01-09 02:20:00 +0000915 if (PP.getCurrentLexer()) {
916 // Get the file name.
917 PP.getCurrentLexer()->LexIncludeFilename(Tok);
918 } else {
919 // We're in a macro, so we can't use LexIncludeFilename; just
920 // grab the next token.
921 PP.Lex(Tok);
922 }
Joao Matos3e1ec722012-08-31 21:34:27 +0000923 }
924
Joao Matos3e1ec722012-08-31 21:34:27 +0000925 // Reserve a buffer to get the spelling.
926 SmallString<128> FilenameBuffer;
927 StringRef Filename;
928 SourceLocation EndLoc;
929
930 switch (Tok.getKind()) {
931 case tok::eod:
932 // If the token kind is EOD, the error has already been diagnosed.
933 return false;
934
935 case tok::angle_string_literal:
936 case tok::string_literal: {
937 bool Invalid = false;
938 Filename = PP.getSpelling(Tok, FilenameBuffer, &Invalid);
939 if (Invalid)
940 return false;
941 break;
942 }
943
944 case tok::less:
945 // This could be a <foo/bar.h> file coming from a macro expansion. In this
946 // case, glue the tokens together into FilenameBuffer and interpret those.
947 FilenameBuffer.push_back('<');
Richard Trieu97bc3d52012-10-22 20:28:48 +0000948 if (PP.ConcatenateIncludeName(FilenameBuffer, EndLoc)) {
949 // Let the caller know a <eod> was found by changing the Token kind.
950 Tok.setKind(tok::eod);
Joao Matos3e1ec722012-08-31 21:34:27 +0000951 return false; // Found <eod> but no ">"? Diagnostic already emitted.
Richard Trieu97bc3d52012-10-22 20:28:48 +0000952 }
Joao Matos3e1ec722012-08-31 21:34:27 +0000953 Filename = FilenameBuffer.str();
954 break;
955 default:
956 PP.Diag(Tok.getLocation(), diag::err_pp_expects_filename);
957 return false;
958 }
959
Richard Trieu97bc3d52012-10-22 20:28:48 +0000960 SourceLocation FilenameLoc = Tok.getLocation();
961
Joao Matos3e1ec722012-08-31 21:34:27 +0000962 // Get ')'.
963 PP.LexNonComment(Tok);
964
965 // Ensure we have a trailing ).
966 if (Tok.isNot(tok::r_paren)) {
Richard Trieu97bc3d52012-10-22 20:28:48 +0000967 PP.Diag(PP.getLocForEndOfToken(FilenameLoc), diag::err_pp_missing_rparen)
968 << II->getName();
Joao Matos3e1ec722012-08-31 21:34:27 +0000969 PP.Diag(LParenLoc, diag::note_matching) << "(";
970 return false;
971 }
972
973 bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename);
974 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
975 // error.
976 if (Filename.empty())
977 return false;
978
979 // Search include directories.
980 const DirectoryLookup *CurDir;
981 const FileEntry *File =
982 PP.LookupFile(Filename, isAngled, LookupFrom, CurDir, NULL, NULL, NULL);
983
984 // Get the result value. A result of true means the file exists.
985 return File != 0;
986}
987
988/// EvaluateHasInclude - Process a '__has_include("path")' expression.
989/// Returns true if successful.
990static bool EvaluateHasInclude(Token &Tok, IdentifierInfo *II,
991 Preprocessor &PP) {
992 return EvaluateHasIncludeCommon(Tok, II, PP, NULL);
993}
994
995/// EvaluateHasIncludeNext - Process '__has_include_next("path")' expression.
996/// Returns true if successful.
997static bool EvaluateHasIncludeNext(Token &Tok,
998 IdentifierInfo *II, Preprocessor &PP) {
999 // __has_include_next is like __has_include, except that we start
1000 // searching after the current found directory. If we can't do this,
1001 // issue a diagnostic.
1002 const DirectoryLookup *Lookup = PP.GetCurDirLookup();
1003 if (PP.isInPrimaryFile()) {
1004 Lookup = 0;
1005 PP.Diag(Tok, diag::pp_include_next_in_primary);
1006 } else if (Lookup == 0) {
1007 PP.Diag(Tok, diag::pp_include_next_absolute_path);
1008 } else {
1009 // Start looking up in the next directory.
1010 ++Lookup;
1011 }
1012
1013 return EvaluateHasIncludeCommon(Tok, II, PP, Lookup);
1014}
1015
Douglas Gregorb09de512012-09-25 15:44:52 +00001016/// \brief Process __building_module(identifier) expression.
1017/// \returns true if we are building the named module, false otherwise.
1018static bool EvaluateBuildingModule(Token &Tok,
1019 IdentifierInfo *II, Preprocessor &PP) {
1020 // Get '('.
1021 PP.LexNonComment(Tok);
1022
1023 // Ensure we have a '('.
1024 if (Tok.isNot(tok::l_paren)) {
1025 PP.Diag(Tok.getLocation(), diag::err_pp_missing_lparen) << II->getName();
1026 return false;
1027 }
1028
1029 // Save '(' location for possible missing ')' message.
1030 SourceLocation LParenLoc = Tok.getLocation();
1031
1032 // Get the module name.
1033 PP.LexNonComment(Tok);
1034
1035 // Ensure that we have an identifier.
1036 if (Tok.isNot(tok::identifier)) {
1037 PP.Diag(Tok.getLocation(), diag::err_expected_id_building_module);
1038 return false;
1039 }
1040
1041 bool Result
1042 = Tok.getIdentifierInfo()->getName() == PP.getLangOpts().CurrentModule;
1043
1044 // Get ')'.
1045 PP.LexNonComment(Tok);
1046
1047 // Ensure we have a trailing ).
1048 if (Tok.isNot(tok::r_paren)) {
1049 PP.Diag(Tok.getLocation(), diag::err_pp_missing_rparen) << II->getName();
1050 PP.Diag(LParenLoc, diag::note_matching) << "(";
1051 return false;
1052 }
1053
1054 return Result;
1055}
1056
Joao Matos3e1ec722012-08-31 21:34:27 +00001057/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
1058/// as a builtin macro, handle it and return the next token as 'Tok'.
1059void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
1060 // Figure out which token this is.
1061 IdentifierInfo *II = Tok.getIdentifierInfo();
1062 assert(II && "Can't be a macro without id info!");
1063
1064 // If this is an _Pragma or Microsoft __pragma directive, expand it,
1065 // invoke the pragma handler, then lex the token after it.
1066 if (II == Ident_Pragma)
1067 return Handle_Pragma(Tok);
1068 else if (II == Ident__pragma) // in non-MS mode this is null
1069 return HandleMicrosoft__pragma(Tok);
1070
1071 ++NumBuiltinMacroExpanded;
1072
1073 SmallString<128> TmpBuffer;
1074 llvm::raw_svector_ostream OS(TmpBuffer);
1075
1076 // Set up the return result.
1077 Tok.setIdentifierInfo(0);
1078 Tok.clearFlag(Token::NeedsCleaning);
1079
1080 if (II == Ident__LINE__) {
1081 // C99 6.10.8: "__LINE__: The presumed line number (within the current
1082 // source file) of the current source line (an integer constant)". This can
1083 // be affected by #line.
1084 SourceLocation Loc = Tok.getLocation();
1085
1086 // Advance to the location of the first _, this might not be the first byte
1087 // of the token if it starts with an escaped newline.
1088 Loc = AdvanceToTokenCharacter(Loc, 0);
1089
1090 // One wrinkle here is that GCC expands __LINE__ to location of the *end* of
1091 // a macro expansion. This doesn't matter for object-like macros, but
1092 // can matter for a function-like macro that expands to contain __LINE__.
1093 // Skip down through expansion points until we find a file loc for the
1094 // end of the expansion history.
1095 Loc = SourceMgr.getExpansionRange(Loc).second;
1096 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc);
1097
1098 // __LINE__ expands to a simple numeric value.
1099 OS << (PLoc.isValid()? PLoc.getLine() : 1);
1100 Tok.setKind(tok::numeric_constant);
1101 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
1102 // C99 6.10.8: "__FILE__: The presumed name of the current source file (a
1103 // character string literal)". This can be affected by #line.
1104 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
1105
1106 // __BASE_FILE__ is a GNU extension that returns the top of the presumed
1107 // #include stack instead of the current file.
1108 if (II == Ident__BASE_FILE__ && PLoc.isValid()) {
1109 SourceLocation NextLoc = PLoc.getIncludeLoc();
1110 while (NextLoc.isValid()) {
1111 PLoc = SourceMgr.getPresumedLoc(NextLoc);
1112 if (PLoc.isInvalid())
1113 break;
1114
1115 NextLoc = PLoc.getIncludeLoc();
1116 }
1117 }
1118
1119 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
1120 SmallString<128> FN;
1121 if (PLoc.isValid()) {
1122 FN += PLoc.getFilename();
1123 Lexer::Stringify(FN);
1124 OS << '"' << FN.str() << '"';
1125 }
1126 Tok.setKind(tok::string_literal);
1127 } else if (II == Ident__DATE__) {
1128 if (!DATELoc.isValid())
1129 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1130 Tok.setKind(tok::string_literal);
1131 Tok.setLength(strlen("\"Mmm dd yyyy\""));
1132 Tok.setLocation(SourceMgr.createExpansionLoc(DATELoc, Tok.getLocation(),
1133 Tok.getLocation(),
1134 Tok.getLength()));
1135 return;
1136 } else if (II == Ident__TIME__) {
1137 if (!TIMELoc.isValid())
1138 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1139 Tok.setKind(tok::string_literal);
1140 Tok.setLength(strlen("\"hh:mm:ss\""));
1141 Tok.setLocation(SourceMgr.createExpansionLoc(TIMELoc, Tok.getLocation(),
1142 Tok.getLocation(),
1143 Tok.getLength()));
1144 return;
1145 } else if (II == Ident__INCLUDE_LEVEL__) {
1146 // Compute the presumed include depth of this token. This can be affected
1147 // by GNU line markers.
1148 unsigned Depth = 0;
1149
1150 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
1151 if (PLoc.isValid()) {
1152 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
1153 for (; PLoc.isValid(); ++Depth)
1154 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
1155 }
1156
1157 // __INCLUDE_LEVEL__ expands to a simple numeric value.
1158 OS << Depth;
1159 Tok.setKind(tok::numeric_constant);
1160 } else if (II == Ident__TIMESTAMP__) {
1161 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
1162 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
1163
1164 // Get the file that we are lexing out of. If we're currently lexing from
1165 // a macro, dig into the include stack.
1166 const FileEntry *CurFile = 0;
1167 PreprocessorLexer *TheLexer = getCurrentFileLexer();
1168
1169 if (TheLexer)
1170 CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID());
1171
1172 const char *Result;
1173 if (CurFile) {
1174 time_t TT = CurFile->getModificationTime();
1175 struct tm *TM = localtime(&TT);
1176 Result = asctime(TM);
1177 } else {
1178 Result = "??? ??? ?? ??:??:?? ????\n";
1179 }
1180 // Surround the string with " and strip the trailing newline.
1181 OS << '"' << StringRef(Result, strlen(Result)-1) << '"';
1182 Tok.setKind(tok::string_literal);
1183 } else if (II == Ident__COUNTER__) {
1184 // __COUNTER__ expands to a simple numeric value.
1185 OS << CounterValue++;
1186 Tok.setKind(tok::numeric_constant);
1187 } else if (II == Ident__has_feature ||
1188 II == Ident__has_extension ||
1189 II == Ident__has_builtin ||
1190 II == Ident__has_attribute) {
1191 // The argument to these builtins should be a parenthesized identifier.
1192 SourceLocation StartLoc = Tok.getLocation();
1193
1194 bool IsValid = false;
1195 IdentifierInfo *FeatureII = 0;
1196
1197 // Read the '('.
Andy Gibbs3f03b582012-11-17 19:18:27 +00001198 LexUnexpandedToken(Tok);
Joao Matos3e1ec722012-08-31 21:34:27 +00001199 if (Tok.is(tok::l_paren)) {
1200 // Read the identifier
Andy Gibbs3f03b582012-11-17 19:18:27 +00001201 LexUnexpandedToken(Tok);
Joao Matos3e1ec722012-08-31 21:34:27 +00001202 if (Tok.is(tok::identifier) || Tok.is(tok::kw_const)) {
1203 FeatureII = Tok.getIdentifierInfo();
1204
1205 // Read the ')'.
Andy Gibbs3f03b582012-11-17 19:18:27 +00001206 LexUnexpandedToken(Tok);
Joao Matos3e1ec722012-08-31 21:34:27 +00001207 if (Tok.is(tok::r_paren))
1208 IsValid = true;
1209 }
1210 }
1211
1212 bool Value = false;
1213 if (!IsValid)
1214 Diag(StartLoc, diag::err_feature_check_malformed);
1215 else if (II == Ident__has_builtin) {
1216 // Check for a builtin is trivial.
1217 Value = FeatureII->getBuiltinID() != 0;
1218 } else if (II == Ident__has_attribute)
1219 Value = HasAttribute(FeatureII);
1220 else if (II == Ident__has_extension)
1221 Value = HasExtension(*this, FeatureII);
1222 else {
1223 assert(II == Ident__has_feature && "Must be feature check");
1224 Value = HasFeature(*this, FeatureII);
1225 }
1226
1227 OS << (int)Value;
1228 if (IsValid)
1229 Tok.setKind(tok::numeric_constant);
1230 } else if (II == Ident__has_include ||
1231 II == Ident__has_include_next) {
1232 // The argument to these two builtins should be a parenthesized
1233 // file name string literal using angle brackets (<>) or
1234 // double-quotes ("").
1235 bool Value;
1236 if (II == Ident__has_include)
1237 Value = EvaluateHasInclude(Tok, II, *this);
1238 else
1239 Value = EvaluateHasIncludeNext(Tok, II, *this);
1240 OS << (int)Value;
Richard Trieu97bc3d52012-10-22 20:28:48 +00001241 if (Tok.is(tok::r_paren))
1242 Tok.setKind(tok::numeric_constant);
Joao Matos3e1ec722012-08-31 21:34:27 +00001243 } else if (II == Ident__has_warning) {
1244 // The argument should be a parenthesized string literal.
1245 // The argument to these builtins should be a parenthesized identifier.
1246 SourceLocation StartLoc = Tok.getLocation();
1247 bool IsValid = false;
1248 bool Value = false;
1249 // Read the '('.
Andy Gibbs02a17682012-11-17 19:15:38 +00001250 LexUnexpandedToken(Tok);
Joao Matos3e1ec722012-08-31 21:34:27 +00001251 do {
Andy Gibbs02a17682012-11-17 19:15:38 +00001252 if (Tok.isNot(tok::l_paren)) {
1253 Diag(StartLoc, diag::err_warning_check_malformed);
1254 break;
Joao Matos3e1ec722012-08-31 21:34:27 +00001255 }
Andy Gibbs02a17682012-11-17 19:15:38 +00001256
1257 LexUnexpandedToken(Tok);
1258 std::string WarningName;
1259 SourceLocation StrStartLoc = Tok.getLocation();
Andy Gibbs97f84612012-11-17 19:16:52 +00001260 if (!FinishLexStringLiteral(Tok, WarningName, "'__has_warning'",
1261 /*MacroExpansion=*/false)) {
Andy Gibbs02a17682012-11-17 19:15:38 +00001262 // Eat tokens until ')'.
Andy Gibbs6d534d42012-11-17 22:17:28 +00001263 while (Tok.isNot(tok::r_paren) && Tok.isNot(tok::eod) &&
1264 Tok.isNot(tok::eof))
Andy Gibbs02a17682012-11-17 19:15:38 +00001265 LexUnexpandedToken(Tok);
1266 break;
1267 }
1268
1269 // Is the end a ')'?
1270 if (!(IsValid = Tok.is(tok::r_paren))) {
1271 Diag(StartLoc, diag::err_warning_check_malformed);
1272 break;
1273 }
1274
1275 if (WarningName.size() < 3 || WarningName[0] != '-' ||
1276 WarningName[1] != 'W') {
1277 Diag(StrStartLoc, diag::warn_has_warning_invalid_option);
1278 break;
1279 }
1280
1281 // Finally, check if the warning flags maps to a diagnostic group.
1282 // We construct a SmallVector here to talk to getDiagnosticIDs().
1283 // Although we don't use the result, this isn't a hot path, and not
1284 // worth special casing.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001285 SmallVector<diag::kind, 10> Diags;
Andy Gibbs02a17682012-11-17 19:15:38 +00001286 Value = !getDiagnostics().getDiagnosticIDs()->
1287 getDiagnosticsInGroup(WarningName.substr(2), Diags);
Joao Matos3e1ec722012-08-31 21:34:27 +00001288 } while (false);
Joao Matos3e1ec722012-08-31 21:34:27 +00001289
1290 OS << (int)Value;
Andy Gibbsb9971ba2012-11-17 19:14:53 +00001291 if (IsValid)
1292 Tok.setKind(tok::numeric_constant);
Douglas Gregorb09de512012-09-25 15:44:52 +00001293 } else if (II == Ident__building_module) {
1294 // The argument to this builtin should be an identifier. The
1295 // builtin evaluates to 1 when that identifier names the module we are
1296 // currently building.
1297 OS << (int)EvaluateBuildingModule(Tok, II, *this);
1298 Tok.setKind(tok::numeric_constant);
1299 } else if (II == Ident__MODULE__) {
1300 // The current module as an identifier.
1301 OS << getLangOpts().CurrentModule;
1302 IdentifierInfo *ModuleII = getIdentifierInfo(getLangOpts().CurrentModule);
1303 Tok.setIdentifierInfo(ModuleII);
1304 Tok.setKind(ModuleII->getTokenID());
Joao Matos3e1ec722012-08-31 21:34:27 +00001305 } else {
1306 llvm_unreachable("Unknown identifier!");
1307 }
Dmitri Gribenko374b3832012-09-24 21:07:17 +00001308 CreateString(OS.str(), Tok, Tok.getLocation(), Tok.getLocation());
Joao Matos3e1ec722012-08-31 21:34:27 +00001309}
1310
1311void Preprocessor::markMacroAsUsed(MacroInfo *MI) {
1312 // If the 'used' status changed, and the macro requires 'unused' warning,
1313 // remove its SourceLocation from the warn-for-unused-macro locations.
1314 if (MI->isWarnIfUnused() && !MI->isUsed())
1315 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
1316 MI->setIsUsed(true);
1317}