blob: c21f399e63d68f3318ac8b5b6a3f57508601f770 [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".
224
225 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
226 // identifier to the expanded token.
227 bool isAtStartOfLine = Identifier.isAtStartOfLine();
228 bool hasLeadingSpace = Identifier.hasLeadingSpace();
229
230 // Remember where the token is instantiated.
231 SourceLocation InstantiateLoc = Identifier.getLocation();
232
233 // Replace the result token.
234 Identifier = MI->getReplacementToken(0);
235
236 // Restore the StartOfLine/LeadingSpace markers.
237 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
238 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
239
240 // Update the tokens location to include both its logical and physical
241 // locations.
242 SourceLocation Loc =
243 SourceMgr.getInstantiationLoc(Identifier.getLocation(), InstantiateLoc);
244 Identifier.setLocation(Loc);
245
246 // If this is #define X X, we must mark the result as unexpandible.
247 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo())
248 if (getMacroInfo(NewII) == MI)
249 Identifier.setFlag(Token::DisableExpand);
250
251 // Since this is not an identifier token, it can't be macro expanded, so
252 // we're done.
253 ++NumFastMacroExpanded;
254 return false;
255 }
256
257 // Start expanding the macro.
258 EnterMacro(Identifier, Args);
259
260 // Now that the macro is at the top of the include stack, ask the
261 // preprocessor to read the next token from it.
262 Lex(Identifier);
263 return false;
264}
265
266/// ReadFunctionLikeMacroArgs - After reading "MACRO(", this method is
267/// invoked to read all of the actual arguments specified for the macro
268/// invocation. This returns null on error.
269MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
270 MacroInfo *MI) {
271 // The number of fixed arguments to parse.
272 unsigned NumFixedArgsLeft = MI->getNumArgs();
273 bool isVariadic = MI->isVariadic();
274
275 // Outer loop, while there are more arguments, keep reading them.
276 Token Tok;
277 Tok.setKind(tok::comma);
278 --NumFixedArgsLeft; // Start reading the first arg.
279
280 // ArgTokens - Build up a list of tokens that make up each argument. Each
281 // argument is separated by an EOF token. Use a SmallVector so we can avoid
282 // heap allocations in the common case.
283 llvm::SmallVector<Token, 64> ArgTokens;
284
285 unsigned NumActuals = 0;
286 while (Tok.is(tok::comma)) {
287 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
288 // that we already consumed the first one.
289 unsigned NumParens = 0;
290
291 while (1) {
292 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
293 // an argument value in a macro could expand to ',' or '(' or ')'.
294 LexUnexpandedToken(Tok);
295
296 if (Tok.is(tok::eof) || Tok.is(tok::eom)) { // "#if f(<eof>" & "#if f(\n"
297 Diag(MacroName, diag::err_unterm_macro_invoc);
298 // Do not lose the EOF/EOM. Return it to the client.
299 MacroName = Tok;
300 return 0;
301 } else if (Tok.is(tok::r_paren)) {
302 // If we found the ) token, the macro arg list is done.
303 if (NumParens-- == 0)
304 break;
305 } else if (Tok.is(tok::l_paren)) {
306 ++NumParens;
307 } else if (Tok.is(tok::comma) && NumParens == 0) {
308 // Comma ends this argument if there are more fixed arguments expected.
309 if (NumFixedArgsLeft)
310 break;
311
312 // If this is not a variadic macro, too many args were specified.
313 if (!isVariadic) {
314 // Emit the diagnostic at the macro name in case there is a missing ).
315 // Emitting it at the , could be far away from the macro name.
316 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
317 return 0;
318 }
319 // Otherwise, continue to add the tokens to this variable argument.
320 } else if (Tok.is(tok::comment) && !KeepMacroComments) {
321 // If this is a comment token in the argument list and we're just in
322 // -C mode (not -CC mode), discard the comment.
323 continue;
324 } else if (Tok.is(tok::identifier)) {
325 // Reading macro arguments can cause macros that we are currently
326 // expanding from to be popped off the expansion stack. Doing so causes
327 // them to be reenabled for expansion. Here we record whether any
328 // identifiers we lex as macro arguments correspond to disabled macros.
329 // If so, we mark the token as noexpand. This is a subtle aspect of
330 // C99 6.10.3.4p2.
331 if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
332 if (!MI->isEnabled())
333 Tok.setFlag(Token::DisableExpand);
334 }
335
336 ArgTokens.push_back(Tok);
337 }
338
339 // Empty arguments are standard in C99 and supported as an extension in
340 // other modes.
341 if (ArgTokens.empty() && !Features.C99)
342 Diag(Tok, diag::ext_empty_fnmacro_arg);
343
344 // Add a marker EOF token to the end of the token list for this argument.
345 Token EOFTok;
346 EOFTok.startToken();
347 EOFTok.setKind(tok::eof);
348 EOFTok.setLocation(Tok.getLocation());
349 EOFTok.setLength(0);
350 ArgTokens.push_back(EOFTok);
351 ++NumActuals;
352 --NumFixedArgsLeft;
353 };
354
355 // Okay, we either found the r_paren. Check to see if we parsed too few
356 // arguments.
357 unsigned MinArgsExpected = MI->getNumArgs();
358
359 // See MacroArgs instance var for description of this.
360 bool isVarargsElided = false;
361
362 if (NumActuals < MinArgsExpected) {
363 // There are several cases where too few arguments is ok, handle them now.
364 if (NumActuals+1 == MinArgsExpected && MI->isVariadic()) {
365 // Varargs where the named vararg parameter is missing: ok as extension.
366 // #define A(x, ...)
367 // A("blah")
368 Diag(Tok, diag::ext_missing_varargs_arg);
369
370 // Remember this occurred if this is a C99 macro invocation with at least
371 // one actual argument.
372 isVarargsElided = MI->isC99Varargs() && MI->getNumArgs() > 1;
373 } else if (MI->getNumArgs() == 1) {
374 // #define A(x)
375 // A()
376 // is ok because it is an empty argument.
377
378 // Empty arguments are standard in C99 and supported as an extension in
379 // other modes.
380 if (ArgTokens.empty() && !Features.C99)
381 Diag(Tok, diag::ext_empty_fnmacro_arg);
382 } else {
383 // Otherwise, emit the error.
384 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
385 return 0;
386 }
387
388 // Add a marker EOF token to the end of the token list for this argument.
389 SourceLocation EndLoc = Tok.getLocation();
390 Tok.startToken();
391 Tok.setKind(tok::eof);
392 Tok.setLocation(EndLoc);
393 Tok.setLength(0);
394 ArgTokens.push_back(Tok);
395 }
396
397 return MacroArgs::create(MI, &ArgTokens[0], ArgTokens.size(),isVarargsElided);
398}
399
400/// ComputeDATE_TIME - Compute the current time, enter it into the specified
401/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
402/// the identifier tokens inserted.
403static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
404 Preprocessor &PP) {
405 time_t TT = time(0);
406 struct tm *TM = localtime(&TT);
407
408 static const char * const Months[] = {
409 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
410 };
411
412 char TmpBuffer[100];
413 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
414 TM->tm_year+1900);
415 DATELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
416
417 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
418 TIMELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
419}
420
421/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
422/// as a builtin macro, handle it and return the next token as 'Tok'.
423void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
424 // Figure out which token this is.
425 IdentifierInfo *II = Tok.getIdentifierInfo();
426 assert(II && "Can't be a macro without id info!");
427
428 // If this is an _Pragma directive, expand it, invoke the pragma handler, then
429 // lex the token after it.
430 if (II == Ident_Pragma)
431 return Handle_Pragma(Tok);
432
433 ++NumBuiltinMacroExpanded;
434
435 char TmpBuffer[100];
436
437 // Set up the return result.
438 Tok.setIdentifierInfo(0);
439 Tok.clearFlag(Token::NeedsCleaning);
440
441 if (II == Ident__LINE__) {
442 // __LINE__ expands to a simple numeric value.
443 sprintf(TmpBuffer, "%u", SourceMgr.getLogicalLineNumber(Tok.getLocation()));
444 unsigned Length = strlen(TmpBuffer);
445 Tok.setKind(tok::numeric_constant);
446 Tok.setLength(Length);
447 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
448 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
449 SourceLocation Loc = Tok.getLocation();
450 if (II == Ident__BASE_FILE__) {
451 Diag(Tok, diag::ext_pp_base_file);
452 SourceLocation NextLoc = SourceMgr.getIncludeLoc(Loc);
453 while (NextLoc.isValid()) {
454 Loc = NextLoc;
455 NextLoc = SourceMgr.getIncludeLoc(Loc);
456 }
457 }
458
459 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
460 std::string FN = SourceMgr.getSourceName(SourceMgr.getLogicalLoc(Loc));
461 FN = '"' + Lexer::Stringify(FN) + '"';
462 Tok.setKind(tok::string_literal);
463 Tok.setLength(FN.size());
464 Tok.setLocation(CreateString(&FN[0], FN.size(), Tok.getLocation()));
465 } else if (II == Ident__DATE__) {
466 if (!DATELoc.isValid())
467 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
468 Tok.setKind(tok::string_literal);
469 Tok.setLength(strlen("\"Mmm dd yyyy\""));
470 Tok.setLocation(SourceMgr.getInstantiationLoc(DATELoc, Tok.getLocation()));
471 } else if (II == Ident__TIME__) {
472 if (!TIMELoc.isValid())
473 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
474 Tok.setKind(tok::string_literal);
475 Tok.setLength(strlen("\"hh:mm:ss\""));
476 Tok.setLocation(SourceMgr.getInstantiationLoc(TIMELoc, Tok.getLocation()));
477 } else if (II == Ident__INCLUDE_LEVEL__) {
478 Diag(Tok, diag::ext_pp_include_level);
479
480 // Compute the include depth of this token.
481 unsigned Depth = 0;
482 SourceLocation Loc = SourceMgr.getIncludeLoc(Tok.getLocation());
483 for (; Loc.isValid(); ++Depth)
484 Loc = SourceMgr.getIncludeLoc(Loc);
485
486 // __INCLUDE_LEVEL__ expands to a simple numeric value.
487 sprintf(TmpBuffer, "%u", Depth);
488 unsigned Length = strlen(TmpBuffer);
489 Tok.setKind(tok::numeric_constant);
490 Tok.setLength(Length);
491 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
492 } else if (II == Ident__TIMESTAMP__) {
493 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
494 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
495 Diag(Tok, diag::ext_pp_timestamp);
496
497 // Get the file that we are lexing out of. If we're currently lexing from
498 // a macro, dig into the include stack.
499 const FileEntry *CurFile = 0;
500 Lexer *TheLexer = getCurrentFileLexer();
501
502 if (TheLexer)
503 CurFile = SourceMgr.getFileEntryForLoc(TheLexer->getFileLoc());
504
505 // If this file is older than the file it depends on, emit a diagnostic.
506 const char *Result;
507 if (CurFile) {
508 time_t TT = CurFile->getModificationTime();
509 struct tm *TM = localtime(&TT);
510 Result = asctime(TM);
511 } else {
512 Result = "??? ??? ?? ??:??:?? ????\n";
513 }
514 TmpBuffer[0] = '"';
515 strcpy(TmpBuffer+1, Result);
516 unsigned Len = strlen(TmpBuffer);
517 TmpBuffer[Len-1] = '"'; // Replace the newline with a quote.
518 Tok.setKind(tok::string_literal);
519 Tok.setLength(Len);
520 Tok.setLocation(CreateString(TmpBuffer, Len, Tok.getLocation()));
521 } else {
522 assert(0 && "Unknown identifier!");
523 }
524}