您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

346 行
19KB

  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 6.5, http://www.gnu.org/software/texinfo/ -->
  4. <head>
  5. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  6. <title>Lexer (The GNU C Preprocessor Internals)</title>
  7. <meta name="description" content="Lexer (The GNU C Preprocessor Internals)">
  8. <meta name="keywords" content="Lexer (The GNU C Preprocessor Internals)">
  9. <meta name="resource-type" content="document">
  10. <meta name="distribution" content="global">
  11. <meta name="Generator" content="makeinfo">
  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="Hash-Nodes.html#Hash-Nodes" rel="next" title="Hash Nodes">
  17. <link href="Conventions.html#Conventions" rel="prev" title="Conventions">
  18. <style type="text/css">
  19. <!--
  20. a.summary-letter {text-decoration: none}
  21. blockquote.indentedblock {margin-right: 0em}
  22. blockquote.smallindentedblock {margin-right: 0em; font-size: smaller}
  23. blockquote.smallquotation {font-size: smaller}
  24. div.display {margin-left: 3.2em}
  25. div.example {margin-left: 3.2em}
  26. div.lisp {margin-left: 3.2em}
  27. div.smalldisplay {margin-left: 3.2em}
  28. div.smallexample {margin-left: 3.2em}
  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.nolinebreak {white-space: nowrap}
  40. span.roman {font-family: initial; font-weight: normal}
  41. span.sansserif {font-family: sans-serif; font-weight: normal}
  42. ul.no-bullet {list-style: none}
  43. -->
  44. </style>
  45. </head>
  46. <body lang="en">
  47. <a name="Lexer"></a>
  48. <div class="header">
  49. <p>
  50. Next: <a href="Hash-Nodes.html#Hash-Nodes" accesskey="n" rel="next">Hash Nodes</a>, Previous: <a href="Conventions.html#Conventions" accesskey="p" rel="prev">Conventions</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>
  51. </div>
  52. <hr>
  53. <a name="The-Lexer"></a>
  54. <h2 class="unnumbered">The Lexer</h2>
  55. <a name="index-lexer"></a>
  56. <a name="index-newlines"></a>
  57. <a name="index-escaped-newlines"></a>
  58. <a name="Overview"></a>
  59. <h3 class="section">Overview</h3>
  60. <p>The lexer is contained in the file <samp>lex.c</samp>. It is a hand-coded
  61. lexer, and not implemented as a state machine. It can understand C, C++
  62. and Objective-C source code, and has been extended to allow reasonably
  63. successful preprocessing of assembly language. The lexer does not make
  64. an initial pass to strip out trigraphs and escaped newlines, but handles
  65. them as they are encountered in a single pass of the input file. It
  66. returns preprocessing tokens individually, not a line at a time.
  67. </p>
  68. <p>It is mostly transparent to users of the library, since the library&rsquo;s
  69. interface for obtaining the next token, <code>cpp_get_token</code>, takes care
  70. of lexing new tokens, handling directives, and expanding macros as
  71. necessary. However, the lexer does expose some functionality so that
  72. clients of the library can easily spell a given token, such as
  73. <code>cpp_spell_token</code> and <code>cpp_token_len</code>. These functions are
  74. useful when generating diagnostics, and for emitting the preprocessed
  75. output.
  76. </p>
  77. <a name="Lexing-a-token"></a>
  78. <h3 class="section">Lexing a token</h3>
  79. <p>Lexing of an individual token is handled by <code>_cpp_lex_direct</code> and
  80. its subroutines. In its current form the code is quite complicated,
  81. with read ahead characters and such-like, since it strives to not step
  82. back in the character stream in preparation for handling non-ASCII file
  83. encodings. The current plan is to convert any such files to UTF-8
  84. before processing them. This complexity is therefore unnecessary and
  85. will be removed, so I&rsquo;ll not discuss it further here.
  86. </p>
  87. <p>The job of <code>_cpp_lex_direct</code> is simply to lex a token. It is not
  88. responsible for issues like directive handling, returning lookahead
  89. tokens directly, multiple-include optimization, or conditional block
  90. skipping. It necessarily has a minor r&ocirc;le to play in memory
  91. management of lexed lines. I discuss these issues in a separate section
  92. (see <a href="#Lexing-a-line">Lexing a line</a>).
  93. </p>
  94. <p>The lexer places the token it lexes into storage pointed to by the
  95. variable <code>cur_token</code>, and then increments it. This variable is
  96. important for correct diagnostic positioning. Unless a specific line
  97. and column are passed to the diagnostic routines, they will examine the
  98. <code>line</code> and <code>col</code> values of the token just before the location
  99. that <code>cur_token</code> points to, and use that location to report the
  100. diagnostic.
  101. </p>
  102. <p>The lexer does not consider whitespace to be a token in its own right.
  103. If whitespace (other than a new line) precedes a token, it sets the
  104. <code>PREV_WHITE</code> bit in the token&rsquo;s flags. Each token has its
  105. <code>line</code> and <code>col</code> variables set to the line and column of the
  106. first character of the token. This line number is the line number in
  107. the translation unit, and can be converted to a source (file, line) pair
  108. using the line map code.
  109. </p>
  110. <p>The first token on a logical, i.e. unescaped, line has the flag
  111. <code>BOL</code> set for beginning-of-line. This flag is intended for
  112. internal use, both to distinguish a &lsquo;<samp>#</samp>&rsquo; that begins a directive
  113. from one that doesn&rsquo;t, and to generate a call-back to clients that want
  114. to be notified about the start of every non-directive line with tokens
  115. on it. Clients cannot reliably determine this for themselves: the first
  116. token might be a macro, and the tokens of a macro expansion do not have
  117. the <code>BOL</code> flag set. The macro expansion may even be empty, and the
  118. next token on the line certainly won&rsquo;t have the <code>BOL</code> flag set.
  119. </p>
  120. <p>New lines are treated specially; exactly how the lexer handles them is
  121. context-dependent. The C standard mandates that directives are
  122. terminated by the first unescaped newline character, even if it appears
  123. in the middle of a macro expansion. Therefore, if the state variable
  124. <code>in_directive</code> is set, the lexer returns a <code>CPP_EOF</code> token,
  125. which is normally used to indicate end-of-file, to indicate
  126. end-of-directive. In a directive a <code>CPP_EOF</code> token never means
  127. end-of-file. Conveniently, if the caller was <code>collect_args</code>, it
  128. already handles <code>CPP_EOF</code> as if it were end-of-file, and reports an
  129. error about an unterminated macro argument list.
  130. </p>
  131. <p>The C standard also specifies that a new line in the middle of the
  132. arguments to a macro is treated as whitespace. This white space is
  133. important in case the macro argument is stringized. The state variable
  134. <code>parsing_args</code> is nonzero when the preprocessor is collecting the
  135. arguments to a macro call. It is set to 1 when looking for the opening
  136. parenthesis to a function-like macro, and 2 when collecting the actual
  137. arguments up to the closing parenthesis, since these two cases need to
  138. be distinguished sometimes. One such time is here: the lexer sets the
  139. <code>PREV_WHITE</code> flag of a token if it meets a new line when
  140. <code>parsing_args</code> is set to 2. It doesn&rsquo;t set it if it meets a new
  141. line when <code>parsing_args</code> is 1, since then code like
  142. </p>
  143. <div class="smallexample">
  144. <pre class="smallexample">#define foo() bar
  145. foo
  146. baz
  147. </pre></div>
  148. <p>would be output with an erroneous space before &lsquo;<samp>baz</samp>&rsquo;:
  149. </p>
  150. <div class="smallexample">
  151. <pre class="smallexample">foo
  152. baz
  153. </pre></div>
  154. <p>This is a good example of the subtlety of getting token spacing correct
  155. in the preprocessor; there are plenty of tests in the testsuite for
  156. corner cases like this.
  157. </p>
  158. <p>The lexer is written to treat each of &lsquo;<samp>\r</samp>&rsquo;, &lsquo;<samp>\n</samp>&rsquo;, &lsquo;<samp>\r\n</samp>&rsquo;
  159. and &lsquo;<samp>\n\r</samp>&rsquo; as a single new line indicator. This allows it to
  160. transparently preprocess MS-DOS, Macintosh and Unix files without their
  161. needing to pass through a special filter beforehand.
  162. </p>
  163. <p>We also decided to treat a backslash, either &lsquo;<samp>\</samp>&rsquo; or the trigraph
  164. &lsquo;<samp>??/</samp>&rsquo;, separated from one of the above newline indicators by
  165. non-comment whitespace only, as intending to escape the newline. It
  166. tends to be a typing mistake, and cannot reasonably be mistaken for
  167. anything else in any of the C-family grammars. Since handling it this
  168. way is not strictly conforming to the ISO standard, the library issues a
  169. warning wherever it encounters it.
  170. </p>
  171. <p>Handling newlines like this is made simpler by doing it in one place
  172. only. The function <code>handle_newline</code> takes care of all newline
  173. characters, and <code>skip_escaped_newlines</code> takes care of arbitrarily
  174. long sequences of escaped newlines, deferring to <code>handle_newline</code>
  175. to handle the newlines themselves.
  176. </p>
  177. <p>The most painful aspect of lexing ISO-standard C and C++ is handling
  178. trigraphs and backlash-escaped newlines. Trigraphs are processed before
  179. any interpretation of the meaning of a character is made, and unfortunately
  180. there is a trigraph representation for a backslash, so it is possible for
  181. the trigraph &lsquo;<samp>??/</samp>&rsquo; to introduce an escaped newline.
  182. </p>
  183. <p>Escaped newlines are tedious because theoretically they can occur
  184. anywhere&mdash;between the &lsquo;<samp>+</samp>&rsquo; and &lsquo;<samp>=</samp>&rsquo; of the &lsquo;<samp>+=</samp>&rsquo; token,
  185. within the characters of an identifier, and even between the &lsquo;<samp>*</samp>&rsquo;
  186. and &lsquo;<samp>/</samp>&rsquo; that terminates a comment. Moreover, you cannot be sure
  187. there is just one&mdash;there might be an arbitrarily long sequence of them.
  188. </p>
  189. <p>So, for example, the routine that lexes a number, <code>parse_number</code>,
  190. cannot assume that it can scan forwards until the first non-number
  191. character and be done with it, because this could be the &lsquo;<samp>\</samp>&rsquo;
  192. introducing an escaped newline, or the &lsquo;<samp>?</samp>&rsquo; introducing the trigraph
  193. sequence that represents the &lsquo;<samp>\</samp>&rsquo; of an escaped newline. If it
  194. encounters a &lsquo;<samp>?</samp>&rsquo; or &lsquo;<samp>\</samp>&rsquo;, it calls <code>skip_escaped_newlines</code>
  195. to skip over any potential escaped newlines before checking whether the
  196. number has been finished.
  197. </p>
  198. <p>Similarly code in the main body of <code>_cpp_lex_direct</code> cannot simply
  199. check for a &lsquo;<samp>=</samp>&rsquo; after a &lsquo;<samp>+</samp>&rsquo; character to determine whether it
  200. has a &lsquo;<samp>+=</samp>&rsquo; token; it needs to be prepared for an escaped newline of
  201. some sort. Such cases use the function <code>get_effective_char</code>, which
  202. returns the first character after any intervening escaped newlines.
  203. </p>
  204. <p>The lexer needs to keep track of the correct column position, including
  205. counting tabs as specified by the <samp>-ftabstop=</samp> option. This
  206. should be done even within C-style comments; they can appear in the
  207. middle of a line, and we want to report diagnostics in the correct
  208. position for text appearing after the end of the comment.
  209. </p>
  210. <a name="Invalid-identifiers"></a><p>Some identifiers, such as <code>__VA_ARGS__</code> and poisoned identifiers,
  211. may be invalid and require a diagnostic. However, if they appear in a
  212. macro expansion we don&rsquo;t want to complain with each use of the macro.
  213. It is therefore best to catch them during the lexing stage, in
  214. <code>parse_identifier</code>. In both cases, whether a diagnostic is needed
  215. or not is dependent upon the lexer&rsquo;s state. For example, we don&rsquo;t want
  216. to issue a diagnostic for re-poisoning a poisoned identifier, or for
  217. using <code>__VA_ARGS__</code> in the expansion of a variable-argument macro.
  218. Therefore <code>parse_identifier</code> makes use of state flags to determine
  219. whether a diagnostic is appropriate. Since we change state on a
  220. per-token basis, and don&rsquo;t lex whole lines at a time, this is not a
  221. problem.
  222. </p>
  223. <p>Another place where state flags are used to change behavior is whilst
  224. lexing header names. Normally, a &lsquo;<samp>&lt;</samp>&rsquo; would be lexed as a single
  225. token. After a <code>#include</code> directive, though, it should be lexed as
  226. a single token as far as the nearest &lsquo;<samp>&gt;</samp>&rsquo; character. Note that we
  227. don&rsquo;t allow the terminators of header names to be escaped; the first
  228. &lsquo;<samp>&quot;</samp>&rsquo; or &lsquo;<samp>&gt;</samp>&rsquo; terminates the header name.
  229. </p>
  230. <p>Interpretation of some character sequences depends upon whether we are
  231. lexing C, C++ or Objective-C, and on the revision of the standard in
  232. force. For example, &lsquo;<samp>::</samp>&rsquo; is a single token in C++, but in C it is
  233. two separate &lsquo;<samp>:</samp>&rsquo; tokens and almost certainly a syntax error. Such
  234. cases are handled by <code>_cpp_lex_direct</code> based upon command-line
  235. flags stored in the <code>cpp_options</code> structure.
  236. </p>
  237. <p>Once a token has been lexed, it leads an independent existence. The
  238. spelling of numbers, identifiers and strings is copied to permanent
  239. storage from the original input buffer, so a token remains valid and
  240. correct even if its source buffer is freed with <code>_cpp_pop_buffer</code>.
  241. The storage holding the spellings of such tokens remains until the
  242. client program calls cpp_destroy, probably at the end of the translation
  243. unit.
  244. </p>
  245. <a name="Lexing-a-line"></a><a name="Lexing-a-line-1"></a>
  246. <h3 class="section">Lexing a line</h3>
  247. <a name="index-token-run"></a>
  248. <p>When the preprocessor was changed to return pointers to tokens, one
  249. feature I wanted was some sort of guarantee regarding how long a
  250. returned pointer remains valid. This is important to the stand-alone
  251. preprocessor, the future direction of the C family front ends, and even
  252. to cpplib itself internally.
  253. </p>
  254. <p>Occasionally the preprocessor wants to be able to peek ahead in the
  255. token stream. For example, after the name of a function-like macro, it
  256. wants to check the next token to see if it is an opening parenthesis.
  257. Another example is that, after reading the first few tokens of a
  258. <code>#pragma</code> directive and not recognizing it as a registered pragma,
  259. it wants to backtrack and allow the user-defined handler for unknown
  260. pragmas to access the full <code>#pragma</code> token stream. The stand-alone
  261. preprocessor wants to be able to test the current token with the
  262. previous one to see if a space needs to be inserted to preserve their
  263. separate tokenization upon re-lexing (paste avoidance), so it needs to
  264. be sure the pointer to the previous token is still valid. The
  265. recursive-descent C++ parser wants to be able to perform tentative
  266. parsing arbitrarily far ahead in the token stream, and then to be able
  267. to jump back to a prior position in that stream if necessary.
  268. </p>
  269. <p>The rule I chose, which is fairly natural, is to arrange that the
  270. preprocessor lex all tokens on a line consecutively into a token buffer,
  271. which I call a <em>token run</em>, and when meeting an unescaped new line
  272. (newlines within comments do not count either), to start lexing back at
  273. the beginning of the run. Note that we do <em>not</em> lex a line of
  274. tokens at once; if we did that <code>parse_identifier</code> would not have
  275. state flags available to warn about invalid identifiers (see <a href="#Invalid-identifiers">Invalid identifiers</a>).
  276. </p>
  277. <p>In other words, accessing tokens that appeared earlier in the current
  278. line is valid, but since each logical line overwrites the tokens of the
  279. previous line, tokens from prior lines are unavailable. In particular,
  280. since a directive only occupies a single logical line, this means that
  281. the directive handlers like the <code>#pragma</code> handler can jump around
  282. in the directive&rsquo;s tokens if necessary.
  283. </p>
  284. <p>Two issues remain: what about tokens that arise from macro expansions,
  285. and what happens when we have a long line that overflows the token run?
  286. </p>
  287. <p>Since we promise clients that we preserve the validity of pointers that
  288. we have already returned for tokens that appeared earlier in the line,
  289. we cannot reallocate the run. Instead, on overflow it is expanded by
  290. chaining a new token run on to the end of the existing one.
  291. </p>
  292. <p>The tokens forming a macro&rsquo;s replacement list are collected by the
  293. <code>#define</code> handler, and placed in storage that is only freed by
  294. <code>cpp_destroy</code>. So if a macro is expanded in the line of tokens,
  295. the pointers to the tokens of its expansion that are returned will always
  296. remain valid. However, macros are a little trickier than that, since
  297. they give rise to three sources of fresh tokens. They are the built-in
  298. macros like <code>__LINE__</code>, and the &lsquo;<samp>#</samp>&rsquo; and &lsquo;<samp>##</samp>&rsquo; operators
  299. for stringizing and token pasting. I handled this by allocating
  300. space for these tokens from the lexer&rsquo;s token run chain. This means
  301. they automatically receive the same lifetime guarantees as lexed tokens,
  302. and we don&rsquo;t need to concern ourselves with freeing them.
  303. </p>
  304. <p>Lexing into a line of tokens solves some of the token memory management
  305. issues, but not all. The opening parenthesis after a function-like
  306. macro name might lie on a different line, and the front ends definitely
  307. want the ability to look ahead past the end of the current line. So
  308. cpplib only moves back to the start of the token run at the end of a
  309. line if the variable <code>keep_tokens</code> is zero. Line-buffering is
  310. quite natural for the preprocessor, and as a result the only time cpplib
  311. needs to increment this variable is whilst looking for the opening
  312. parenthesis to, and reading the arguments of, a function-like macro. In
  313. the near future cpplib will export an interface to increment and
  314. decrement this variable, so that clients can share full control over the
  315. lifetime of token pointers too.
  316. </p>
  317. <p>The routine <code>_cpp_lex_token</code> handles moving to new token runs,
  318. calling <code>_cpp_lex_direct</code> to lex new tokens, or returning
  319. previously-lexed tokens if we stepped back in the token stream. It also
  320. checks each token for the <code>BOL</code> flag, which might indicate a
  321. directive that needs to be handled, or require a start-of-line call-back
  322. to be made. <code>_cpp_lex_token</code> also handles skipping over tokens in
  323. failed conditional blocks, and invalidates the control macro of the
  324. multiple-include optimization if a token was successfully lexed outside
  325. a directive. In other words, its callers do not need to concern
  326. themselves with such issues.
  327. </p>
  328. <hr>
  329. <div class="header">
  330. <p>
  331. Next: <a href="Hash-Nodes.html#Hash-Nodes" accesskey="n" rel="next">Hash Nodes</a>, Previous: <a href="Conventions.html#Conventions" accesskey="p" rel="prev">Conventions</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>
  332. </div>
  333. </body>
  334. </html>