1//===--- TokenLexer.h - Lex from a token buffer -----------------*- C++ -*-===//
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 defines the TokenLexer interface.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_LEX_TOKENLEXER_H
15#define LLVM_CLANG_LEX_TOKENLEXER_H
16
17#include "clang/Basic/SourceLocation.h"
18#include "llvm/ADT/ArrayRef.h"
19
20namespace clang {
21  class MacroInfo;
22  class Preprocessor;
23  class Token;
24  class MacroArgs;
25  class VAOptExpansionContext;
26
27/// TokenLexer - This implements a lexer that returns tokens from a macro body
28/// or token stream instead of lexing from a character buffer.  This is used for
29/// macro expansion and _Pragma handling, for example.
30///
31class TokenLexer {
32  /// Macro - The macro we are expanding from.  This is null if expanding a
33  /// token stream.
34  ///
35  MacroInfo *Macro;
36
37  /// ActualArgs - The actual arguments specified for a function-like macro, or
38  /// null.  The TokenLexer owns the pointed-to object.
39  MacroArgs *ActualArgs;
40
41  /// PP - The current preprocessor object we are expanding for.
42  ///
43  Preprocessor &PP;
44
45  /// Tokens - This is the pointer to an array of tokens that the macro is
46  /// defined to, with arguments expanded for function-like macros.  If this is
47  /// a token stream, these are the tokens we are returning.  This points into
48  /// the macro definition we are lexing from, a cache buffer that is owned by
49  /// the preprocessor, or some other buffer that we may or may not own
50  /// (depending on OwnsTokens).
51  /// Note that if it points into Preprocessor's cache buffer, the Preprocessor
52  /// may update the pointer as needed.
53  const Token *Tokens;
54  friend class Preprocessor;
55
56  /// NumTokens - This is the length of the Tokens array.
57  ///
58  unsigned NumTokens;
59
60  /// This is the index of the next token that Lex will return.
61  ///
62  unsigned CurTokenIdx;
63
64  /// ExpandLocStart/End - The source location range where this macro was
65  /// expanded.
66  SourceLocation ExpandLocStart, ExpandLocEnd;
67
68  /// \brief Source location pointing at the source location entry chunk that
69  /// was reserved for the current macro expansion.
70  SourceLocation MacroExpansionStart;
71
72  /// \brief The offset of the macro expansion in the
73  /// "source location address space".
74  unsigned MacroStartSLocOffset;
75
76  /// \brief Location of the macro definition.
77  SourceLocation MacroDefStart;
78  /// \brief Length of the macro definition.
79  unsigned MacroDefLength;
80
81  /// Lexical information about the expansion point of the macro: the identifier
82  /// that the macro expanded from had these properties.
83  bool AtStartOfLine : 1;
84  bool HasLeadingSpace : 1;
85
86  // NextTokGetsSpace - When this is true, the next token appended to the
87  // output list during function argument expansion will get a leading space,
88  // regardless of whether it had one to begin with or not. This is used for
89  // placemarker support. If still true after function argument expansion, the
90  // leading space will be applied to the first token following the macro
91  // expansion.
92  bool NextTokGetsSpace : 1;
93
94  /// OwnsTokens - This is true if this TokenLexer allocated the Tokens
95  /// array, and thus needs to free it when destroyed.  For simple object-like
96  /// macros (for example) we just point into the token buffer of the macro
97  /// definition, we don't make a copy of it.
98  bool OwnsTokens : 1;
99
100  /// DisableMacroExpansion - This is true when tokens lexed from the TokenLexer
101  /// should not be subject to further macro expansion.
102  bool DisableMacroExpansion : 1;
103
104  TokenLexer(const TokenLexer &) = delete;
105  void operator=(const TokenLexer &) = delete;
106public:
107  /// Create a TokenLexer for the specified macro with the specified actual
108  /// arguments.  Note that this ctor takes ownership of the ActualArgs pointer.
109  /// ILEnd specifies the location of the ')' for a function-like macro or the
110  /// identifier for an object-like macro.
111  TokenLexer(Token &Tok, SourceLocation ILEnd, MacroInfo *MI,
112             MacroArgs *ActualArgs, Preprocessor &pp)
113    : Macro(nullptr), ActualArgs(nullptr), PP(pp), OwnsTokens(false) {
114    Init(Tok, ILEnd, MI, ActualArgs);
115  }
116
117  /// Init - Initialize this TokenLexer to expand from the specified macro
118  /// with the specified argument information.  Note that this ctor takes
119  /// ownership of the ActualArgs pointer.  ILEnd specifies the location of the
120  /// ')' for a function-like macro or the identifier for an object-like macro.
121  void Init(Token &Tok, SourceLocation ILEnd, MacroInfo *MI,
122            MacroArgs *ActualArgs);
123
124  /// Create a TokenLexer for the specified token stream.  If 'OwnsTokens' is
125  /// specified, this takes ownership of the tokens and delete[]'s them when
126  /// the token lexer is empty.
127  TokenLexer(const Token *TokArray, unsigned NumToks, bool DisableExpansion,
128             bool ownsTokens, Preprocessor &pp)
129    : Macro(nullptr), ActualArgs(nullptr), PP(pp), OwnsTokens(false) {
130    Init(TokArray, NumToks, DisableExpansion, ownsTokens);
131  }
132
133  /// Init - Initialize this TokenLexer with the specified token stream.
134  /// This does not take ownership of the specified token vector.
135  ///
136  /// DisableExpansion is true when macro expansion of tokens lexed from this
137  /// stream should be disabled.
138  void Init(const Token *TokArray, unsigned NumToks,
139            bool DisableMacroExpansion, bool OwnsTokens);
140
141  ~TokenLexer() { destroy(); }
142
143  /// isNextTokenLParen - If the next token lexed will pop this macro off the
144  /// expansion stack, return 2.  If the next unexpanded token is a '(', return
145  /// 1, otherwise return 0.
146  unsigned isNextTokenLParen() const;
147
148  /// Lex - Lex and return a token from this macro stream.
149  bool Lex(Token &Tok);
150
151  /// isParsingPreprocessorDirective - Return true if we are in the middle of a
152  /// preprocessor directive.
153  bool isParsingPreprocessorDirective() const;
154
155private:
156  void destroy();
157
158  /// isAtEnd - Return true if the next lex call will pop this macro off the
159  /// include stack.
160  bool isAtEnd() const {
161    return CurTokenIdx == NumTokens;
162  }
163
164  /// Concatenates the next (sub-)sequence of \p Tokens separated by '##'
165  /// starting with LHSTok - stopping when we encounter a token that is neither
166  /// '##' nor preceded by '##'.  Places the result back into \p LHSTok and sets
167  /// \p CurIdx to point to the token following the last one that was pasted.
168  ///
169  /// Also performs the MSVC extension wide-literal token pasting involved with:
170  ///       \code L #macro-arg. \endcode
171  ///
172  /// \param[in,out] LHSTok - Contains the token to the left of '##' in \p
173  /// Tokens upon entry and will contain the resulting concatenated Token upon
174  /// exit.
175  ///
176  /// \param[in] TokenStream - The stream of Tokens we are lexing from.
177  ///
178  /// \param[in,out] CurIdx - Upon entry, \pTokens[\pCurIdx] must equal '##'
179  /// (with the exception of the MSVC extension mentioned above).  Upon exit, it
180  /// is set to the index of the token following the last token that was
181  /// concatenated together.
182  ///
183  /// \returns If this returns true, the caller should immediately return the
184  /// token.
185
186  bool pasteTokens(Token &LHSTok, ArrayRef<Token> TokenStream,
187                   unsigned int &CurIdx);
188
189  /// Calls pasteTokens above, passing in the '*this' object's Tokens and
190  /// CurTokenIdx data members.
191  bool pasteTokens(Token &Tok);
192
193
194  /// Takes the tail sequence of tokens within ReplacementToks that represent
195  /// the just expanded __VA_OPT__ tokens (possibly zero tokens) and transforms
196  /// them into a string.  \p VCtx is used to determine which token represents
197  /// the first __VA_OPT__ replacement token.
198  ///
199  /// \param[in,out] ReplacementToks - Contains the current Replacement Tokens
200  /// (prior to rescanning and token pasting), the tail end of which represents
201  /// the tokens just expanded through __VA_OPT__ processing.  These (sub)
202  /// sequence of tokens are folded into one stringified token.
203  ///
204  /// \param[in] VCtx - contains relevent contextual information about the
205  /// state of the tokens around and including the __VA_OPT__ token, necessary
206  /// for stringification.
207
208  void stringifyVAOPTContents(SmallVectorImpl<Token> &ReplacementToks,
209                              const VAOptExpansionContext &VCtx,
210                              SourceLocation VAOPTClosingParenLoc);
211
212  /// Expand the arguments of a function-like macro so that we can quickly
213  /// return preexpanded tokens from Tokens.
214  void ExpandFunctionArguments();
215
216  /// HandleMicrosoftCommentPaste - In microsoft compatibility mode, /##/ pastes
217  /// together to form a comment that comments out everything in the current
218  /// macro, other active macros, and anything left on the current physical
219  /// source line of the expanded buffer.  Handle this by returning the
220  /// first token on the next line.
221  void HandleMicrosoftCommentPaste(Token &Tok, SourceLocation OpLoc);
222
223  /// \brief If \p loc is a FileID and points inside the current macro
224  /// definition, returns the appropriate source location pointing at the
225  /// macro expansion source location entry.
226  SourceLocation getExpansionLocForMacroDefLoc(SourceLocation loc) const;
227
228  /// \brief Creates SLocEntries and updates the locations of macro argument
229  /// tokens to their new expanded locations.
230  ///
231  /// \param ArgIdSpellLoc the location of the macro argument id inside the
232  /// macro definition.
233  void updateLocForMacroArgTokens(SourceLocation ArgIdSpellLoc,
234                                  Token *begin_tokens, Token *end_tokens);
235
236  /// Remove comma ahead of __VA_ARGS__, if present, according to compiler
237  /// dialect settings.  Returns true if the comma is removed.
238  bool MaybeRemoveCommaBeforeVaArgs(SmallVectorImpl<Token> &ResultToks,
239                                    bool HasPasteOperator,
240                                    MacroInfo *Macro, unsigned MacroArgNo,
241                                    Preprocessor &PP);
242
243  void PropagateLineStartLeadingSpaceInfo(Token &Result);
244};
245
246}  // end namespace clang
247
248#endif
249