Macro-Expansion.html 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  2. <html>
  3. <!-- Created by GNU Texinfo 5.2, http://www.gnu.org/software/texinfo/ -->
  4. <head>
  5. <title>The GNU C Preprocessor Internals: Macro Expansion</title>
  6. <meta name="description" content="The GNU C Preprocessor Internals: Macro Expansion">
  7. <meta name="keywords" content="The GNU C Preprocessor Internals: Macro Expansion">
  8. <meta name="resource-type" content="document">
  9. <meta name="distribution" content="global">
  10. <meta name="Generator" content="makeinfo">
  11. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  12. <link href="index.html#Top" rel="start" title="Top">
  13. <link href="Concept-Index.html#Concept-Index" rel="index" title="Concept Index">
  14. <link href="index.html#SEC_Contents" rel="contents" title="Table of Contents">
  15. <link href="index.html#Top" rel="up" title="Top">
  16. <link href="Token-Spacing.html#Token-Spacing" rel="next" title="Token Spacing">
  17. <link href="Hash-Nodes.html#Hash-Nodes" rel="prev" title="Hash Nodes">
  18. <style type="text/css">
  19. <!--
  20. a.summary-letter {text-decoration: none}
  21. blockquote.smallquotation {font-size: smaller}
  22. div.display {margin-left: 3.2em}
  23. div.example {margin-left: 3.2em}
  24. div.indentedblock {margin-left: 3.2em}
  25. div.lisp {margin-left: 3.2em}
  26. div.smalldisplay {margin-left: 3.2em}
  27. div.smallexample {margin-left: 3.2em}
  28. div.smallindentedblock {margin-left: 3.2em; font-size: smaller}
  29. div.smalllisp {margin-left: 3.2em}
  30. kbd {font-style:oblique}
  31. pre.display {font-family: inherit}
  32. pre.format {font-family: inherit}
  33. pre.menu-comment {font-family: serif}
  34. pre.menu-preformatted {font-family: serif}
  35. pre.smalldisplay {font-family: inherit; font-size: smaller}
  36. pre.smallexample {font-size: smaller}
  37. pre.smallformat {font-family: inherit; font-size: smaller}
  38. pre.smalllisp {font-size: smaller}
  39. span.nocodebreak {white-space:nowrap}
  40. span.nolinebreak {white-space:nowrap}
  41. span.roman {font-family:serif; font-weight:normal}
  42. span.sansserif {font-family:sans-serif; font-weight:normal}
  43. ul.no-bullet {list-style: none}
  44. -->
  45. </style>
  46. </head>
  47. <body lang="en" bgcolor="#FFFFFF" text="#000000" link="#0000FF" vlink="#800080" alink="#FF0000">
  48. <a name="Macro-Expansion"></a>
  49. <div class="header">
  50. <p>
  51. Next: <a href="Token-Spacing.html#Token-Spacing" accesskey="n" rel="next">Token Spacing</a>, Previous: <a href="Hash-Nodes.html#Hash-Nodes" accesskey="p" rel="prev">Hash Nodes</a>, Up: <a href="index.html#Top" accesskey="u" rel="up">Top</a> &nbsp; [<a href="index.html#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="Concept-Index.html#Concept-Index" title="Index" rel="index">Index</a>]</p>
  52. </div>
  53. <hr>
  54. <a name="Macro-Expansion-Algorithm"></a>
  55. <h2 class="unnumbered">Macro Expansion Algorithm</h2>
  56. <a name="index-macro-expansion"></a>
  57. <p>Macro expansion is a tricky operation, fraught with nasty corner cases
  58. and situations that render what you thought was a nifty way to
  59. optimize the preprocessor&rsquo;s expansion algorithm wrong in quite subtle
  60. ways.
  61. </p>
  62. <p>I strongly recommend you have a good grasp of how the C and C++
  63. standards require macros to be expanded before diving into this
  64. section, let alone the code!. If you don&rsquo;t have a clear mental
  65. picture of how things like nested macro expansion, stringizing and
  66. token pasting are supposed to work, damage to your sanity can quickly
  67. result.
  68. </p>
  69. <a name="Internal-representation-of-macros"></a>
  70. <h3 class="section">Internal representation of macros</h3>
  71. <a name="index-macro-representation-_0028internal_0029"></a>
  72. <p>The preprocessor stores macro expansions in tokenized form. This
  73. saves repeated lexing passes during expansion, at the cost of a small
  74. increase in memory consumption on average. The tokens are stored
  75. contiguously in memory, so a pointer to the first one and a token
  76. count is all you need to get the replacement list of a macro.
  77. </p>
  78. <p>If the macro is a function-like macro the preprocessor also stores its
  79. parameters, in the form of an ordered list of pointers to the hash
  80. table entry of each parameter&rsquo;s identifier. Further, in the macro&rsquo;s
  81. stored expansion each occurrence of a parameter is replaced with a
  82. special token of type <code>CPP_MACRO_ARG</code>. Each such token holds the
  83. index of the parameter it represents in the parameter list, which
  84. allows rapid replacement of parameters with their arguments during
  85. expansion. Despite this optimization it is still necessary to store
  86. the original parameters to the macro, both for dumping with e.g.,
  87. <samp>-dD</samp>, and to warn about non-trivial macro redefinitions when
  88. the parameter names have changed.
  89. </p>
  90. <a name="Macro-expansion-overview"></a>
  91. <h3 class="section">Macro expansion overview</h3>
  92. <p>The preprocessor maintains a <em>context stack</em>, implemented as a
  93. linked list of <code>cpp_context</code> structures, which together represent
  94. the macro expansion state at any one time. The <code>struct
  95. cpp_reader</code> member variable <code>context</code> points to the current top
  96. of this stack. The top normally holds the unexpanded replacement list
  97. of the innermost macro under expansion, except when cpplib is about to
  98. pre-expand an argument, in which case it holds that argument&rsquo;s
  99. unexpanded tokens.
  100. </p>
  101. <p>When there are no macros under expansion, cpplib is in <em>base
  102. context</em>. All contexts other than the base context contain a
  103. contiguous list of tokens delimited by a starting and ending token.
  104. When not in base context, cpplib obtains the next token from the list
  105. of the top context. If there are no tokens left in the list, it pops
  106. that context off the stack, and subsequent ones if necessary, until an
  107. unexhausted context is found or it returns to base context. In base
  108. context, cpplib reads tokens directly from the lexer.
  109. </p>
  110. <p>If it encounters an identifier that is both a macro and enabled for
  111. expansion, cpplib prepares to push a new context for that macro on the
  112. stack by calling the routine <code>enter_macro_context</code>. When this
  113. routine returns, the new context will contain the unexpanded tokens of
  114. the replacement list of that macro. In the case of function-like
  115. macros, <code>enter_macro_context</code> also replaces any parameters in the
  116. replacement list, stored as <code>CPP_MACRO_ARG</code> tokens, with the
  117. appropriate macro argument. If the standard requires that the
  118. parameter be replaced with its expanded argument, the argument will
  119. have been fully macro expanded first.
  120. </p>
  121. <p><code>enter_macro_context</code> also handles special macros like
  122. <code>__LINE__</code>. Although these macros expand to a single token which
  123. cannot contain any further macros, for reasons of token spacing
  124. (see <a href="Token-Spacing.html#Token-Spacing">Token Spacing</a>) and simplicity of implementation, cpplib
  125. handles these special macros by pushing a context containing just that
  126. one token.
  127. </p>
  128. <p>The final thing that <code>enter_macro_context</code> does before returning
  129. is to mark the macro disabled for expansion (except for special macros
  130. like <code>__TIME__</code>). The macro is re-enabled when its context is
  131. later popped from the context stack, as described above. This strict
  132. ordering ensures that a macro is disabled whilst its expansion is
  133. being scanned, but that it is <em>not</em> disabled whilst any arguments
  134. to it are being expanded.
  135. </p>
  136. <a name="Scanning-the-replacement-list-for-macros-to-expand"></a>
  137. <h3 class="section">Scanning the replacement list for macros to expand</h3>
  138. <p>The C standard states that, after any parameters have been replaced
  139. with their possibly-expanded arguments, the replacement list is
  140. scanned for nested macros. Further, any identifiers in the
  141. replacement list that are not expanded during this scan are never
  142. again eligible for expansion in the future, if the reason they were
  143. not expanded is that the macro in question was disabled.
  144. </p>
  145. <p>Clearly this latter condition can only apply to tokens resulting from
  146. argument pre-expansion. Other tokens never have an opportunity to be
  147. re-tested for expansion. It is possible for identifiers that are
  148. function-like macros to not expand initially but to expand during a
  149. later scan. This occurs when the identifier is the last token of an
  150. argument (and therefore originally followed by a comma or a closing
  151. parenthesis in its macro&rsquo;s argument list), and when it replaces its
  152. parameter in the macro&rsquo;s replacement list, the subsequent token
  153. happens to be an opening parenthesis (itself possibly the first token
  154. of an argument).
  155. </p>
  156. <p>It is important to note that when cpplib reads the last token of a
  157. given context, that context still remains on the stack. Only when
  158. looking for the <em>next</em> token do we pop it off the stack and drop
  159. to a lower context. This makes backing up by one token easy, but more
  160. importantly ensures that the macro corresponding to the current
  161. context is still disabled when we are considering the last token of
  162. its replacement list for expansion (or indeed expanding it). As an
  163. example, which illustrates many of the points above, consider
  164. </p>
  165. <div class="smallexample">
  166. <pre class="smallexample">#define foo(x) bar x
  167. foo(foo) (2)
  168. </pre></div>
  169. <p>which fully expands to &lsquo;<samp>bar foo (2)</samp>&rsquo;. During pre-expansion
  170. of the argument, &lsquo;<samp>foo</samp>&rsquo; does not expand even though the macro is
  171. enabled, since it has no following parenthesis [pre-expansion of an
  172. argument only uses tokens from that argument; it cannot take tokens
  173. from whatever follows the macro invocation]. This still leaves the
  174. argument token &lsquo;<samp>foo</samp>&rsquo; eligible for future expansion. Then, when
  175. re-scanning after argument replacement, the token &lsquo;<samp>foo</samp>&rsquo; is
  176. rejected for expansion, and marked ineligible for future expansion,
  177. since the macro is now disabled. It is disabled because the
  178. replacement list &lsquo;<samp>bar foo</samp>&rsquo; of the macro is still on the context
  179. stack.
  180. </p>
  181. <p>If instead the algorithm looked for an opening parenthesis first and
  182. then tested whether the macro were disabled it would be subtly wrong.
  183. In the example above, the replacement list of &lsquo;<samp>foo</samp>&rsquo; would be
  184. popped in the process of finding the parenthesis, re-enabling
  185. &lsquo;<samp>foo</samp>&rsquo; and expanding it a second time.
  186. </p>
  187. <a name="Looking-for-a-function_002dlike-macro_0027s-opening-parenthesis"></a>
  188. <h3 class="section">Looking for a function-like macro&rsquo;s opening parenthesis</h3>
  189. <p>Function-like macros only expand when immediately followed by a
  190. parenthesis. To do this cpplib needs to temporarily disable macros
  191. and read the next token. Unfortunately, because of spacing issues
  192. (see <a href="Token-Spacing.html#Token-Spacing">Token Spacing</a>), there can be fake padding tokens in-between,
  193. and if the next real token is not a parenthesis cpplib needs to be
  194. able to back up that one token as well as retain the information in
  195. any intervening padding tokens.
  196. </p>
  197. <p>Backing up more than one token when macros are involved is not
  198. permitted by cpplib, because in general it might involve issues like
  199. restoring popped contexts onto the context stack, which are too hard.
  200. Instead, searching for the parenthesis is handled by a special
  201. function, <code>funlike_invocation_p</code>, which remembers padding
  202. information as it reads tokens. If the next real token is not an
  203. opening parenthesis, it backs up that one token, and then pushes an
  204. extra context just containing the padding information if necessary.
  205. </p>
  206. <a name="Marking-tokens-ineligible-for-future-expansion"></a>
  207. <h3 class="section">Marking tokens ineligible for future expansion</h3>
  208. <p>As discussed above, cpplib needs a way of marking tokens as
  209. unexpandable. Since the tokens cpplib handles are read-only once they
  210. have been lexed, it instead makes a copy of the token and adds the
  211. flag <code>NO_EXPAND</code> to the copy.
  212. </p>
  213. <p>For efficiency and to simplify memory management by avoiding having to
  214. remember to free these tokens, they are allocated as temporary tokens
  215. from the lexer&rsquo;s current token run (see <a href="Lexer.html#Lexing-a-line">Lexing a line</a>) using the
  216. function <code>_cpp_temp_token</code>. The tokens are then re-used once the
  217. current line of tokens has been read in.
  218. </p>
  219. <p>This might sound unsafe. However, tokens runs are not re-used at the
  220. end of a line if it happens to be in the middle of a macro argument
  221. list, and cpplib only wants to back-up more than one lexer token in
  222. situations where no macro expansion is involved, so the optimization
  223. is safe.
  224. </p>
  225. <hr>
  226. <div class="header">
  227. <p>
  228. Next: <a href="Token-Spacing.html#Token-Spacing" accesskey="n" rel="next">Token Spacing</a>, Previous: <a href="Hash-Nodes.html#Hash-Nodes" accesskey="p" rel="prev">Hash Nodes</a>, Up: <a href="index.html#Top" accesskey="u" rel="up">Top</a> &nbsp; [<a href="index.html#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="Concept-Index.html#Concept-Index" title="Index" rel="index">Index</a>]</p>
  229. </div>
  230. </body>
  231. </html>