blob: fb9b613f5c8e7f0b528042791f0a83185e60bc2b [file] [log] [blame]
Chris Lattnera3b605e2008-03-09 03:13:06 +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/Diagnostic.h"
Chris Lattnerf90a2482008-03-18 05:59:11 +000021#include <ctime>
Chris Lattnera3b605e2008-03-09 03:13:06 +000022using namespace clang;
23
24/// setMacroInfo - Specify a macro for this identifier.
25///
26void Preprocessor::setMacroInfo(IdentifierInfo *II, MacroInfo *MI) {
27 if (MI == 0) {
28 if (II->hasMacroDefinition()) {
29 Macros.erase(II);
30 II->setHasMacroDefinition(false);
31 }
32 } else {
33 Macros[II] = MI;
34 II->setHasMacroDefinition(true);
35 }
36}
37
38/// RegisterBuiltinMacro - Register the specified identifier in the identifier
39/// table and mark it as a builtin macro to be expanded.
40IdentifierInfo *Preprocessor::RegisterBuiltinMacro(const char *Name) {
41 // Get the identifier.
42 IdentifierInfo *Id = getIdentifierInfo(Name);
43
44 // Mark it as being a macro that is builtin.
45 MacroInfo *MI = new MacroInfo(SourceLocation());
46 MI->setIsBuiltinMacro();
47 setMacroInfo(Id, MI);
48 return Id;
49}
50
51
52/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
53/// identifier table.
54void Preprocessor::RegisterBuiltinMacros() {
55 Ident__LINE__ = RegisterBuiltinMacro("__LINE__");
56 Ident__FILE__ = RegisterBuiltinMacro("__FILE__");
57 Ident__DATE__ = RegisterBuiltinMacro("__DATE__");
58 Ident__TIME__ = RegisterBuiltinMacro("__TIME__");
59 Ident_Pragma = RegisterBuiltinMacro("_Pragma");
60
61 // GCC Extensions.
62 Ident__BASE_FILE__ = RegisterBuiltinMacro("__BASE_FILE__");
63 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro("__INCLUDE_LEVEL__");
64 Ident__TIMESTAMP__ = RegisterBuiltinMacro("__TIMESTAMP__");
65}
66
67/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
68/// in its expansion, currently expands to that token literally.
69static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
70 const IdentifierInfo *MacroIdent,
71 Preprocessor &PP) {
72 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
73
74 // If the token isn't an identifier, it's always literally expanded.
75 if (II == 0) return true;
76
77 // If the identifier is a macro, and if that macro is enabled, it may be
78 // expanded so it's not a trivial expansion.
79 if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled() &&
80 // Fast expanding "#define X X" is ok, because X would be disabled.
81 II != MacroIdent)
82 return false;
83
84 // If this is an object-like macro invocation, it is safe to trivially expand
85 // it.
86 if (MI->isObjectLike()) return true;
87
88 // If this is a function-like macro invocation, it's safe to trivially expand
89 // as long as the identifier is not a macro argument.
90 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
91 I != E; ++I)
92 if (*I == II)
93 return false; // Identifier is a macro argument.
94
95 return true;
96}
97
98
99/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
100/// lexed is a '('. If so, consume the token and return true, if not, this
101/// method should have no observable side-effect on the lexed tokens.
102bool Preprocessor::isNextPPTokenLParen() {
103 // Do some quick tests for rejection cases.
104 unsigned Val;
105 if (CurLexer)
106 Val = CurLexer->isNextPPTokenLParen();
107 else
108 Val = CurTokenLexer->isNextTokenLParen();
109
110 if (Val == 2) {
111 // We have run off the end. If it's a source file we don't
112 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the
113 // macro stack.
114 if (CurLexer)
115 return false;
116 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
117 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
118 if (Entry.TheLexer)
119 Val = Entry.TheLexer->isNextPPTokenLParen();
120 else
121 Val = Entry.TheTokenLexer->isNextTokenLParen();
122
123 if (Val != 2)
124 break;
125
126 // Ran off the end of a source file?
127 if (Entry.TheLexer)
128 return false;
129 }
130 }
131
132 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
133 // have found something that isn't a '(' or we found the end of the
134 // translation unit. In either case, return false.
135 if (Val != 1)
136 return false;
137
138 Token Tok;
139 LexUnexpandedToken(Tok);
140 assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
141 return true;
142}
143
144/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
145/// expanded as a macro, handle it and return the next token as 'Identifier'.
146bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
147 MacroInfo *MI) {
148 // If this is a macro exapnsion in the "#if !defined(x)" line for the file,
149 // then the macro could expand to different things in other contexts, we need
150 // to disable the optimization in this case.
151 if (CurLexer) CurLexer->MIOpt.ExpandedMacro();
152
153 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
154 if (MI->isBuiltinMacro()) {
155 ExpandBuiltinMacro(Identifier);
156 return false;
157 }
158
159 /// Args - If this is a function-like macro expansion, this contains,
160 /// for each macro argument, the list of tokens that were provided to the
161 /// invocation.
162 MacroArgs *Args = 0;
163
164 // If this is a function-like macro, read the arguments.
165 if (MI->isFunctionLike()) {
166 // C99 6.10.3p10: If the preprocessing token immediately after the the macro
167 // name isn't a '(', this macro should not be expanded. Otherwise, consume
168 // it.
169 if (!isNextPPTokenLParen())
170 return true;
171
172 // Remember that we are now parsing the arguments to a macro invocation.
173 // Preprocessor directives used inside macro arguments are not portable, and
174 // this enables the warning.
175 InMacroArgs = true;
176 Args = ReadFunctionLikeMacroArgs(Identifier, MI);
177
178 // Finished parsing args.
179 InMacroArgs = false;
180
181 // If there was an error parsing the arguments, bail out.
182 if (Args == 0) return false;
183
184 ++NumFnMacroExpanded;
185 } else {
186 ++NumMacroExpanded;
187 }
188
189 // Notice that this macro has been used.
190 MI->setIsUsed(true);
191
192 // If we started lexing a macro, enter the macro expansion body.
193
194 // If this macro expands to no tokens, don't bother to push it onto the
195 // expansion stack, only to take it right back off.
196 if (MI->getNumTokens() == 0) {
197 // No need for arg info.
198 if (Args) Args->destroy();
199
200 // Ignore this macro use, just return the next token in the current
201 // buffer.
202 bool HadLeadingSpace = Identifier.hasLeadingSpace();
203 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
204
205 Lex(Identifier);
206
207 // If the identifier isn't on some OTHER line, inherit the leading
208 // whitespace/first-on-a-line property of this token. This handles
209 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
210 // empty.
211 if (!Identifier.isAtStartOfLine()) {
212 if (IsAtStartOfLine) Identifier.setFlag(Token::StartOfLine);
213 if (HadLeadingSpace) Identifier.setFlag(Token::LeadingSpace);
214 }
215 ++NumFastMacroExpanded;
216 return false;
217
218 } else if (MI->getNumTokens() == 1 &&
219 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
220 *this)){
221 // Otherwise, if this macro expands into a single trivially-expanded
222 // token: expand it now. This handles common cases like
223 // "#define VAL 42".
Sam Bishop9a4939f2008-03-21 07:13:02 +0000224
225 // No need for arg info.
226 if (Args) Args->destroy();
227
Chris Lattnera3b605e2008-03-09 03:13:06 +0000228 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
229 // identifier to the expanded token.
230 bool isAtStartOfLine = Identifier.isAtStartOfLine();
231 bool hasLeadingSpace = Identifier.hasLeadingSpace();
232
233 // Remember where the token is instantiated.
234 SourceLocation InstantiateLoc = Identifier.getLocation();
235
236 // Replace the result token.
237 Identifier = MI->getReplacementToken(0);
238
239 // Restore the StartOfLine/LeadingSpace markers.
240 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
241 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
242
243 // Update the tokens location to include both its logical and physical
244 // locations.
245 SourceLocation Loc =
246 SourceMgr.getInstantiationLoc(Identifier.getLocation(), InstantiateLoc);
247 Identifier.setLocation(Loc);
248
249 // If this is #define X X, we must mark the result as unexpandible.
250 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo())
251 if (getMacroInfo(NewII) == MI)
252 Identifier.setFlag(Token::DisableExpand);
253
254 // Since this is not an identifier token, it can't be macro expanded, so
255 // we're done.
256 ++NumFastMacroExpanded;
257 return false;
258 }
259
260 // Start expanding the macro.
261 EnterMacro(Identifier, Args);
262
263 // Now that the macro is at the top of the include stack, ask the
264 // preprocessor to read the next token from it.
265 Lex(Identifier);
266 return false;
267}
268
269/// ReadFunctionLikeMacroArgs - After reading "MACRO(", this method is
270/// invoked to read all of the actual arguments specified for the macro
271/// invocation. This returns null on error.
272MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
273 MacroInfo *MI) {
274 // The number of fixed arguments to parse.
275 unsigned NumFixedArgsLeft = MI->getNumArgs();
276 bool isVariadic = MI->isVariadic();
277
278 // Outer loop, while there are more arguments, keep reading them.
279 Token Tok;
280 Tok.setKind(tok::comma);
281 --NumFixedArgsLeft; // Start reading the first arg.
282
283 // ArgTokens - Build up a list of tokens that make up each argument. Each
284 // argument is separated by an EOF token. Use a SmallVector so we can avoid
285 // heap allocations in the common case.
286 llvm::SmallVector<Token, 64> ArgTokens;
287
288 unsigned NumActuals = 0;
289 while (Tok.is(tok::comma)) {
290 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
291 // that we already consumed the first one.
292 unsigned NumParens = 0;
293
294 while (1) {
295 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
296 // an argument value in a macro could expand to ',' or '(' or ')'.
297 LexUnexpandedToken(Tok);
298
299 if (Tok.is(tok::eof) || Tok.is(tok::eom)) { // "#if f(<eof>" & "#if f(\n"
300 Diag(MacroName, diag::err_unterm_macro_invoc);
301 // Do not lose the EOF/EOM. Return it to the client.
302 MacroName = Tok;
303 return 0;
304 } else if (Tok.is(tok::r_paren)) {
305 // If we found the ) token, the macro arg list is done.
306 if (NumParens-- == 0)
307 break;
308 } else if (Tok.is(tok::l_paren)) {
309 ++NumParens;
310 } else if (Tok.is(tok::comma) && NumParens == 0) {
311 // Comma ends this argument if there are more fixed arguments expected.
312 if (NumFixedArgsLeft)
313 break;
314
315 // If this is not a variadic macro, too many args were specified.
316 if (!isVariadic) {
317 // Emit the diagnostic at the macro name in case there is a missing ).
318 // Emitting it at the , could be far away from the macro name.
319 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
320 return 0;
321 }
322 // Otherwise, continue to add the tokens to this variable argument.
323 } else if (Tok.is(tok::comment) && !KeepMacroComments) {
324 // If this is a comment token in the argument list and we're just in
325 // -C mode (not -CC mode), discard the comment.
326 continue;
327 } else if (Tok.is(tok::identifier)) {
328 // Reading macro arguments can cause macros that we are currently
329 // expanding from to be popped off the expansion stack. Doing so causes
330 // them to be reenabled for expansion. Here we record whether any
331 // identifiers we lex as macro arguments correspond to disabled macros.
332 // If so, we mark the token as noexpand. This is a subtle aspect of
333 // C99 6.10.3.4p2.
334 if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
335 if (!MI->isEnabled())
336 Tok.setFlag(Token::DisableExpand);
337 }
338
339 ArgTokens.push_back(Tok);
340 }
341
342 // Empty arguments are standard in C99 and supported as an extension in
343 // other modes.
344 if (ArgTokens.empty() && !Features.C99)
345 Diag(Tok, diag::ext_empty_fnmacro_arg);
346
347 // Add a marker EOF token to the end of the token list for this argument.
348 Token EOFTok;
349 EOFTok.startToken();
350 EOFTok.setKind(tok::eof);
351 EOFTok.setLocation(Tok.getLocation());
352 EOFTok.setLength(0);
353 ArgTokens.push_back(EOFTok);
354 ++NumActuals;
355 --NumFixedArgsLeft;
356 };
357
358 // Okay, we either found the r_paren. Check to see if we parsed too few
359 // arguments.
360 unsigned MinArgsExpected = MI->getNumArgs();
361
362 // See MacroArgs instance var for description of this.
363 bool isVarargsElided = false;
364
365 if (NumActuals < MinArgsExpected) {
366 // There are several cases where too few arguments is ok, handle them now.
367 if (NumActuals+1 == MinArgsExpected && MI->isVariadic()) {
368 // Varargs where the named vararg parameter is missing: ok as extension.
369 // #define A(x, ...)
370 // A("blah")
371 Diag(Tok, diag::ext_missing_varargs_arg);
372
Chris Lattner63bc0352008-05-08 05:10:33 +0000373 // Remember this occurred if this is a macro invocation with at least
374 // one actual argument. This allows us to elide the comma when used for
375 // cases like:
376 // #define A(x, foo...) blah(a, ## foo)
377 // #define A(x, ...) blah(a, ## __VA_ARGS__)
378 isVarargsElided = MI->getNumArgs() > 1;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000379 } else if (MI->getNumArgs() == 1) {
380 // #define A(x)
381 // A()
382 // is ok because it is an empty argument.
383
384 // Empty arguments are standard in C99 and supported as an extension in
385 // other modes.
386 if (ArgTokens.empty() && !Features.C99)
387 Diag(Tok, diag::ext_empty_fnmacro_arg);
388 } else {
389 // Otherwise, emit the error.
390 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
391 return 0;
392 }
393
394 // Add a marker EOF token to the end of the token list for this argument.
395 SourceLocation EndLoc = Tok.getLocation();
396 Tok.startToken();
397 Tok.setKind(tok::eof);
398 Tok.setLocation(EndLoc);
399 Tok.setLength(0);
400 ArgTokens.push_back(Tok);
401 }
402
403 return MacroArgs::create(MI, &ArgTokens[0], ArgTokens.size(),isVarargsElided);
404}
405
406/// ComputeDATE_TIME - Compute the current time, enter it into the specified
407/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
408/// the identifier tokens inserted.
409static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
410 Preprocessor &PP) {
411 time_t TT = time(0);
412 struct tm *TM = localtime(&TT);
413
414 static const char * const Months[] = {
415 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
416 };
417
418 char TmpBuffer[100];
419 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
420 TM->tm_year+1900);
421 DATELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
422
423 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
424 TIMELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
425}
426
427/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
428/// as a builtin macro, handle it and return the next token as 'Tok'.
429void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
430 // Figure out which token this is.
431 IdentifierInfo *II = Tok.getIdentifierInfo();
432 assert(II && "Can't be a macro without id info!");
433
434 // If this is an _Pragma directive, expand it, invoke the pragma handler, then
435 // lex the token after it.
436 if (II == Ident_Pragma)
437 return Handle_Pragma(Tok);
438
439 ++NumBuiltinMacroExpanded;
440
441 char TmpBuffer[100];
442
443 // Set up the return result.
444 Tok.setIdentifierInfo(0);
445 Tok.clearFlag(Token::NeedsCleaning);
446
447 if (II == Ident__LINE__) {
448 // __LINE__ expands to a simple numeric value.
449 sprintf(TmpBuffer, "%u", SourceMgr.getLogicalLineNumber(Tok.getLocation()));
450 unsigned Length = strlen(TmpBuffer);
451 Tok.setKind(tok::numeric_constant);
452 Tok.setLength(Length);
453 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
454 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
455 SourceLocation Loc = Tok.getLocation();
456 if (II == Ident__BASE_FILE__) {
457 Diag(Tok, diag::ext_pp_base_file);
458 SourceLocation NextLoc = SourceMgr.getIncludeLoc(Loc);
459 while (NextLoc.isValid()) {
460 Loc = NextLoc;
461 NextLoc = SourceMgr.getIncludeLoc(Loc);
462 }
463 }
464
465 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
466 std::string FN = SourceMgr.getSourceName(SourceMgr.getLogicalLoc(Loc));
467 FN = '"' + Lexer::Stringify(FN) + '"';
468 Tok.setKind(tok::string_literal);
469 Tok.setLength(FN.size());
470 Tok.setLocation(CreateString(&FN[0], FN.size(), Tok.getLocation()));
471 } else if (II == Ident__DATE__) {
472 if (!DATELoc.isValid())
473 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
474 Tok.setKind(tok::string_literal);
475 Tok.setLength(strlen("\"Mmm dd yyyy\""));
476 Tok.setLocation(SourceMgr.getInstantiationLoc(DATELoc, Tok.getLocation()));
477 } else if (II == Ident__TIME__) {
478 if (!TIMELoc.isValid())
479 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
480 Tok.setKind(tok::string_literal);
481 Tok.setLength(strlen("\"hh:mm:ss\""));
482 Tok.setLocation(SourceMgr.getInstantiationLoc(TIMELoc, Tok.getLocation()));
483 } else if (II == Ident__INCLUDE_LEVEL__) {
484 Diag(Tok, diag::ext_pp_include_level);
485
486 // Compute the include depth of this token.
487 unsigned Depth = 0;
488 SourceLocation Loc = SourceMgr.getIncludeLoc(Tok.getLocation());
489 for (; Loc.isValid(); ++Depth)
490 Loc = SourceMgr.getIncludeLoc(Loc);
491
492 // __INCLUDE_LEVEL__ expands to a simple numeric value.
493 sprintf(TmpBuffer, "%u", Depth);
494 unsigned Length = strlen(TmpBuffer);
495 Tok.setKind(tok::numeric_constant);
496 Tok.setLength(Length);
497 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
498 } else if (II == Ident__TIMESTAMP__) {
499 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
500 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
501 Diag(Tok, diag::ext_pp_timestamp);
502
503 // Get the file that we are lexing out of. If we're currently lexing from
504 // a macro, dig into the include stack.
505 const FileEntry *CurFile = 0;
506 Lexer *TheLexer = getCurrentFileLexer();
507
508 if (TheLexer)
509 CurFile = SourceMgr.getFileEntryForLoc(TheLexer->getFileLoc());
510
511 // If this file is older than the file it depends on, emit a diagnostic.
512 const char *Result;
513 if (CurFile) {
514 time_t TT = CurFile->getModificationTime();
515 struct tm *TM = localtime(&TT);
516 Result = asctime(TM);
517 } else {
518 Result = "??? ??? ?? ??:??:?? ????\n";
519 }
520 TmpBuffer[0] = '"';
521 strcpy(TmpBuffer+1, Result);
522 unsigned Len = strlen(TmpBuffer);
523 TmpBuffer[Len-1] = '"'; // Replace the newline with a quote.
524 Tok.setKind(tok::string_literal);
525 Tok.setLength(Len);
526 Tok.setLocation(CreateString(TmpBuffer, Len, Tok.getLocation()));
527 } else {
528 assert(0 && "Unknown identifier!");
529 }
530}