OSDN Git Service

PR target/33135
[pf3gnuchains/gcc-fork.git] / gcc / doc / cppinternals.texi
1 \input texinfo
2 @setfilename cppinternals.info
3 @settitle The GNU C Preprocessor Internals
4
5 @include gcc-common.texi
6
7 @ifinfo
8 @dircategory Software development
9 @direntry
10 * Cpplib: (cppinternals).      Cpplib internals.
11 @end direntry
12 @end ifinfo
13
14 @c @smallbook
15 @c @cropmarks
16 @c @finalout
17 @setchapternewpage odd
18 @ifinfo
19 This file documents the internals of the GNU C Preprocessor.
20
21 Copyright 2000, 2001, 2002, 2004, 2005, 2006, 2007 Free Software
22 Foundation, Inc.
23
24 Permission is granted to make and distribute verbatim copies of
25 this manual provided the copyright notice and this permission notice
26 are preserved on all copies.
27
28 @ignore
29 Permission is granted to process this file through Tex and print the
30 results, provided the printed document carries copying permission
31 notice identical to this one except for the removal of this paragraph
32 (this paragraph not being relevant to the printed manual).
33
34 @end ignore
35 Permission is granted to copy and distribute modified versions of this
36 manual under the conditions for verbatim copying, provided also that
37 the entire resulting derived work is distributed under the terms of a
38 permission notice identical to this one.
39
40 Permission is granted to copy and distribute translations of this manual
41 into another language, under the above conditions for modified versions.
42 @end ifinfo
43
44 @titlepage
45 @title Cpplib Internals
46 @versionsubtitle
47 @author Neil Booth
48 @page
49 @vskip 0pt plus 1filll
50 @c man begin COPYRIGHT
51 Copyright @copyright{} 2000, 2001, 2002, 2004, 2005
52 Free Software Foundation, Inc.
53
54 Permission is granted to make and distribute verbatim copies of
55 this manual provided the copyright notice and this permission notice
56 are preserved on all copies.
57
58 Permission is granted to copy and distribute modified versions of this
59 manual under the conditions for verbatim copying, provided also that
60 the entire resulting derived work is distributed under the terms of a
61 permission notice identical to this one.
62
63 Permission is granted to copy and distribute translations of this manual
64 into another language, under the above conditions for modified versions.
65 @c man end
66 @end titlepage
67 @contents
68 @page
69
70 @ifnottex
71 @node Top
72 @top
73 @chapter Cpplib---the GNU C Preprocessor
74
75 The GNU C preprocessor is
76 implemented as a library, @dfn{cpplib}, so it can be easily shared between
77 a stand-alone preprocessor, and a preprocessor integrated with the C,
78 C++ and Objective-C front ends.  It is also available for use by other
79 programs, though this is not recommended as its exposed interface has
80 not yet reached a point of reasonable stability.
81
82 The library has been written to be re-entrant, so that it can be used
83 to preprocess many files simultaneously if necessary.  It has also been
84 written with the preprocessing token as the fundamental unit; the
85 preprocessor in previous versions of GCC would operate on text strings
86 as the fundamental unit.
87
88 This brief manual documents the internals of cpplib, and explains some
89 of the tricky issues.  It is intended that, along with the comments in
90 the source code, a reasonably competent C programmer should be able to
91 figure out what the code is doing, and why things have been implemented
92 the way they have.
93
94 @menu
95 * Conventions::         Conventions used in the code.
96 * Lexer::               The combined C, C++ and Objective-C Lexer.
97 * Hash Nodes::          All identifiers are entered into a hash table.
98 * Macro Expansion::     Macro expansion algorithm.
99 * Token Spacing::       Spacing and paste avoidance issues.
100 * Line Numbering::      Tracking location within files.
101 * Guard Macros::        Optimizing header files with guard macros.
102 * Files::               File handling.
103 * Concept Index::       Index.
104 @end menu
105 @end ifnottex
106
107 @node Conventions
108 @unnumbered Conventions
109 @cindex interface
110 @cindex header files
111
112 cpplib has two interfaces---one is exposed internally only, and the
113 other is for both internal and external use.
114
115 The convention is that functions and types that are exposed to multiple
116 files internally are prefixed with @samp{_cpp_}, and are to be found in
117 the file @file{internal.h}.  Functions and types exposed to external
118 clients are in @file{cpplib.h}, and prefixed with @samp{cpp_}.  For
119 historical reasons this is no longer quite true, but we should strive to
120 stick to it.
121
122 We are striving to reduce the information exposed in @file{cpplib.h} to the
123 bare minimum necessary, and then to keep it there.  This makes clear
124 exactly what external clients are entitled to assume, and allows us to
125 change internals in the future without worrying whether library clients
126 are perhaps relying on some kind of undocumented implementation-specific
127 behavior.
128
129 @node Lexer
130 @unnumbered The Lexer
131 @cindex lexer
132 @cindex newlines
133 @cindex escaped newlines
134
135 @section Overview
136 The lexer is contained in the file @file{lex.c}.  It is a hand-coded
137 lexer, and not implemented as a state machine.  It can understand C, C++
138 and Objective-C source code, and has been extended to allow reasonably
139 successful preprocessing of assembly language.  The lexer does not make
140 an initial pass to strip out trigraphs and escaped newlines, but handles
141 them as they are encountered in a single pass of the input file.  It
142 returns preprocessing tokens individually, not a line at a time.
143
144 It is mostly transparent to users of the library, since the library's
145 interface for obtaining the next token, @code{cpp_get_token}, takes care
146 of lexing new tokens, handling directives, and expanding macros as
147 necessary.  However, the lexer does expose some functionality so that
148 clients of the library can easily spell a given token, such as
149 @code{cpp_spell_token} and @code{cpp_token_len}.  These functions are
150 useful when generating diagnostics, and for emitting the preprocessed
151 output.
152
153 @section Lexing a token
154 Lexing of an individual token is handled by @code{_cpp_lex_direct} and
155 its subroutines.  In its current form the code is quite complicated,
156 with read ahead characters and such-like, since it strives to not step
157 back in the character stream in preparation for handling non-ASCII file
158 encodings.  The current plan is to convert any such files to UTF-8
159 before processing them.  This complexity is therefore unnecessary and
160 will be removed, so I'll not discuss it further here.
161
162 The job of @code{_cpp_lex_direct} is simply to lex a token.  It is not
163 responsible for issues like directive handling, returning lookahead
164 tokens directly, multiple-include optimization, or conditional block
165 skipping.  It necessarily has a minor r@^ole to play in memory
166 management of lexed lines.  I discuss these issues in a separate section
167 (@pxref{Lexing a line}).
168
169 The lexer places the token it lexes into storage pointed to by the
170 variable @code{cur_token}, and then increments it.  This variable is
171 important for correct diagnostic positioning.  Unless a specific line
172 and column are passed to the diagnostic routines, they will examine the
173 @code{line} and @code{col} values of the token just before the location
174 that @code{cur_token} points to, and use that location to report the
175 diagnostic.
176
177 The lexer does not consider whitespace to be a token in its own right.
178 If whitespace (other than a new line) precedes a token, it sets the
179 @code{PREV_WHITE} bit in the token's flags.  Each token has its
180 @code{line} and @code{col} variables set to the line and column of the
181 first character of the token.  This line number is the line number in
182 the translation unit, and can be converted to a source (file, line) pair
183 using the line map code.
184
185 The first token on a logical, i.e.@: unescaped, line has the flag
186 @code{BOL} set for beginning-of-line.  This flag is intended for
187 internal use, both to distinguish a @samp{#} that begins a directive
188 from one that doesn't, and to generate a call-back to clients that want
189 to be notified about the start of every non-directive line with tokens
190 on it.  Clients cannot reliably determine this for themselves: the first
191 token might be a macro, and the tokens of a macro expansion do not have
192 the @code{BOL} flag set.  The macro expansion may even be empty, and the
193 next token on the line certainly won't have the @code{BOL} flag set.
194
195 New lines are treated specially; exactly how the lexer handles them is
196 context-dependent.  The C standard mandates that directives are
197 terminated by the first unescaped newline character, even if it appears
198 in the middle of a macro expansion.  Therefore, if the state variable
199 @code{in_directive} is set, the lexer returns a @code{CPP_EOF} token,
200 which is normally used to indicate end-of-file, to indicate
201 end-of-directive.  In a directive a @code{CPP_EOF} token never means
202 end-of-file.  Conveniently, if the caller was @code{collect_args}, it
203 already handles @code{CPP_EOF} as if it were end-of-file, and reports an
204 error about an unterminated macro argument list.
205
206 The C standard also specifies that a new line in the middle of the
207 arguments to a macro is treated as whitespace.  This white space is
208 important in case the macro argument is stringified.  The state variable
209 @code{parsing_args} is nonzero when the preprocessor is collecting the
210 arguments to a macro call.  It is set to 1 when looking for the opening
211 parenthesis to a function-like macro, and 2 when collecting the actual
212 arguments up to the closing parenthesis, since these two cases need to
213 be distinguished sometimes.  One such time is here: the lexer sets the
214 @code{PREV_WHITE} flag of a token if it meets a new line when
215 @code{parsing_args} is set to 2.  It doesn't set it if it meets a new
216 line when @code{parsing_args} is 1, since then code like
217
218 @smallexample
219 #define foo() bar
220 foo
221 baz
222 @end smallexample
223
224 @noindent would be output with an erroneous space before @samp{baz}:
225
226 @smallexample
227 foo
228  baz
229 @end smallexample
230
231 This is a good example of the subtlety of getting token spacing correct
232 in the preprocessor; there are plenty of tests in the testsuite for
233 corner cases like this.
234
235 The lexer is written to treat each of @samp{\r}, @samp{\n}, @samp{\r\n}
236 and @samp{\n\r} as a single new line indicator.  This allows it to
237 transparently preprocess MS-DOS, Macintosh and Unix files without their
238 needing to pass through a special filter beforehand.
239
240 We also decided to treat a backslash, either @samp{\} or the trigraph
241 @samp{??/}, separated from one of the above newline indicators by
242 non-comment whitespace only, as intending to escape the newline.  It
243 tends to be a typing mistake, and cannot reasonably be mistaken for
244 anything else in any of the C-family grammars.  Since handling it this
245 way is not strictly conforming to the ISO standard, the library issues a
246 warning wherever it encounters it.
247
248 Handling newlines like this is made simpler by doing it in one place
249 only.  The function @code{handle_newline} takes care of all newline
250 characters, and @code{skip_escaped_newlines} takes care of arbitrarily
251 long sequences of escaped newlines, deferring to @code{handle_newline}
252 to handle the newlines themselves.
253
254 The most painful aspect of lexing ISO-standard C and C++ is handling
255 trigraphs and backlash-escaped newlines.  Trigraphs are processed before
256 any interpretation of the meaning of a character is made, and unfortunately
257 there is a trigraph representation for a backslash, so it is possible for
258 the trigraph @samp{??/} to introduce an escaped newline.
259
260 Escaped newlines are tedious because theoretically they can occur
261 anywhere---between the @samp{+} and @samp{=} of the @samp{+=} token,
262 within the characters of an identifier, and even between the @samp{*}
263 and @samp{/} that terminates a comment.  Moreover, you cannot be sure
264 there is just one---there might be an arbitrarily long sequence of them.
265
266 So, for example, the routine that lexes a number, @code{parse_number},
267 cannot assume that it can scan forwards until the first non-number
268 character and be done with it, because this could be the @samp{\}
269 introducing an escaped newline, or the @samp{?} introducing the trigraph
270 sequence that represents the @samp{\} of an escaped newline.  If it
271 encounters a @samp{?} or @samp{\}, it calls @code{skip_escaped_newlines}
272 to skip over any potential escaped newlines before checking whether the
273 number has been finished.
274
275 Similarly code in the main body of @code{_cpp_lex_direct} cannot simply
276 check for a @samp{=} after a @samp{+} character to determine whether it
277 has a @samp{+=} token; it needs to be prepared for an escaped newline of
278 some sort.  Such cases use the function @code{get_effective_char}, which
279 returns the first character after any intervening escaped newlines.
280
281 The lexer needs to keep track of the correct column position, including
282 counting tabs as specified by the @option{-ftabstop=} option.  This
283 should be done even within C-style comments; they can appear in the
284 middle of a line, and we want to report diagnostics in the correct
285 position for text appearing after the end of the comment.
286
287 @anchor{Invalid identifiers}
288 Some identifiers, such as @code{__VA_ARGS__} and poisoned identifiers,
289 may be invalid and require a diagnostic.  However, if they appear in a
290 macro expansion we don't want to complain with each use of the macro.
291 It is therefore best to catch them during the lexing stage, in
292 @code{parse_identifier}.  In both cases, whether a diagnostic is needed
293 or not is dependent upon the lexer's state.  For example, we don't want
294 to issue a diagnostic for re-poisoning a poisoned identifier, or for
295 using @code{__VA_ARGS__} in the expansion of a variable-argument macro.
296 Therefore @code{parse_identifier} makes use of state flags to determine
297 whether a diagnostic is appropriate.  Since we change state on a
298 per-token basis, and don't lex whole lines at a time, this is not a
299 problem.
300
301 Another place where state flags are used to change behavior is whilst
302 lexing header names.  Normally, a @samp{<} would be lexed as a single
303 token.  After a @code{#include} directive, though, it should be lexed as
304 a single token as far as the nearest @samp{>} character.  Note that we
305 don't allow the terminators of header names to be escaped; the first
306 @samp{"} or @samp{>} terminates the header name.
307
308 Interpretation of some character sequences depends upon whether we are
309 lexing C, C++ or Objective-C, and on the revision of the standard in
310 force.  For example, @samp{::} is a single token in C++, but in C it is
311 two separate @samp{:} tokens and almost certainly a syntax error.  Such
312 cases are handled by @code{_cpp_lex_direct} based upon command-line
313 flags stored in the @code{cpp_options} structure.
314
315 Once a token has been lexed, it leads an independent existence.  The
316 spelling of numbers, identifiers and strings is copied to permanent
317 storage from the original input buffer, so a token remains valid and
318 correct even if its source buffer is freed with @code{_cpp_pop_buffer}.
319 The storage holding the spellings of such tokens remains until the
320 client program calls cpp_destroy, probably at the end of the translation
321 unit.
322
323 @anchor{Lexing a line}
324 @section Lexing a line
325 @cindex token run
326
327 When the preprocessor was changed to return pointers to tokens, one
328 feature I wanted was some sort of guarantee regarding how long a
329 returned pointer remains valid.  This is important to the stand-alone
330 preprocessor, the future direction of the C family front ends, and even
331 to cpplib itself internally.
332
333 Occasionally the preprocessor wants to be able to peek ahead in the
334 token stream.  For example, after the name of a function-like macro, it
335 wants to check the next token to see if it is an opening parenthesis.
336 Another example is that, after reading the first few tokens of a
337 @code{#pragma} directive and not recognizing it as a registered pragma,
338 it wants to backtrack and allow the user-defined handler for unknown
339 pragmas to access the full @code{#pragma} token stream.  The stand-alone
340 preprocessor wants to be able to test the current token with the
341 previous one to see if a space needs to be inserted to preserve their
342 separate tokenization upon re-lexing (paste avoidance), so it needs to
343 be sure the pointer to the previous token is still valid.  The
344 recursive-descent C++ parser wants to be able to perform tentative
345 parsing arbitrarily far ahead in the token stream, and then to be able
346 to jump back to a prior position in that stream if necessary.
347
348 The rule I chose, which is fairly natural, is to arrange that the
349 preprocessor lex all tokens on a line consecutively into a token buffer,
350 which I call a @dfn{token run}, and when meeting an unescaped new line
351 (newlines within comments do not count either), to start lexing back at
352 the beginning of the run.  Note that we do @emph{not} lex a line of
353 tokens at once; if we did that @code{parse_identifier} would not have
354 state flags available to warn about invalid identifiers (@pxref{Invalid
355 identifiers}).
356
357 In other words, accessing tokens that appeared earlier in the current
358 line is valid, but since each logical line overwrites the tokens of the
359 previous line, tokens from prior lines are unavailable.  In particular,
360 since a directive only occupies a single logical line, this means that
361 the directive handlers like the @code{#pragma} handler can jump around
362 in the directive's tokens if necessary.
363
364 Two issues remain: what about tokens that arise from macro expansions,
365 and what happens when we have a long line that overflows the token run?
366
367 Since we promise clients that we preserve the validity of pointers that
368 we have already returned for tokens that appeared earlier in the line,
369 we cannot reallocate the run.  Instead, on overflow it is expanded by
370 chaining a new token run on to the end of the existing one.
371
372 The tokens forming a macro's replacement list are collected by the
373 @code{#define} handler, and placed in storage that is only freed by
374 @code{cpp_destroy}.  So if a macro is expanded in the line of tokens,
375 the pointers to the tokens of its expansion that are returned will always
376 remain valid.  However, macros are a little trickier than that, since
377 they give rise to three sources of fresh tokens.  They are the built-in
378 macros like @code{__LINE__}, and the @samp{#} and @samp{##} operators
379 for stringification and token pasting.  I handled this by allocating
380 space for these tokens from the lexer's token run chain.  This means
381 they automatically receive the same lifetime guarantees as lexed tokens,
382 and we don't need to concern ourselves with freeing them.
383
384 Lexing into a line of tokens solves some of the token memory management
385 issues, but not all.  The opening parenthesis after a function-like
386 macro name might lie on a different line, and the front ends definitely
387 want the ability to look ahead past the end of the current line.  So
388 cpplib only moves back to the start of the token run at the end of a
389 line if the variable @code{keep_tokens} is zero.  Line-buffering is
390 quite natural for the preprocessor, and as a result the only time cpplib
391 needs to increment this variable is whilst looking for the opening
392 parenthesis to, and reading the arguments of, a function-like macro.  In
393 the near future cpplib will export an interface to increment and
394 decrement this variable, so that clients can share full control over the
395 lifetime of token pointers too.
396
397 The routine @code{_cpp_lex_token} handles moving to new token runs,
398 calling @code{_cpp_lex_direct} to lex new tokens, or returning
399 previously-lexed tokens if we stepped back in the token stream.  It also
400 checks each token for the @code{BOL} flag, which might indicate a
401 directive that needs to be handled, or require a start-of-line call-back
402 to be made.  @code{_cpp_lex_token} also handles skipping over tokens in
403 failed conditional blocks, and invalidates the control macro of the
404 multiple-include optimization if a token was successfully lexed outside
405 a directive.  In other words, its callers do not need to concern
406 themselves with such issues.
407
408 @node Hash Nodes
409 @unnumbered Hash Nodes
410 @cindex hash table
411 @cindex identifiers
412 @cindex macros
413 @cindex assertions
414 @cindex named operators
415
416 When cpplib encounters an ``identifier'', it generates a hash code for
417 it and stores it in the hash table.  By ``identifier'' we mean tokens
418 with type @code{CPP_NAME}; this includes identifiers in the usual C
419 sense, as well as keywords, directive names, macro names and so on.  For
420 example, all of @code{pragma}, @code{int}, @code{foo} and
421 @code{__GNUC__} are identifiers and hashed when lexed.
422
423 Each node in the hash table contain various information about the
424 identifier it represents.  For example, its length and type.  At any one
425 time, each identifier falls into exactly one of three categories:
426
427 @itemize @bullet
428 @item Macros
429
430 These have been declared to be macros, either on the command line or
431 with @code{#define}.  A few, such as @code{__TIME__} are built-ins
432 entered in the hash table during initialization.  The hash node for a
433 normal macro points to a structure with more information about the
434 macro, such as whether it is function-like, how many arguments it takes,
435 and its expansion.  Built-in macros are flagged as special, and instead
436 contain an enum indicating which of the various built-in macros it is.
437
438 @item Assertions
439
440 Assertions are in a separate namespace to macros.  To enforce this, cpp
441 actually prepends a @code{#} character before hashing and entering it in
442 the hash table.  An assertion's node points to a chain of answers to
443 that assertion.
444
445 @item Void
446
447 Everything else falls into this category---an identifier that is not
448 currently a macro, or a macro that has since been undefined with
449 @code{#undef}.
450
451 When preprocessing C++, this category also includes the named operators,
452 such as @code{xor}.  In expressions these behave like the operators they
453 represent, but in contexts where the spelling of a token matters they
454 are spelt differently.  This spelling distinction is relevant when they
455 are operands of the stringizing and pasting macro operators @code{#} and
456 @code{##}.  Named operator hash nodes are flagged, both to catch the
457 spelling distinction and to prevent them from being defined as macros.
458 @end itemize
459
460 The same identifiers share the same hash node.  Since each identifier
461 token, after lexing, contains a pointer to its hash node, this is used
462 to provide rapid lookup of various information.  For example, when
463 parsing a @code{#define} statement, CPP flags each argument's identifier
464 hash node with the index of that argument.  This makes duplicated
465 argument checking an O(1) operation for each argument.  Similarly, for
466 each identifier in the macro's expansion, lookup to see if it is an
467 argument, and which argument it is, is also an O(1) operation.  Further,
468 each directive name, such as @code{endif}, has an associated directive
469 enum stored in its hash node, so that directive lookup is also O(1).
470
471 @node Macro Expansion
472 @unnumbered Macro Expansion Algorithm
473 @cindex macro expansion
474
475 Macro expansion is a tricky operation, fraught with nasty corner cases
476 and situations that render what you thought was a nifty way to
477 optimize the preprocessor's expansion algorithm wrong in quite subtle
478 ways.
479
480 I strongly recommend you have a good grasp of how the C and C++
481 standards require macros to be expanded before diving into this
482 section, let alone the code!.  If you don't have a clear mental
483 picture of how things like nested macro expansion, stringification and
484 token pasting are supposed to work, damage to your sanity can quickly
485 result.
486
487 @section Internal representation of macros
488 @cindex macro representation (internal)
489
490 The preprocessor stores macro expansions in tokenized form.  This
491 saves repeated lexing passes during expansion, at the cost of a small
492 increase in memory consumption on average.  The tokens are stored
493 contiguously in memory, so a pointer to the first one and a token
494 count is all you need to get the replacement list of a macro.
495
496 If the macro is a function-like macro the preprocessor also stores its
497 parameters, in the form of an ordered list of pointers to the hash
498 table entry of each parameter's identifier.  Further, in the macro's
499 stored expansion each occurrence of a parameter is replaced with a
500 special token of type @code{CPP_MACRO_ARG}.  Each such token holds the
501 index of the parameter it represents in the parameter list, which
502 allows rapid replacement of parameters with their arguments during
503 expansion.  Despite this optimization it is still necessary to store
504 the original parameters to the macro, both for dumping with e.g.,
505 @option{-dD}, and to warn about non-trivial macro redefinitions when
506 the parameter names have changed.
507
508 @section Macro expansion overview
509 The preprocessor maintains a @dfn{context stack}, implemented as a
510 linked list of @code{cpp_context} structures, which together represent
511 the macro expansion state at any one time.  The @code{struct
512 cpp_reader} member variable @code{context} points to the current top
513 of this stack.  The top normally holds the unexpanded replacement list
514 of the innermost macro under expansion, except when cpplib is about to
515 pre-expand an argument, in which case it holds that argument's
516 unexpanded tokens.
517
518 When there are no macros under expansion, cpplib is in @dfn{base
519 context}.  All contexts other than the base context contain a
520 contiguous list of tokens delimited by a starting and ending token.
521 When not in base context, cpplib obtains the next token from the list
522 of the top context.  If there are no tokens left in the list, it pops
523 that context off the stack, and subsequent ones if necessary, until an
524 unexhausted context is found or it returns to base context.  In base
525 context, cpplib reads tokens directly from the lexer.
526
527 If it encounters an identifier that is both a macro and enabled for
528 expansion, cpplib prepares to push a new context for that macro on the
529 stack by calling the routine @code{enter_macro_context}.  When this
530 routine returns, the new context will contain the unexpanded tokens of
531 the replacement list of that macro.  In the case of function-like
532 macros, @code{enter_macro_context} also replaces any parameters in the
533 replacement list, stored as @code{CPP_MACRO_ARG} tokens, with the
534 appropriate macro argument.  If the standard requires that the
535 parameter be replaced with its expanded argument, the argument will
536 have been fully macro expanded first.
537
538 @code{enter_macro_context} also handles special macros like
539 @code{__LINE__}.  Although these macros expand to a single token which
540 cannot contain any further macros, for reasons of token spacing
541 (@pxref{Token Spacing}) and simplicity of implementation, cpplib
542 handles these special macros by pushing a context containing just that
543 one token.
544
545 The final thing that @code{enter_macro_context} does before returning
546 is to mark the macro disabled for expansion (except for special macros
547 like @code{__TIME__}).  The macro is re-enabled when its context is
548 later popped from the context stack, as described above.  This strict
549 ordering ensures that a macro is disabled whilst its expansion is
550 being scanned, but that it is @emph{not} disabled whilst any arguments
551 to it are being expanded.
552
553 @section Scanning the replacement list for macros to expand
554 The C standard states that, after any parameters have been replaced
555 with their possibly-expanded arguments, the replacement list is
556 scanned for nested macros.  Further, any identifiers in the
557 replacement list that are not expanded during this scan are never
558 again eligible for expansion in the future, if the reason they were
559 not expanded is that the macro in question was disabled.
560
561 Clearly this latter condition can only apply to tokens resulting from
562 argument pre-expansion.  Other tokens never have an opportunity to be
563 re-tested for expansion.  It is possible for identifiers that are
564 function-like macros to not expand initially but to expand during a
565 later scan.  This occurs when the identifier is the last token of an
566 argument (and therefore originally followed by a comma or a closing
567 parenthesis in its macro's argument list), and when it replaces its
568 parameter in the macro's replacement list, the subsequent token
569 happens to be an opening parenthesis (itself possibly the first token
570 of an argument).
571
572 It is important to note that when cpplib reads the last token of a
573 given context, that context still remains on the stack.  Only when
574 looking for the @emph{next} token do we pop it off the stack and drop
575 to a lower context.  This makes backing up by one token easy, but more
576 importantly ensures that the macro corresponding to the current
577 context is still disabled when we are considering the last token of
578 its replacement list for expansion (or indeed expanding it).  As an
579 example, which illustrates many of the points above, consider
580
581 @smallexample
582 #define foo(x) bar x
583 foo(foo) (2)
584 @end smallexample
585
586 @noindent which fully expands to @samp{bar foo (2)}.  During pre-expansion
587 of the argument, @samp{foo} does not expand even though the macro is
588 enabled, since it has no following parenthesis [pre-expansion of an
589 argument only uses tokens from that argument; it cannot take tokens
590 from whatever follows the macro invocation].  This still leaves the
591 argument token @samp{foo} eligible for future expansion.  Then, when
592 re-scanning after argument replacement, the token @samp{foo} is
593 rejected for expansion, and marked ineligible for future expansion,
594 since the macro is now disabled.  It is disabled because the
595 replacement list @samp{bar foo} of the macro is still on the context
596 stack.
597
598 If instead the algorithm looked for an opening parenthesis first and
599 then tested whether the macro were disabled it would be subtly wrong.
600 In the example above, the replacement list of @samp{foo} would be
601 popped in the process of finding the parenthesis, re-enabling
602 @samp{foo} and expanding it a second time.
603
604 @section Looking for a function-like macro's opening parenthesis
605 Function-like macros only expand when immediately followed by a
606 parenthesis.  To do this cpplib needs to temporarily disable macros
607 and read the next token.  Unfortunately, because of spacing issues
608 (@pxref{Token Spacing}), there can be fake padding tokens in-between,
609 and if the next real token is not a parenthesis cpplib needs to be
610 able to back up that one token as well as retain the information in
611 any intervening padding tokens.
612
613 Backing up more than one token when macros are involved is not
614 permitted by cpplib, because in general it might involve issues like
615 restoring popped contexts onto the context stack, which are too hard.
616 Instead, searching for the parenthesis is handled by a special
617 function, @code{funlike_invocation_p}, which remembers padding
618 information as it reads tokens.  If the next real token is not an
619 opening parenthesis, it backs up that one token, and then pushes an
620 extra context just containing the padding information if necessary.
621
622 @section Marking tokens ineligible for future expansion
623 As discussed above, cpplib needs a way of marking tokens as
624 unexpandable.  Since the tokens cpplib handles are read-only once they
625 have been lexed, it instead makes a copy of the token and adds the
626 flag @code{NO_EXPAND} to the copy.
627
628 For efficiency and to simplify memory management by avoiding having to
629 remember to free these tokens, they are allocated as temporary tokens
630 from the lexer's current token run (@pxref{Lexing a line}) using the
631 function @code{_cpp_temp_token}.  The tokens are then re-used once the
632 current line of tokens has been read in.
633
634 This might sound unsafe.  However, tokens runs are not re-used at the
635 end of a line if it happens to be in the middle of a macro argument
636 list, and cpplib only wants to back-up more than one lexer token in
637 situations where no macro expansion is involved, so the optimization
638 is safe.
639
640 @node Token Spacing
641 @unnumbered Token Spacing
642 @cindex paste avoidance
643 @cindex spacing
644 @cindex token spacing
645
646 First, consider an issue that only concerns the stand-alone
647 preprocessor: there needs to be a guarantee that re-reading its preprocessed
648 output results in an identical token stream.  Without taking special
649 measures, this might not be the case because of macro substitution.
650 For example:
651
652 @smallexample
653 #define PLUS +
654 #define EMPTY
655 #define f(x) =x=
656 +PLUS -EMPTY- PLUS+ f(=)
657         @expansion{} + + - - + + = = =
658 @emph{not}
659         @expansion{} ++ -- ++ ===
660 @end smallexample
661
662 One solution would be to simply insert a space between all adjacent
663 tokens.  However, we would like to keep space insertion to a minimum,
664 both for aesthetic reasons and because it causes problems for people who
665 still try to abuse the preprocessor for things like Fortran source and
666 Makefiles.
667
668 For now, just notice that when tokens are added (or removed, as shown by
669 the @code{EMPTY} example) from the original lexed token stream, we need
670 to check for accidental token pasting.  We call this @dfn{paste
671 avoidance}.  Token addition and removal can only occur because of macro
672 expansion, but accidental pasting can occur in many places: both before
673 and after each macro replacement, each argument replacement, and
674 additionally each token created by the @samp{#} and @samp{##} operators.
675
676 Look at how the preprocessor gets whitespace output correct
677 normally.  The @code{cpp_token} structure contains a flags byte, and one
678 of those flags is @code{PREV_WHITE}.  This is flagged by the lexer, and
679 indicates that the token was preceded by whitespace of some form other
680 than a new line.  The stand-alone preprocessor can use this flag to
681 decide whether to insert a space between tokens in the output.
682
683 Now consider the result of the following macro expansion:
684
685 @smallexample
686 #define add(x, y, z) x + y +z;
687 sum = add (1,2, 3);
688         @expansion{} sum = 1 + 2 +3;
689 @end smallexample
690
691 The interesting thing here is that the tokens @samp{1} and @samp{2} are
692 output with a preceding space, and @samp{3} is output without a
693 preceding space, but when lexed none of these tokens had that property.
694 Careful consideration reveals that @samp{1} gets its preceding
695 whitespace from the space preceding @samp{add} in the macro invocation,
696 @emph{not} replacement list.  @samp{2} gets its whitespace from the
697 space preceding the parameter @samp{y} in the macro replacement list,
698 and @samp{3} has no preceding space because parameter @samp{z} has none
699 in the replacement list.
700
701 Once lexed, tokens are effectively fixed and cannot be altered, since
702 pointers to them might be held in many places, in particular by
703 in-progress macro expansions.  So instead of modifying the two tokens
704 above, the preprocessor inserts a special token, which I call a
705 @dfn{padding token}, into the token stream to indicate that spacing of
706 the subsequent token is special.  The preprocessor inserts padding
707 tokens in front of every macro expansion and expanded macro argument.
708 These point to a @dfn{source token} from which the subsequent real token
709 should inherit its spacing.  In the above example, the source tokens are
710 @samp{add} in the macro invocation, and @samp{y} and @samp{z} in the
711 macro replacement list, respectively.
712
713 It is quite easy to get multiple padding tokens in a row, for example if
714 a macro's first replacement token expands straight into another macro.
715
716 @smallexample
717 #define foo bar
718 #define bar baz
719 [foo]
720         @expansion{} [baz]
721 @end smallexample
722
723 Here, two padding tokens are generated with sources the @samp{foo} token
724 between the brackets, and the @samp{bar} token from foo's replacement
725 list, respectively.  Clearly the first padding token is the one to
726 use, so the output code should contain a rule that the first
727 padding token in a sequence is the one that matters.
728
729 But what if a macro expansion is left?  Adjusting the above
730 example slightly:
731
732 @smallexample
733 #define foo bar
734 #define bar EMPTY baz
735 #define EMPTY
736 [foo] EMPTY;
737         @expansion{} [ baz] ;
738 @end smallexample
739
740 As shown, now there should be a space before @samp{baz} and the
741 semicolon in the output.
742
743 The rules we decided above fail for @samp{baz}: we generate three
744 padding tokens, one per macro invocation, before the token @samp{baz}.
745 We would then have it take its spacing from the first of these, which
746 carries source token @samp{foo} with no leading space.
747
748 It is vital that cpplib get spacing correct in these examples since any
749 of these macro expansions could be stringified, where spacing matters.
750
751 So, this demonstrates that not just entering macro and argument
752 expansions, but leaving them requires special handling too.  I made
753 cpplib insert a padding token with a @code{NULL} source token when
754 leaving macro expansions, as well as after each replaced argument in a
755 macro's replacement list.  It also inserts appropriate padding tokens on
756 either side of tokens created by the @samp{#} and @samp{##} operators.
757 I expanded the rule so that, if we see a padding token with a
758 @code{NULL} source token, @emph{and} that source token has no leading
759 space, then we behave as if we have seen no padding tokens at all.  A
760 quick check shows this rule will then get the above example correct as
761 well.
762
763 Now a relationship with paste avoidance is apparent: we have to be
764 careful about paste avoidance in exactly the same locations we have
765 padding tokens in order to get white space correct.  This makes
766 implementation of paste avoidance easy: wherever the stand-alone
767 preprocessor is fixing up spacing because of padding tokens, and it
768 turns out that no space is needed, it has to take the extra step to
769 check that a space is not needed after all to avoid an accidental paste.
770 The function @code{cpp_avoid_paste} advises whether a space is required
771 between two consecutive tokens.  To avoid excessive spacing, it tries
772 hard to only require a space if one is likely to be necessary, but for
773 reasons of efficiency it is slightly conservative and might recommend a
774 space where one is not strictly needed.
775
776 @node Line Numbering
777 @unnumbered Line numbering
778 @cindex line numbers
779
780 @section Just which line number anyway?
781
782 There are three reasonable requirements a cpplib client might have for
783 the line number of a token passed to it:
784
785 @itemize @bullet
786 @item
787 The source line it was lexed on.
788 @item
789 The line it is output on.  This can be different to the line it was
790 lexed on if, for example, there are intervening escaped newlines or
791 C-style comments.  For example:
792
793 @smallexample
794 foo /* @r{A long
795 comment} */ bar \
796 baz
797 @result{}
798 foo bar baz
799 @end smallexample
800
801 @item
802 If the token results from a macro expansion, the line of the macro name,
803 or possibly the line of the closing parenthesis in the case of
804 function-like macro expansion.
805 @end itemize
806
807 The @code{cpp_token} structure contains @code{line} and @code{col}
808 members.  The lexer fills these in with the line and column of the first
809 character of the token.  Consequently, but maybe unexpectedly, a token
810 from the replacement list of a macro expansion carries the location of
811 the token within the @code{#define} directive, because cpplib expands a
812 macro by returning pointers to the tokens in its replacement list.  The
813 current implementation of cpplib assigns tokens created from built-in
814 macros and the @samp{#} and @samp{##} operators the location of the most
815 recently lexed token.  This is a because they are allocated from the
816 lexer's token runs, and because of the way the diagnostic routines infer
817 the appropriate location to report.
818
819 The diagnostic routines in cpplib display the location of the most
820 recently @emph{lexed} token, unless they are passed a specific line and
821 column to report.  For diagnostics regarding tokens that arise from
822 macro expansions, it might also be helpful for the user to see the
823 original location in the macro definition that the token came from.
824 Since that is exactly the information each token carries, such an
825 enhancement could be made relatively easily in future.
826
827 The stand-alone preprocessor faces a similar problem when determining
828 the correct line to output the token on: the position attached to a
829 token is fairly useless if the token came from a macro expansion.  All
830 tokens on a logical line should be output on its first physical line, so
831 the token's reported location is also wrong if it is part of a physical
832 line other than the first.
833
834 To solve these issues, cpplib provides a callback that is generated
835 whenever it lexes a preprocessing token that starts a new logical line
836 other than a directive.  It passes this token (which may be a
837 @code{CPP_EOF} token indicating the end of the translation unit) to the
838 callback routine, which can then use the line and column of this token
839 to produce correct output.
840
841 @section Representation of line numbers
842
843 As mentioned above, cpplib stores with each token the line number that
844 it was lexed on.  In fact, this number is not the number of the line in
845 the source file, but instead bears more resemblance to the number of the
846 line in the translation unit.
847
848 The preprocessor maintains a monotonic increasing line count, which is
849 incremented at every new line character (and also at the end of any
850 buffer that does not end in a new line).  Since a line number of zero is
851 useful to indicate certain special states and conditions, this variable
852 starts counting from one.
853
854 This variable therefore uniquely enumerates each line in the translation
855 unit.  With some simple infrastructure, it is straight forward to map
856 from this to the original source file and line number pair, saving space
857 whenever line number information needs to be saved.  The code the
858 implements this mapping lies in the files @file{line-map.c} and
859 @file{line-map.h}.
860
861 Command-line macros and assertions are implemented by pushing a buffer
862 containing the right hand side of an equivalent @code{#define} or
863 @code{#assert} directive.  Some built-in macros are handled similarly.
864 Since these are all processed before the first line of the main input
865 file, it will typically have an assigned line closer to twenty than to
866 one.
867
868 @node Guard Macros
869 @unnumbered The Multiple-Include Optimization
870 @cindex guard macros
871 @cindex controlling macros
872 @cindex multiple-include optimization
873
874 Header files are often of the form
875
876 @smallexample
877 #ifndef FOO
878 #define FOO
879 @dots{}
880 #endif
881 @end smallexample
882
883 @noindent
884 to prevent the compiler from processing them more than once.  The
885 preprocessor notices such header files, so that if the header file
886 appears in a subsequent @code{#include} directive and @code{FOO} is
887 defined, then it is ignored and it doesn't preprocess or even re-open
888 the file a second time.  This is referred to as the @dfn{multiple
889 include optimization}.
890
891 Under what circumstances is such an optimization valid?  If the file
892 were included a second time, it can only be optimized away if that
893 inclusion would result in no tokens to return, and no relevant
894 directives to process.  Therefore the current implementation imposes
895 requirements and makes some allowances as follows:
896
897 @enumerate
898 @item
899 There must be no tokens outside the controlling @code{#if}-@code{#endif}
900 pair, but whitespace and comments are permitted.
901
902 @item
903 There must be no directives outside the controlling directive pair, but
904 the @dfn{null directive} (a line containing nothing other than a single
905 @samp{#} and possibly whitespace) is permitted.
906
907 @item
908 The opening directive must be of the form
909
910 @smallexample
911 #ifndef FOO
912 @end smallexample
913
914 or
915
916 @smallexample
917 #if !defined FOO     [equivalently, #if !defined(FOO)]
918 @end smallexample
919
920 @item
921 In the second form above, the tokens forming the @code{#if} expression
922 must have come directly from the source file---no macro expansion must
923 have been involved.  This is because macro definitions can change, and
924 tracking whether or not a relevant change has been made is not worth the
925 implementation cost.
926
927 @item
928 There can be no @code{#else} or @code{#elif} directives at the outer
929 conditional block level, because they would probably contain something
930 of interest to a subsequent pass.
931 @end enumerate
932
933 First, when pushing a new file on the buffer stack,
934 @code{_stack_include_file} sets the controlling macro @code{mi_cmacro} to
935 @code{NULL}, and sets @code{mi_valid} to @code{true}.  This indicates
936 that the preprocessor has not yet encountered anything that would
937 invalidate the multiple-include optimization.  As described in the next
938 few paragraphs, these two variables having these values effectively
939 indicates top-of-file.
940
941 When about to return a token that is not part of a directive,
942 @code{_cpp_lex_token} sets @code{mi_valid} to @code{false}.  This
943 enforces the constraint that tokens outside the controlling conditional
944 block invalidate the optimization.
945
946 The @code{do_if}, when appropriate, and @code{do_ifndef} directive
947 handlers pass the controlling macro to the function
948 @code{push_conditional}.  cpplib maintains a stack of nested conditional
949 blocks, and after processing every opening conditional this function
950 pushes an @code{if_stack} structure onto the stack.  In this structure
951 it records the controlling macro for the block, provided there is one
952 and we're at top-of-file (as described above).  If an @code{#elif} or
953 @code{#else} directive is encountered, the controlling macro for that
954 block is cleared to @code{NULL}.  Otherwise, it survives until the
955 @code{#endif} closing the block, upon which @code{do_endif} sets
956 @code{mi_valid} to true and stores the controlling macro in
957 @code{mi_cmacro}.
958
959 @code{_cpp_handle_directive} clears @code{mi_valid} when processing any
960 directive other than an opening conditional and the null directive.
961 With this, and requiring top-of-file to record a controlling macro, and
962 no @code{#else} or @code{#elif} for it to survive and be copied to
963 @code{mi_cmacro} by @code{do_endif}, we have enforced the absence of
964 directives outside the main conditional block for the optimization to be
965 on.
966
967 Note that whilst we are inside the conditional block, @code{mi_valid} is
968 likely to be reset to @code{false}, but this does not matter since
969 the closing @code{#endif} restores it to @code{true} if appropriate.
970
971 Finally, since @code{_cpp_lex_direct} pops the file off the buffer stack
972 at @code{EOF} without returning a token, if the @code{#endif} directive
973 was not followed by any tokens, @code{mi_valid} is @code{true} and
974 @code{_cpp_pop_file_buffer} remembers the controlling macro associated
975 with the file.  Subsequent calls to @code{stack_include_file} result in
976 no buffer being pushed if the controlling macro is defined, effecting
977 the optimization.
978
979 A quick word on how we handle the
980
981 @smallexample
982 #if !defined FOO
983 @end smallexample
984
985 @noindent
986 case.  @code{_cpp_parse_expr} and @code{parse_defined} take steps to see
987 whether the three stages @samp{!}, @samp{defined-expression} and
988 @samp{end-of-directive} occur in order in a @code{#if} expression.  If
989 so, they return the guard macro to @code{do_if} in the variable
990 @code{mi_ind_cmacro}, and otherwise set it to @code{NULL}.
991 @code{enter_macro_context} sets @code{mi_valid} to false, so if a macro
992 was expanded whilst parsing any part of the expression, then the
993 top-of-file test in @code{push_conditional} fails and the optimization
994 is turned off.
995
996 @node Files
997 @unnumbered File Handling
998 @cindex files
999
1000 Fairly obviously, the file handling code of cpplib resides in the file
1001 @file{files.c}.  It takes care of the details of file searching,
1002 opening, reading and caching, for both the main source file and all the
1003 headers it recursively includes.
1004
1005 The basic strategy is to minimize the number of system calls.  On many
1006 systems, the basic @code{open ()} and @code{fstat ()} system calls can
1007 be quite expensive.  For every @code{#include}-d file, we need to try
1008 all the directories in the search path until we find a match.  Some
1009 projects, such as glibc, pass twenty or thirty include paths on the
1010 command line, so this can rapidly become time consuming.
1011
1012 For a header file we have not encountered before we have little choice
1013 but to do this.  However, it is often the case that the same headers are
1014 repeatedly included, and in these cases we try to avoid repeating the
1015 filesystem queries whilst searching for the correct file.
1016
1017 For each file we try to open, we store the constructed path in a splay
1018 tree.  This path first undergoes simplification by the function
1019 @code{_cpp_simplify_pathname}.  For example,
1020 @file{/usr/include/bits/../foo.h} is simplified to
1021 @file{/usr/include/foo.h} before we enter it in the splay tree and try
1022 to @code{open ()} the file.  CPP will then find subsequent uses of
1023 @file{foo.h}, even as @file{/usr/include/foo.h}, in the splay tree and
1024 save system calls.
1025
1026 Further, it is likely the file contents have also been cached, saving a
1027 @code{read ()} system call.  We don't bother caching the contents of
1028 header files that are re-inclusion protected, and whose re-inclusion
1029 macro is defined when we leave the header file for the first time.  If
1030 the host supports it, we try to map suitably large files into memory,
1031 rather than reading them in directly.
1032
1033 The include paths are internally stored on a null-terminated
1034 singly-linked list, starting with the @code{"header.h"} directory search
1035 chain, which then links into the @code{<header.h>} directory chain.
1036
1037 Files included with the @code{<foo.h>} syntax start the lookup directly
1038 in the second half of this chain.  However, files included with the
1039 @code{"foo.h"} syntax start at the beginning of the chain, but with one
1040 extra directory prepended.  This is the directory of the current file;
1041 the one containing the @code{#include} directive.  Prepending this
1042 directory on a per-file basis is handled by the function
1043 @code{search_from}.
1044
1045 Note that a header included with a directory component, such as
1046 @code{#include "mydir/foo.h"} and opened as
1047 @file{/usr/local/include/mydir/foo.h}, will have the complete path minus
1048 the basename @samp{foo.h} as the current directory.
1049
1050 Enough information is stored in the splay tree that CPP can immediately
1051 tell whether it can skip the header file because of the multiple include
1052 optimization, whether the file didn't exist or couldn't be opened for
1053 some reason, or whether the header was flagged not to be re-used, as it
1054 is with the obsolete @code{#import} directive.
1055
1056 For the benefit of MS-DOS filesystems with an 8.3 filename limitation,
1057 CPP offers the ability to treat various include file names as aliases
1058 for the real header files with shorter names.  The map from one to the
1059 other is found in a special file called @samp{header.gcc}, stored in the
1060 command line (or system) include directories to which the mapping
1061 applies.  This may be higher up the directory tree than the full path to
1062 the file minus the base name.
1063
1064 @node Concept Index
1065 @unnumbered Concept Index
1066 @printindex cp
1067
1068 @bye