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