1 //===--- TokenLexer.cpp - Lex from a token stream -------------------------===//
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 TokenLexer interface.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Lex/TokenLexer.h"
15 #include "MacroArgs.h"
16 #include "clang/Lex/MacroInfo.h"
17 #include "clang/Lex/Preprocessor.h"
18 #include "clang/Basic/SourceManager.h"
19 #include "clang/Lex/LexDiagnostic.h"
20 #include "llvm/ADT/SmallVector.h"
21 using namespace clang;
22 
23 
24 /// Create a TokenLexer for the specified macro with the specified actual
25 /// arguments.  Note that this ctor takes ownership of the ActualArgs pointer.
26 void TokenLexer::Init(Token &Tok, SourceLocation ILEnd, MacroArgs *Actuals) {
27   // If the client is reusing a TokenLexer, make sure to free any memory
28   // associated with it.
29   destroy();
30 
31   Macro = PP.getMacroInfo(Tok.getIdentifierInfo());
32   ActualArgs = Actuals;
33   CurToken = 0;
34 
35   InstantiateLocStart = Tok.getLocation();
36   InstantiateLocEnd = ILEnd;
37   AtStartOfLine = Tok.isAtStartOfLine();
38   HasLeadingSpace = Tok.hasLeadingSpace();
39   Tokens = &*Macro->tokens_begin();
40   OwnsTokens = false;
41   DisableMacroExpansion = false;
42   NumTokens = Macro->tokens_end()-Macro->tokens_begin();
43 
44   // If this is a function-like macro, expand the arguments and change
45   // Tokens to point to the expanded tokens.
46   if (Macro->isFunctionLike() && Macro->getNumArgs())
47     ExpandFunctionArguments();
48 
49   // Mark the macro as currently disabled, so that it is not recursively
50   // expanded.  The macro must be disabled only after argument pre-expansion of
51   // function-like macro arguments occurs.
52   Macro->DisableMacro();
53 }
54 
55 
56 
57 /// Create a TokenLexer for the specified token stream.  This does not
58 /// take ownership of the specified token vector.
59 void TokenLexer::Init(const Token *TokArray, unsigned NumToks,
60                       bool disableMacroExpansion, bool ownsTokens) {
61   // If the client is reusing a TokenLexer, make sure to free any memory
62   // associated with it.
63   destroy();
64 
65   Macro = 0;
66   ActualArgs = 0;
67   Tokens = TokArray;
68   OwnsTokens = ownsTokens;
69   DisableMacroExpansion = disableMacroExpansion;
70   NumTokens = NumToks;
71   CurToken = 0;
72   InstantiateLocStart = InstantiateLocEnd = SourceLocation();
73   AtStartOfLine = false;
74   HasLeadingSpace = false;
75 
76   // Set HasLeadingSpace/AtStartOfLine so that the first token will be
77   // returned unmodified.
78   if (NumToks != 0) {
79     AtStartOfLine   = TokArray[0].isAtStartOfLine();
80     HasLeadingSpace = TokArray[0].hasLeadingSpace();
81   }
82 }
83 
84 
85 void TokenLexer::destroy() {
86   // If this was a function-like macro that actually uses its arguments, delete
87   // the expanded tokens.
88   if (OwnsTokens) {
89     delete [] Tokens;
90     Tokens = 0;
91     OwnsTokens = false;
92   }
93 
94   // TokenLexer owns its formal arguments.
95   if (ActualArgs) ActualArgs->destroy();
96 }
97 
98 /// Expand the arguments of a function-like macro so that we can quickly
99 /// return preexpanded tokens from Tokens.
100 void TokenLexer::ExpandFunctionArguments() {
101   llvm::SmallVector<Token, 128> ResultToks;
102 
103   // Loop through 'Tokens', expanding them into ResultToks.  Keep
104   // track of whether we change anything.  If not, no need to keep them.  If so,
105   // we install the newly expanded sequence as the new 'Tokens' list.
106   bool MadeChange = false;
107 
108   // NextTokGetsSpace - When this is true, the next token appended to the
109   // output list will get a leading space, regardless of whether it had one to
110   // begin with or not.  This is used for placemarker support.
111   bool NextTokGetsSpace = false;
112 
113   for (unsigned i = 0, e = NumTokens; i != e; ++i) {
114     // If we found the stringify operator, get the argument stringified.  The
115     // preprocessor already verified that the following token is a macro name
116     // when the #define was parsed.
117     const Token &CurTok = Tokens[i];
118     if (CurTok.is(tok::hash) || CurTok.is(tok::hashat)) {
119       int ArgNo = Macro->getArgumentNum(Tokens[i+1].getIdentifierInfo());
120       assert(ArgNo != -1 && "Token following # is not an argument?");
121 
122       Token Res;
123       if (CurTok.is(tok::hash))  // Stringify
124         Res = ActualArgs->getStringifiedArgument(ArgNo, PP);
125       else {
126         // 'charify': don't bother caching these.
127         Res = MacroArgs::StringifyArgument(ActualArgs->getUnexpArgument(ArgNo),
128                                            PP, true);
129       }
130 
131       // The stringified/charified string leading space flag gets set to match
132       // the #/#@ operator.
133       if (CurTok.hasLeadingSpace() || NextTokGetsSpace)
134         Res.setFlag(Token::LeadingSpace);
135 
136       ResultToks.push_back(Res);
137       MadeChange = true;
138       ++i;  // Skip arg name.
139       NextTokGetsSpace = false;
140       continue;
141     }
142 
143     // Otherwise, if this is not an argument token, just add the token to the
144     // output buffer.
145     IdentifierInfo *II = CurTok.getIdentifierInfo();
146     int ArgNo = II ? Macro->getArgumentNum(II) : -1;
147     if (ArgNo == -1) {
148       // This isn't an argument, just add it.
149       ResultToks.push_back(CurTok);
150 
151       if (NextTokGetsSpace) {
152         ResultToks.back().setFlag(Token::LeadingSpace);
153         NextTokGetsSpace = false;
154       }
155       continue;
156     }
157 
158     // An argument is expanded somehow, the result is different than the
159     // input.
160     MadeChange = true;
161 
162     // Otherwise, this is a use of the argument.  Find out if there is a paste
163     // (##) operator before or after the argument.
164     bool PasteBefore =
165       !ResultToks.empty() && ResultToks.back().is(tok::hashhash);
166     bool PasteAfter = i+1 != e && Tokens[i+1].is(tok::hashhash);
167 
168     // If it is not the LHS/RHS of a ## operator, we must pre-expand the
169     // argument and substitute the expanded tokens into the result.  This is
170     // C99 6.10.3.1p1.
171     if (!PasteBefore && !PasteAfter) {
172       const Token *ResultArgToks;
173 
174       // Only preexpand the argument if it could possibly need it.  This
175       // avoids some work in common cases.
176       const Token *ArgTok = ActualArgs->getUnexpArgument(ArgNo);
177       if (ActualArgs->ArgNeedsPreexpansion(ArgTok, PP))
178         ResultArgToks = &ActualArgs->getPreExpArgument(ArgNo, PP)[0];
179       else
180         ResultArgToks = ArgTok;  // Use non-preexpanded tokens.
181 
182       // If the arg token expanded into anything, append it.
183       if (ResultArgToks->isNot(tok::eof)) {
184         unsigned FirstResult = ResultToks.size();
185         unsigned NumToks = MacroArgs::getArgLength(ResultArgToks);
186         ResultToks.append(ResultArgToks, ResultArgToks+NumToks);
187 
188         // If any tokens were substituted from the argument, the whitespace
189         // before the first token should match the whitespace of the arg
190         // identifier.
191         ResultToks[FirstResult].setFlagValue(Token::LeadingSpace,
192                                              CurTok.hasLeadingSpace() ||
193                                              NextTokGetsSpace);
194         NextTokGetsSpace = false;
195       } else {
196         // If this is an empty argument, and if there was whitespace before the
197         // formal token, make sure the next token gets whitespace before it.
198         NextTokGetsSpace = CurTok.hasLeadingSpace();
199       }
200       continue;
201     }
202 
203     // Okay, we have a token that is either the LHS or RHS of a paste (##)
204     // argument.  It gets substituted as its non-pre-expanded tokens.
205     const Token *ArgToks = ActualArgs->getUnexpArgument(ArgNo);
206     unsigned NumToks = MacroArgs::getArgLength(ArgToks);
207     if (NumToks) {  // Not an empty argument?
208       // If this is the GNU ", ## __VA_ARG__" extension, and we just learned
209       // that __VA_ARG__ expands to multiple tokens, avoid a pasting error when
210       // the expander trys to paste ',' with the first token of the __VA_ARG__
211       // expansion.
212       if (PasteBefore && ResultToks.size() >= 2 &&
213           ResultToks[ResultToks.size()-2].is(tok::comma) &&
214           (unsigned)ArgNo == Macro->getNumArgs()-1 &&
215           Macro->isVariadic()) {
216         // Remove the paste operator, report use of the extension.
217         PP.Diag(ResultToks.back().getLocation(), diag::ext_paste_comma);
218         ResultToks.pop_back();
219       }
220 
221       ResultToks.append(ArgToks, ArgToks+NumToks);
222 
223       // If this token (the macro argument) was supposed to get leading
224       // whitespace, transfer this information onto the first token of the
225       // expansion.
226       //
227       // Do not do this if the paste operator occurs before the macro argument,
228       // as in "A ## MACROARG".  In valid code, the first token will get
229       // smooshed onto the preceding one anyway (forming AMACROARG).  In
230       // assembler-with-cpp mode, invalid pastes are allowed through: in this
231       // case, we do not want the extra whitespace to be added.  For example,
232       // we want ". ## foo" -> ".foo" not ". foo".
233       if ((CurTok.hasLeadingSpace() || NextTokGetsSpace) &&
234           !PasteBefore)
235         ResultToks[ResultToks.size()-NumToks].setFlag(Token::LeadingSpace);
236 
237       NextTokGetsSpace = false;
238       continue;
239     }
240 
241     // If an empty argument is on the LHS or RHS of a paste, the standard (C99
242     // 6.10.3.3p2,3) calls for a bunch of placemarker stuff to occur.  We
243     // implement this by eating ## operators when a LHS or RHS expands to
244     // empty.
245     NextTokGetsSpace |= CurTok.hasLeadingSpace();
246     if (PasteAfter) {
247       // Discard the argument token and skip (don't copy to the expansion
248       // buffer) the paste operator after it.
249       NextTokGetsSpace |= Tokens[i+1].hasLeadingSpace();
250       ++i;
251       continue;
252     }
253 
254     // If this is on the RHS of a paste operator, we've already copied the
255     // paste operator to the ResultToks list.  Remove it.
256     assert(PasteBefore && ResultToks.back().is(tok::hashhash));
257     NextTokGetsSpace |= ResultToks.back().hasLeadingSpace();
258     ResultToks.pop_back();
259 
260     // If this is the __VA_ARGS__ token, and if the argument wasn't provided,
261     // and if the macro had at least one real argument, and if the token before
262     // the ## was a comma, remove the comma.
263     if ((unsigned)ArgNo == Macro->getNumArgs()-1 && // is __VA_ARGS__
264         ActualArgs->isVarargsElidedUse() &&       // Argument elided.
265         !ResultToks.empty() && ResultToks.back().is(tok::comma)) {
266       // Never add a space, even if the comma, ##, or arg had a space.
267       NextTokGetsSpace = false;
268       // Remove the paste operator, report use of the extension.
269       PP.Diag(ResultToks.back().getLocation(), diag::ext_paste_comma);
270       ResultToks.pop_back();
271     }
272     continue;
273   }
274 
275   // If anything changed, install this as the new Tokens list.
276   if (MadeChange) {
277     assert(!OwnsTokens && "This would leak if we already own the token list");
278     // This is deleted in the dtor.
279     NumTokens = ResultToks.size();
280     llvm::BumpPtrAllocator &Alloc = PP.getPreprocessorAllocator();
281     Token *Res =
282       static_cast<Token *>(Alloc.Allocate(sizeof(Token)*ResultToks.size(),
283                                           llvm::alignof<Token>()));
284     if (NumTokens)
285       memcpy(Res, &ResultToks[0], NumTokens*sizeof(Token));
286     Tokens = Res;
287 
288     // The preprocessor bump pointer owns these tokens, not us.
289     OwnsTokens = false;
290   }
291 }
292 
293 /// Lex - Lex and return a token from this macro stream.
294 ///
295 void TokenLexer::Lex(Token &Tok) {
296   // Lexing off the end of the macro, pop this macro off the expansion stack.
297   if (isAtEnd()) {
298     // If this is a macro (not a token stream), mark the macro enabled now
299     // that it is no longer being expanded.
300     if (Macro) Macro->EnableMacro();
301 
302     // Pop this context off the preprocessors lexer stack and get the next
303     // token.  This will delete "this" so remember the PP instance var.
304     Preprocessor &PPCache = PP;
305     if (PP.HandleEndOfTokenLexer(Tok))
306       return;
307 
308     // HandleEndOfTokenLexer may not return a token.  If it doesn't, lex
309     // whatever is next.
310     return PPCache.Lex(Tok);
311   }
312 
313   // If this is the first token of the expanded result, we inherit spacing
314   // properties later.
315   bool isFirstToken = CurToken == 0;
316 
317   // Get the next token to return.
318   Tok = Tokens[CurToken++];
319 
320   bool TokenIsFromPaste = false;
321 
322   // If this token is followed by a token paste (##) operator, paste the tokens!
323   if (!isAtEnd() && Tokens[CurToken].is(tok::hashhash)) {
324     if (PasteTokens(Tok)) {
325       // When handling the microsoft /##/ extension, the final token is
326       // returned by PasteTokens, not the pasted token.
327       return;
328     } else {
329       TokenIsFromPaste = true;
330     }
331   }
332 
333   // The token's current location indicate where the token was lexed from.  We
334   // need this information to compute the spelling of the token, but any
335   // diagnostics for the expanded token should appear as if they came from
336   // InstantiationLoc.  Pull this information together into a new SourceLocation
337   // that captures all of this.
338   if (InstantiateLocStart.isValid()) {   // Don't do this for token streams.
339     SourceManager &SM = PP.getSourceManager();
340     Tok.setLocation(SM.createInstantiationLoc(Tok.getLocation(),
341                                               InstantiateLocStart,
342                                               InstantiateLocEnd,
343                                               Tok.getLength()));
344   }
345 
346   // If this is the first token, set the lexical properties of the token to
347   // match the lexical properties of the macro identifier.
348   if (isFirstToken) {
349     Tok.setFlagValue(Token::StartOfLine , AtStartOfLine);
350     Tok.setFlagValue(Token::LeadingSpace, HasLeadingSpace);
351   }
352 
353   // Handle recursive expansion!
354   if (!Tok.isAnnotation() && Tok.getIdentifierInfo() != 0) {
355     // Change the kind of this identifier to the appropriate token kind, e.g.
356     // turning "for" into a keyword.
357     IdentifierInfo *II = Tok.getIdentifierInfo();
358     Tok.setKind(II->getTokenID());
359 
360     // If this identifier was poisoned and from a paste, emit an error.  This
361     // won't be handled by Preprocessor::HandleIdentifier because this is coming
362     // from a macro expansion.
363     if (II->isPoisoned() && TokenIsFromPaste) {
364       // We warn about __VA_ARGS__ with poisoning.
365       if (II->isStr("__VA_ARGS__"))
366         PP.Diag(Tok, diag::ext_pp_bad_vaargs_use);
367       else
368         PP.Diag(Tok, diag::err_pp_used_poisoned_id);
369     }
370 
371     if (!DisableMacroExpansion && II->isHandleIdentifierCase())
372       PP.HandleIdentifier(Tok);
373   }
374 
375   // Otherwise, return a normal token.
376 }
377 
378 /// PasteTokens - Tok is the LHS of a ## operator, and CurToken is the ##
379 /// operator.  Read the ## and RHS, and paste the LHS/RHS together.  If there
380 /// are more ## after it, chomp them iteratively.  Return the result as Tok.
381 /// If this returns true, the caller should immediately return the token.
382 bool TokenLexer::PasteTokens(Token &Tok) {
383   llvm::SmallVector<char, 128> Buffer;
384   const char *ResultTokStrPtr = 0;
385   do {
386     // Consume the ## operator.
387     SourceLocation PasteOpLoc = Tokens[CurToken].getLocation();
388     ++CurToken;
389     assert(!isAtEnd() && "No token on the RHS of a paste operator!");
390 
391     // Get the RHS token.
392     const Token &RHS = Tokens[CurToken];
393 
394     // Allocate space for the result token.  This is guaranteed to be enough for
395     // the two tokens.
396     Buffer.resize(Tok.getLength() + RHS.getLength());
397 
398     // Get the spelling of the LHS token in Buffer.
399     const char *BufPtr = &Buffer[0];
400     unsigned LHSLen = PP.getSpelling(Tok, BufPtr);
401     if (BufPtr != &Buffer[0])   // Really, we want the chars in Buffer!
402       memcpy(&Buffer[0], BufPtr, LHSLen);
403 
404     BufPtr = &Buffer[LHSLen];
405     unsigned RHSLen = PP.getSpelling(RHS, BufPtr);
406     if (BufPtr != &Buffer[LHSLen])   // Really, we want the chars in Buffer!
407       memcpy(&Buffer[LHSLen], BufPtr, RHSLen);
408 
409     // Trim excess space.
410     Buffer.resize(LHSLen+RHSLen);
411 
412     // Plop the pasted result (including the trailing newline and null) into a
413     // scratch buffer where we can lex it.
414     Token ResultTokTmp;
415     ResultTokTmp.startToken();
416 
417     // Claim that the tmp token is a string_literal so that we can get the
418     // character pointer back from CreateString.
419     ResultTokTmp.setKind(tok::string_literal);
420     PP.CreateString(&Buffer[0], Buffer.size(), ResultTokTmp);
421     SourceLocation ResultTokLoc = ResultTokTmp.getLocation();
422     ResultTokStrPtr = ResultTokTmp.getLiteralData();
423 
424     // Lex the resultant pasted token into Result.
425     Token Result;
426 
427     if (Tok.is(tok::identifier) && RHS.is(tok::identifier)) {
428       // Common paste case: identifier+identifier = identifier.  Avoid creating
429       // a lexer and other overhead.
430       PP.IncrementPasteCounter(true);
431       Result.startToken();
432       Result.setKind(tok::identifier);
433       Result.setLocation(ResultTokLoc);
434       Result.setLength(LHSLen+RHSLen);
435     } else {
436       PP.IncrementPasteCounter(false);
437 
438       assert(ResultTokLoc.isFileID() &&
439              "Should be a raw location into scratch buffer");
440       SourceManager &SourceMgr = PP.getSourceManager();
441       FileID LocFileID = SourceMgr.getFileID(ResultTokLoc);
442 
443       const char *ScratchBufStart = SourceMgr.getBufferData(LocFileID).first;
444 
445       // Make a lexer to lex this string from.  Lex just this one token.
446       // Make a lexer object so that we lex and expand the paste result.
447       Lexer TL(SourceMgr.getLocForStartOfFile(LocFileID),
448                PP.getLangOptions(), ScratchBufStart,
449                ResultTokStrPtr, ResultTokStrPtr+LHSLen+RHSLen);
450 
451       // Lex a token in raw mode.  This way it won't look up identifiers
452       // automatically, lexing off the end will return an eof token, and
453       // warnings are disabled.  This returns true if the result token is the
454       // entire buffer.
455       bool isInvalid = !TL.LexFromRawLexer(Result);
456 
457       // If we got an EOF token, we didn't form even ONE token.  For example, we
458       // did "/ ## /" to get "//".
459       isInvalid |= Result.is(tok::eof);
460 
461       // If pasting the two tokens didn't form a full new token, this is an
462       // error.  This occurs with "x ## +"  and other stuff.  Return with Tok
463       // unmodified and with RHS as the next token to lex.
464       if (isInvalid) {
465         // Test for the Microsoft extension of /##/ turning into // here on the
466         // error path.
467         if (PP.getLangOptions().Microsoft && Tok.is(tok::slash) &&
468             RHS.is(tok::slash)) {
469           HandleMicrosoftCommentPaste(Tok);
470           return true;
471         }
472 
473         // Do not emit the warning when preprocessing assembler code.
474         if (!PP.getLangOptions().AsmPreprocessor) {
475           // Explicitly convert the token location to have proper instantiation
476           // information so that the user knows where it came from.
477           SourceManager &SM = PP.getSourceManager();
478           SourceLocation Loc =
479             SM.createInstantiationLoc(PasteOpLoc, InstantiateLocStart,
480                                       InstantiateLocEnd, 2);
481           PP.Diag(Loc, diag::err_pp_bad_paste)
482             << std::string(Buffer.begin(), Buffer.end());
483         }
484 
485         // Do not consume the RHS.
486         --CurToken;
487       }
488 
489       // Turn ## into 'unknown' to avoid # ## # from looking like a paste
490       // operator.
491       if (Result.is(tok::hashhash))
492         Result.setKind(tok::unknown);
493     }
494 
495     // Transfer properties of the LHS over the the Result.
496     Result.setFlagValue(Token::StartOfLine , Tok.isAtStartOfLine());
497     Result.setFlagValue(Token::LeadingSpace, Tok.hasLeadingSpace());
498 
499     // Finally, replace LHS with the result, consume the RHS, and iterate.
500     ++CurToken;
501     Tok = Result;
502   } while (!isAtEnd() && Tokens[CurToken].is(tok::hashhash));
503 
504   // Now that we got the result token, it will be subject to expansion.  Since
505   // token pasting re-lexes the result token in raw mode, identifier information
506   // isn't looked up.  As such, if the result is an identifier, look up id info.
507   if (Tok.is(tok::identifier)) {
508     // Look up the identifier info for the token.  We disabled identifier lookup
509     // by saying we're skipping contents, so we need to do this manually.
510     IdentifierInfo *II = PP.LookUpIdentifierInfo(Tok, ResultTokStrPtr);
511     Tok.setIdentifierInfo(II);
512   }
513   return false;
514 }
515 
516 /// isNextTokenLParen - If the next token lexed will pop this macro off the
517 /// expansion stack, return 2.  If the next unexpanded token is a '(', return
518 /// 1, otherwise return 0.
519 unsigned TokenLexer::isNextTokenLParen() const {
520   // Out of tokens?
521   if (isAtEnd())
522     return 2;
523   return Tokens[CurToken].is(tok::l_paren);
524 }
525 
526 
527 /// HandleMicrosoftCommentPaste - In microsoft compatibility mode, /##/ pastes
528 /// together to form a comment that comments out everything in the current
529 /// macro, other active macros, and anything left on the current physical
530 /// source line of the instantiated buffer.  Handle this by returning the
531 /// first token on the next line.
532 void TokenLexer::HandleMicrosoftCommentPaste(Token &Tok) {
533   // We 'comment out' the rest of this macro by just ignoring the rest of the
534   // tokens that have not been lexed yet, if any.
535 
536   // Since this must be a macro, mark the macro enabled now that it is no longer
537   // being expanded.
538   assert(Macro && "Token streams can't paste comments");
539   Macro->EnableMacro();
540 
541   PP.HandleMicrosoftCommentPaste(Tok);
542 }
543