110d565efSmrg\input texinfo
210d565efSmrg@setfilename cppinternals.info
310d565efSmrg@settitle The GNU C Preprocessor Internals
410d565efSmrg
510d565efSmrg@include gcc-common.texi
610d565efSmrg
710d565efSmrg@ifinfo
810d565efSmrg@dircategory Software development
910d565efSmrg@direntry
1010d565efSmrg* Cpplib: (cppinternals).      Cpplib internals.
1110d565efSmrg@end direntry
1210d565efSmrg@end ifinfo
1310d565efSmrg
1410d565efSmrg@c @smallbook
1510d565efSmrg@c @cropmarks
1610d565efSmrg@c @finalout
1710d565efSmrg@setchapternewpage odd
1810d565efSmrg@ifinfo
1910d565efSmrgThis file documents the internals of the GNU C Preprocessor.
2010d565efSmrg
21*ec02198aSmrgCopyright (C) 2000-2020 Free Software Foundation, Inc.
2210d565efSmrg
2310d565efSmrgPermission is granted to make and distribute verbatim copies of
2410d565efSmrgthis manual provided the copyright notice and this permission notice
2510d565efSmrgare preserved on all copies.
2610d565efSmrg
2710d565efSmrg@ignore
2810d565efSmrgPermission is granted to process this file through Tex and print the
2910d565efSmrgresults, provided the printed document carries copying permission
3010d565efSmrgnotice identical to this one except for the removal of this paragraph
3110d565efSmrg(this paragraph not being relevant to the printed manual).
3210d565efSmrg
3310d565efSmrg@end ignore
3410d565efSmrgPermission is granted to copy and distribute modified versions of this
3510d565efSmrgmanual under the conditions for verbatim copying, provided also that
3610d565efSmrgthe entire resulting derived work is distributed under the terms of a
3710d565efSmrgpermission notice identical to this one.
3810d565efSmrg
3910d565efSmrgPermission is granted to copy and distribute translations of this manual
4010d565efSmrginto another language, under the above conditions for modified versions.
4110d565efSmrg@end ifinfo
4210d565efSmrg
4310d565efSmrg@titlepage
4410d565efSmrg@title Cpplib Internals
4510d565efSmrg@versionsubtitle
4610d565efSmrg@author Neil Booth
4710d565efSmrg@page
4810d565efSmrg@vskip 0pt plus 1filll
4910d565efSmrg@c man begin COPYRIGHT
50*ec02198aSmrgCopyright @copyright{} 2000-2020 Free Software Foundation, Inc.
5110d565efSmrg
5210d565efSmrgPermission is granted to make and distribute verbatim copies of
5310d565efSmrgthis manual provided the copyright notice and this permission notice
5410d565efSmrgare preserved on all copies.
5510d565efSmrg
5610d565efSmrgPermission is granted to copy and distribute modified versions of this
5710d565efSmrgmanual under the conditions for verbatim copying, provided also that
5810d565efSmrgthe entire resulting derived work is distributed under the terms of a
5910d565efSmrgpermission notice identical to this one.
6010d565efSmrg
6110d565efSmrgPermission is granted to copy and distribute translations of this manual
6210d565efSmrginto another language, under the above conditions for modified versions.
6310d565efSmrg@c man end
6410d565efSmrg@end titlepage
6510d565efSmrg@contents
6610d565efSmrg@page
6710d565efSmrg
6810d565efSmrg@ifnottex
6910d565efSmrg@node Top
7010d565efSmrg@top
7110d565efSmrg@chapter Cpplib---the GNU C Preprocessor
7210d565efSmrg
7310d565efSmrgThe GNU C preprocessor is
7410d565efSmrgimplemented as a library, @dfn{cpplib}, so it can be easily shared between
7510d565efSmrga stand-alone preprocessor, and a preprocessor integrated with the C,
7610d565efSmrgC++ and Objective-C front ends.  It is also available for use by other
7710d565efSmrgprograms, though this is not recommended as its exposed interface has
7810d565efSmrgnot yet reached a point of reasonable stability.
7910d565efSmrg
8010d565efSmrgThe library has been written to be re-entrant, so that it can be used
8110d565efSmrgto preprocess many files simultaneously if necessary.  It has also been
8210d565efSmrgwritten with the preprocessing token as the fundamental unit; the
8310d565efSmrgpreprocessor in previous versions of GCC would operate on text strings
8410d565efSmrgas the fundamental unit.
8510d565efSmrg
8610d565efSmrgThis brief manual documents the internals of cpplib, and explains some
8710d565efSmrgof the tricky issues.  It is intended that, along with the comments in
8810d565efSmrgthe source code, a reasonably competent C programmer should be able to
8910d565efSmrgfigure out what the code is doing, and why things have been implemented
9010d565efSmrgthe way they have.
9110d565efSmrg
9210d565efSmrg@menu
9310d565efSmrg* Conventions::         Conventions used in the code.
9410d565efSmrg* Lexer::               The combined C, C++ and Objective-C Lexer.
9510d565efSmrg* Hash Nodes::          All identifiers are entered into a hash table.
9610d565efSmrg* Macro Expansion::     Macro expansion algorithm.
9710d565efSmrg* Token Spacing::       Spacing and paste avoidance issues.
9810d565efSmrg* Line Numbering::      Tracking location within files.
9910d565efSmrg* Guard Macros::        Optimizing header files with guard macros.
10010d565efSmrg* Files::               File handling.
10110d565efSmrg* Concept Index::       Index.
10210d565efSmrg@end menu
10310d565efSmrg@end ifnottex
10410d565efSmrg
10510d565efSmrg@node Conventions
10610d565efSmrg@unnumbered Conventions
10710d565efSmrg@cindex interface
10810d565efSmrg@cindex header files
10910d565efSmrg
11010d565efSmrgcpplib has two interfaces---one is exposed internally only, and the
11110d565efSmrgother is for both internal and external use.
11210d565efSmrg
11310d565efSmrgThe convention is that functions and types that are exposed to multiple
11410d565efSmrgfiles internally are prefixed with @samp{_cpp_}, and are to be found in
11510d565efSmrgthe file @file{internal.h}.  Functions and types exposed to external
11610d565efSmrgclients are in @file{cpplib.h}, and prefixed with @samp{cpp_}.  For
11710d565efSmrghistorical reasons this is no longer quite true, but we should strive to
11810d565efSmrgstick to it.
11910d565efSmrg
12010d565efSmrgWe are striving to reduce the information exposed in @file{cpplib.h} to the
12110d565efSmrgbare minimum necessary, and then to keep it there.  This makes clear
12210d565efSmrgexactly what external clients are entitled to assume, and allows us to
12310d565efSmrgchange internals in the future without worrying whether library clients
12410d565efSmrgare perhaps relying on some kind of undocumented implementation-specific
12510d565efSmrgbehavior.
12610d565efSmrg
12710d565efSmrg@node Lexer
12810d565efSmrg@unnumbered The Lexer
12910d565efSmrg@cindex lexer
13010d565efSmrg@cindex newlines
13110d565efSmrg@cindex escaped newlines
13210d565efSmrg
13310d565efSmrg@section Overview
13410d565efSmrgThe lexer is contained in the file @file{lex.c}.  It is a hand-coded
13510d565efSmrglexer, and not implemented as a state machine.  It can understand C, C++
13610d565efSmrgand Objective-C source code, and has been extended to allow reasonably
13710d565efSmrgsuccessful preprocessing of assembly language.  The lexer does not make
13810d565efSmrgan initial pass to strip out trigraphs and escaped newlines, but handles
13910d565efSmrgthem as they are encountered in a single pass of the input file.  It
14010d565efSmrgreturns preprocessing tokens individually, not a line at a time.
14110d565efSmrg
14210d565efSmrgIt is mostly transparent to users of the library, since the library's
14310d565efSmrginterface for obtaining the next token, @code{cpp_get_token}, takes care
14410d565efSmrgof lexing new tokens, handling directives, and expanding macros as
14510d565efSmrgnecessary.  However, the lexer does expose some functionality so that
14610d565efSmrgclients of the library can easily spell a given token, such as
14710d565efSmrg@code{cpp_spell_token} and @code{cpp_token_len}.  These functions are
14810d565efSmrguseful when generating diagnostics, and for emitting the preprocessed
14910d565efSmrgoutput.
15010d565efSmrg
15110d565efSmrg@section Lexing a token
15210d565efSmrgLexing of an individual token is handled by @code{_cpp_lex_direct} and
15310d565efSmrgits subroutines.  In its current form the code is quite complicated,
15410d565efSmrgwith read ahead characters and such-like, since it strives to not step
15510d565efSmrgback in the character stream in preparation for handling non-ASCII file
15610d565efSmrgencodings.  The current plan is to convert any such files to UTF-8
15710d565efSmrgbefore processing them.  This complexity is therefore unnecessary and
15810d565efSmrgwill be removed, so I'll not discuss it further here.
15910d565efSmrg
16010d565efSmrgThe job of @code{_cpp_lex_direct} is simply to lex a token.  It is not
16110d565efSmrgresponsible for issues like directive handling, returning lookahead
16210d565efSmrgtokens directly, multiple-include optimization, or conditional block
16310d565efSmrgskipping.  It necessarily has a minor r@^ole to play in memory
16410d565efSmrgmanagement of lexed lines.  I discuss these issues in a separate section
16510d565efSmrg(@pxref{Lexing a line}).
16610d565efSmrg
16710d565efSmrgThe lexer places the token it lexes into storage pointed to by the
16810d565efSmrgvariable @code{cur_token}, and then increments it.  This variable is
16910d565efSmrgimportant for correct diagnostic positioning.  Unless a specific line
17010d565efSmrgand column are passed to the diagnostic routines, they will examine the
17110d565efSmrg@code{line} and @code{col} values of the token just before the location
17210d565efSmrgthat @code{cur_token} points to, and use that location to report the
17310d565efSmrgdiagnostic.
17410d565efSmrg
17510d565efSmrgThe lexer does not consider whitespace to be a token in its own right.
17610d565efSmrgIf whitespace (other than a new line) precedes a token, it sets the
17710d565efSmrg@code{PREV_WHITE} bit in the token's flags.  Each token has its
17810d565efSmrg@code{line} and @code{col} variables set to the line and column of the
17910d565efSmrgfirst character of the token.  This line number is the line number in
18010d565efSmrgthe translation unit, and can be converted to a source (file, line) pair
18110d565efSmrgusing the line map code.
18210d565efSmrg
18310d565efSmrgThe first token on a logical, i.e.@: unescaped, line has the flag
18410d565efSmrg@code{BOL} set for beginning-of-line.  This flag is intended for
18510d565efSmrginternal use, both to distinguish a @samp{#} that begins a directive
18610d565efSmrgfrom one that doesn't, and to generate a call-back to clients that want
18710d565efSmrgto be notified about the start of every non-directive line with tokens
18810d565efSmrgon it.  Clients cannot reliably determine this for themselves: the first
18910d565efSmrgtoken might be a macro, and the tokens of a macro expansion do not have
19010d565efSmrgthe @code{BOL} flag set.  The macro expansion may even be empty, and the
19110d565efSmrgnext token on the line certainly won't have the @code{BOL} flag set.
19210d565efSmrg
19310d565efSmrgNew lines are treated specially; exactly how the lexer handles them is
19410d565efSmrgcontext-dependent.  The C standard mandates that directives are
19510d565efSmrgterminated by the first unescaped newline character, even if it appears
19610d565efSmrgin the middle of a macro expansion.  Therefore, if the state variable
19710d565efSmrg@code{in_directive} is set, the lexer returns a @code{CPP_EOF} token,
19810d565efSmrgwhich is normally used to indicate end-of-file, to indicate
19910d565efSmrgend-of-directive.  In a directive a @code{CPP_EOF} token never means
20010d565efSmrgend-of-file.  Conveniently, if the caller was @code{collect_args}, it
20110d565efSmrgalready handles @code{CPP_EOF} as if it were end-of-file, and reports an
20210d565efSmrgerror about an unterminated macro argument list.
20310d565efSmrg
20410d565efSmrgThe C standard also specifies that a new line in the middle of the
20510d565efSmrgarguments to a macro is treated as whitespace.  This white space is
20610d565efSmrgimportant in case the macro argument is stringized.  The state variable
20710d565efSmrg@code{parsing_args} is nonzero when the preprocessor is collecting the
20810d565efSmrgarguments to a macro call.  It is set to 1 when looking for the opening
20910d565efSmrgparenthesis to a function-like macro, and 2 when collecting the actual
21010d565efSmrgarguments up to the closing parenthesis, since these two cases need to
21110d565efSmrgbe distinguished sometimes.  One such time is here: the lexer sets the
21210d565efSmrg@code{PREV_WHITE} flag of a token if it meets a new line when
21310d565efSmrg@code{parsing_args} is set to 2.  It doesn't set it if it meets a new
21410d565efSmrgline when @code{parsing_args} is 1, since then code like
21510d565efSmrg
21610d565efSmrg@smallexample
21710d565efSmrg#define foo() bar
21810d565efSmrgfoo
21910d565efSmrgbaz
22010d565efSmrg@end smallexample
22110d565efSmrg
22210d565efSmrg@noindent would be output with an erroneous space before @samp{baz}:
22310d565efSmrg
22410d565efSmrg@smallexample
22510d565efSmrgfoo
22610d565efSmrg baz
22710d565efSmrg@end smallexample
22810d565efSmrg
22910d565efSmrgThis is a good example of the subtlety of getting token spacing correct
23010d565efSmrgin the preprocessor; there are plenty of tests in the testsuite for
23110d565efSmrgcorner cases like this.
23210d565efSmrg
23310d565efSmrgThe lexer is written to treat each of @samp{\r}, @samp{\n}, @samp{\r\n}
23410d565efSmrgand @samp{\n\r} as a single new line indicator.  This allows it to
23510d565efSmrgtransparently preprocess MS-DOS, Macintosh and Unix files without their
23610d565efSmrgneeding to pass through a special filter beforehand.
23710d565efSmrg
23810d565efSmrgWe also decided to treat a backslash, either @samp{\} or the trigraph
23910d565efSmrg@samp{??/}, separated from one of the above newline indicators by
24010d565efSmrgnon-comment whitespace only, as intending to escape the newline.  It
24110d565efSmrgtends to be a typing mistake, and cannot reasonably be mistaken for
24210d565efSmrganything else in any of the C-family grammars.  Since handling it this
24310d565efSmrgway is not strictly conforming to the ISO standard, the library issues a
24410d565efSmrgwarning wherever it encounters it.
24510d565efSmrg
24610d565efSmrgHandling newlines like this is made simpler by doing it in one place
24710d565efSmrgonly.  The function @code{handle_newline} takes care of all newline
24810d565efSmrgcharacters, and @code{skip_escaped_newlines} takes care of arbitrarily
24910d565efSmrglong sequences of escaped newlines, deferring to @code{handle_newline}
25010d565efSmrgto handle the newlines themselves.
25110d565efSmrg
25210d565efSmrgThe most painful aspect of lexing ISO-standard C and C++ is handling
25310d565efSmrgtrigraphs and backlash-escaped newlines.  Trigraphs are processed before
25410d565efSmrgany interpretation of the meaning of a character is made, and unfortunately
25510d565efSmrgthere is a trigraph representation for a backslash, so it is possible for
25610d565efSmrgthe trigraph @samp{??/} to introduce an escaped newline.
25710d565efSmrg
25810d565efSmrgEscaped newlines are tedious because theoretically they can occur
25910d565efSmrganywhere---between the @samp{+} and @samp{=} of the @samp{+=} token,
26010d565efSmrgwithin the characters of an identifier, and even between the @samp{*}
26110d565efSmrgand @samp{/} that terminates a comment.  Moreover, you cannot be sure
26210d565efSmrgthere is just one---there might be an arbitrarily long sequence of them.
26310d565efSmrg
26410d565efSmrgSo, for example, the routine that lexes a number, @code{parse_number},
26510d565efSmrgcannot assume that it can scan forwards until the first non-number
26610d565efSmrgcharacter and be done with it, because this could be the @samp{\}
26710d565efSmrgintroducing an escaped newline, or the @samp{?} introducing the trigraph
26810d565efSmrgsequence that represents the @samp{\} of an escaped newline.  If it
26910d565efSmrgencounters a @samp{?} or @samp{\}, it calls @code{skip_escaped_newlines}
27010d565efSmrgto skip over any potential escaped newlines before checking whether the
27110d565efSmrgnumber has been finished.
27210d565efSmrg
27310d565efSmrgSimilarly code in the main body of @code{_cpp_lex_direct} cannot simply
27410d565efSmrgcheck for a @samp{=} after a @samp{+} character to determine whether it
27510d565efSmrghas a @samp{+=} token; it needs to be prepared for an escaped newline of
27610d565efSmrgsome sort.  Such cases use the function @code{get_effective_char}, which
27710d565efSmrgreturns the first character after any intervening escaped newlines.
27810d565efSmrg
27910d565efSmrgThe lexer needs to keep track of the correct column position, including
28010d565efSmrgcounting tabs as specified by the @option{-ftabstop=} option.  This
28110d565efSmrgshould be done even within C-style comments; they can appear in the
28210d565efSmrgmiddle of a line, and we want to report diagnostics in the correct
28310d565efSmrgposition for text appearing after the end of the comment.
28410d565efSmrg
28510d565efSmrg@anchor{Invalid identifiers}
28610d565efSmrgSome identifiers, such as @code{__VA_ARGS__} and poisoned identifiers,
28710d565efSmrgmay be invalid and require a diagnostic.  However, if they appear in a
28810d565efSmrgmacro expansion we don't want to complain with each use of the macro.
28910d565efSmrgIt is therefore best to catch them during the lexing stage, in
29010d565efSmrg@code{parse_identifier}.  In both cases, whether a diagnostic is needed
29110d565efSmrgor not is dependent upon the lexer's state.  For example, we don't want
29210d565efSmrgto issue a diagnostic for re-poisoning a poisoned identifier, or for
29310d565efSmrgusing @code{__VA_ARGS__} in the expansion of a variable-argument macro.
29410d565efSmrgTherefore @code{parse_identifier} makes use of state flags to determine
29510d565efSmrgwhether a diagnostic is appropriate.  Since we change state on a
29610d565efSmrgper-token basis, and don't lex whole lines at a time, this is not a
29710d565efSmrgproblem.
29810d565efSmrg
29910d565efSmrgAnother place where state flags are used to change behavior is whilst
30010d565efSmrglexing header names.  Normally, a @samp{<} would be lexed as a single
30110d565efSmrgtoken.  After a @code{#include} directive, though, it should be lexed as
30210d565efSmrga single token as far as the nearest @samp{>} character.  Note that we
30310d565efSmrgdon't allow the terminators of header names to be escaped; the first
30410d565efSmrg@samp{"} or @samp{>} terminates the header name.
30510d565efSmrg
30610d565efSmrgInterpretation of some character sequences depends upon whether we are
30710d565efSmrglexing C, C++ or Objective-C, and on the revision of the standard in
30810d565efSmrgforce.  For example, @samp{::} is a single token in C++, but in C it is
30910d565efSmrgtwo separate @samp{:} tokens and almost certainly a syntax error.  Such
31010d565efSmrgcases are handled by @code{_cpp_lex_direct} based upon command-line
31110d565efSmrgflags stored in the @code{cpp_options} structure.
31210d565efSmrg
31310d565efSmrgOnce a token has been lexed, it leads an independent existence.  The
31410d565efSmrgspelling of numbers, identifiers and strings is copied to permanent
31510d565efSmrgstorage from the original input buffer, so a token remains valid and
31610d565efSmrgcorrect even if its source buffer is freed with @code{_cpp_pop_buffer}.
31710d565efSmrgThe storage holding the spellings of such tokens remains until the
31810d565efSmrgclient program calls cpp_destroy, probably at the end of the translation
31910d565efSmrgunit.
32010d565efSmrg
32110d565efSmrg@anchor{Lexing a line}
32210d565efSmrg@section Lexing a line
32310d565efSmrg@cindex token run
32410d565efSmrg
32510d565efSmrgWhen the preprocessor was changed to return pointers to tokens, one
32610d565efSmrgfeature I wanted was some sort of guarantee regarding how long a
32710d565efSmrgreturned pointer remains valid.  This is important to the stand-alone
32810d565efSmrgpreprocessor, the future direction of the C family front ends, and even
32910d565efSmrgto cpplib itself internally.
33010d565efSmrg
33110d565efSmrgOccasionally the preprocessor wants to be able to peek ahead in the
33210d565efSmrgtoken stream.  For example, after the name of a function-like macro, it
33310d565efSmrgwants to check the next token to see if it is an opening parenthesis.
33410d565efSmrgAnother example is that, after reading the first few tokens of a
33510d565efSmrg@code{#pragma} directive and not recognizing it as a registered pragma,
33610d565efSmrgit wants to backtrack and allow the user-defined handler for unknown
33710d565efSmrgpragmas to access the full @code{#pragma} token stream.  The stand-alone
33810d565efSmrgpreprocessor wants to be able to test the current token with the
33910d565efSmrgprevious one to see if a space needs to be inserted to preserve their
34010d565efSmrgseparate tokenization upon re-lexing (paste avoidance), so it needs to
34110d565efSmrgbe sure the pointer to the previous token is still valid.  The
34210d565efSmrgrecursive-descent C++ parser wants to be able to perform tentative
34310d565efSmrgparsing arbitrarily far ahead in the token stream, and then to be able
34410d565efSmrgto jump back to a prior position in that stream if necessary.
34510d565efSmrg
34610d565efSmrgThe rule I chose, which is fairly natural, is to arrange that the
34710d565efSmrgpreprocessor lex all tokens on a line consecutively into a token buffer,
34810d565efSmrgwhich I call a @dfn{token run}, and when meeting an unescaped new line
34910d565efSmrg(newlines within comments do not count either), to start lexing back at
35010d565efSmrgthe beginning of the run.  Note that we do @emph{not} lex a line of
35110d565efSmrgtokens at once; if we did that @code{parse_identifier} would not have
35210d565efSmrgstate flags available to warn about invalid identifiers (@pxref{Invalid
35310d565efSmrgidentifiers}).
35410d565efSmrg
35510d565efSmrgIn other words, accessing tokens that appeared earlier in the current
35610d565efSmrgline is valid, but since each logical line overwrites the tokens of the
35710d565efSmrgprevious line, tokens from prior lines are unavailable.  In particular,
35810d565efSmrgsince a directive only occupies a single logical line, this means that
35910d565efSmrgthe directive handlers like the @code{#pragma} handler can jump around
36010d565efSmrgin the directive's tokens if necessary.
36110d565efSmrg
36210d565efSmrgTwo issues remain: what about tokens that arise from macro expansions,
36310d565efSmrgand what happens when we have a long line that overflows the token run?
36410d565efSmrg
36510d565efSmrgSince we promise clients that we preserve the validity of pointers that
36610d565efSmrgwe have already returned for tokens that appeared earlier in the line,
36710d565efSmrgwe cannot reallocate the run.  Instead, on overflow it is expanded by
36810d565efSmrgchaining a new token run on to the end of the existing one.
36910d565efSmrg
37010d565efSmrgThe tokens forming a macro's replacement list are collected by the
37110d565efSmrg@code{#define} handler, and placed in storage that is only freed by
37210d565efSmrg@code{cpp_destroy}.  So if a macro is expanded in the line of tokens,
37310d565efSmrgthe pointers to the tokens of its expansion that are returned will always
37410d565efSmrgremain valid.  However, macros are a little trickier than that, since
37510d565efSmrgthey give rise to three sources of fresh tokens.  They are the built-in
37610d565efSmrgmacros like @code{__LINE__}, and the @samp{#} and @samp{##} operators
37710d565efSmrgfor stringizing and token pasting.  I handled this by allocating
37810d565efSmrgspace for these tokens from the lexer's token run chain.  This means
37910d565efSmrgthey automatically receive the same lifetime guarantees as lexed tokens,
38010d565efSmrgand we don't need to concern ourselves with freeing them.
38110d565efSmrg
38210d565efSmrgLexing into a line of tokens solves some of the token memory management
38310d565efSmrgissues, but not all.  The opening parenthesis after a function-like
38410d565efSmrgmacro name might lie on a different line, and the front ends definitely
38510d565efSmrgwant the ability to look ahead past the end of the current line.  So
38610d565efSmrgcpplib only moves back to the start of the token run at the end of a
38710d565efSmrgline if the variable @code{keep_tokens} is zero.  Line-buffering is
38810d565efSmrgquite natural for the preprocessor, and as a result the only time cpplib
38910d565efSmrgneeds to increment this variable is whilst looking for the opening
39010d565efSmrgparenthesis to, and reading the arguments of, a function-like macro.  In
39110d565efSmrgthe near future cpplib will export an interface to increment and
39210d565efSmrgdecrement this variable, so that clients can share full control over the
39310d565efSmrglifetime of token pointers too.
39410d565efSmrg
39510d565efSmrgThe routine @code{_cpp_lex_token} handles moving to new token runs,
39610d565efSmrgcalling @code{_cpp_lex_direct} to lex new tokens, or returning
39710d565efSmrgpreviously-lexed tokens if we stepped back in the token stream.  It also
39810d565efSmrgchecks each token for the @code{BOL} flag, which might indicate a
39910d565efSmrgdirective that needs to be handled, or require a start-of-line call-back
40010d565efSmrgto be made.  @code{_cpp_lex_token} also handles skipping over tokens in
40110d565efSmrgfailed conditional blocks, and invalidates the control macro of the
40210d565efSmrgmultiple-include optimization if a token was successfully lexed outside
40310d565efSmrga directive.  In other words, its callers do not need to concern
40410d565efSmrgthemselves with such issues.
40510d565efSmrg
40610d565efSmrg@node Hash Nodes
40710d565efSmrg@unnumbered Hash Nodes
40810d565efSmrg@cindex hash table
40910d565efSmrg@cindex identifiers
41010d565efSmrg@cindex macros
41110d565efSmrg@cindex assertions
41210d565efSmrg@cindex named operators
41310d565efSmrg
41410d565efSmrgWhen cpplib encounters an ``identifier'', it generates a hash code for
41510d565efSmrgit and stores it in the hash table.  By ``identifier'' we mean tokens
41610d565efSmrgwith type @code{CPP_NAME}; this includes identifiers in the usual C
41710d565efSmrgsense, as well as keywords, directive names, macro names and so on.  For
41810d565efSmrgexample, all of @code{pragma}, @code{int}, @code{foo} and
41910d565efSmrg@code{__GNUC__} are identifiers and hashed when lexed.
42010d565efSmrg
42110d565efSmrgEach node in the hash table contain various information about the
42210d565efSmrgidentifier it represents.  For example, its length and type.  At any one
42310d565efSmrgtime, each identifier falls into exactly one of three categories:
42410d565efSmrg
42510d565efSmrg@itemize @bullet
42610d565efSmrg@item Macros
42710d565efSmrg
42810d565efSmrgThese have been declared to be macros, either on the command line or
42910d565efSmrgwith @code{#define}.  A few, such as @code{__TIME__} are built-ins
43010d565efSmrgentered in the hash table during initialization.  The hash node for a
43110d565efSmrgnormal macro points to a structure with more information about the
43210d565efSmrgmacro, such as whether it is function-like, how many arguments it takes,
43310d565efSmrgand its expansion.  Built-in macros are flagged as special, and instead
43410d565efSmrgcontain an enum indicating which of the various built-in macros it is.
43510d565efSmrg
43610d565efSmrg@item Assertions
43710d565efSmrg
43810d565efSmrgAssertions are in a separate namespace to macros.  To enforce this, cpp
43910d565efSmrgactually prepends a @code{#} character before hashing and entering it in
44010d565efSmrgthe hash table.  An assertion's node points to a chain of answers to
44110d565efSmrgthat assertion.
44210d565efSmrg
44310d565efSmrg@item Void
44410d565efSmrg
44510d565efSmrgEverything else falls into this category---an identifier that is not
44610d565efSmrgcurrently a macro, or a macro that has since been undefined with
44710d565efSmrg@code{#undef}.
44810d565efSmrg
44910d565efSmrgWhen preprocessing C++, this category also includes the named operators,
45010d565efSmrgsuch as @code{xor}.  In expressions these behave like the operators they
45110d565efSmrgrepresent, but in contexts where the spelling of a token matters they
45210d565efSmrgare spelt differently.  This spelling distinction is relevant when they
45310d565efSmrgare operands of the stringizing and pasting macro operators @code{#} and
45410d565efSmrg@code{##}.  Named operator hash nodes are flagged, both to catch the
45510d565efSmrgspelling distinction and to prevent them from being defined as macros.
45610d565efSmrg@end itemize
45710d565efSmrg
45810d565efSmrgThe same identifiers share the same hash node.  Since each identifier
45910d565efSmrgtoken, after lexing, contains a pointer to its hash node, this is used
46010d565efSmrgto provide rapid lookup of various information.  For example, when
46110d565efSmrgparsing a @code{#define} statement, CPP flags each argument's identifier
46210d565efSmrghash node with the index of that argument.  This makes duplicated
46310d565efSmrgargument checking an O(1) operation for each argument.  Similarly, for
46410d565efSmrgeach identifier in the macro's expansion, lookup to see if it is an
46510d565efSmrgargument, and which argument it is, is also an O(1) operation.  Further,
46610d565efSmrgeach directive name, such as @code{endif}, has an associated directive
46710d565efSmrgenum stored in its hash node, so that directive lookup is also O(1).
46810d565efSmrg
46910d565efSmrg@node Macro Expansion
47010d565efSmrg@unnumbered Macro Expansion Algorithm
47110d565efSmrg@cindex macro expansion
47210d565efSmrg
47310d565efSmrgMacro expansion is a tricky operation, fraught with nasty corner cases
47410d565efSmrgand situations that render what you thought was a nifty way to
47510d565efSmrgoptimize the preprocessor's expansion algorithm wrong in quite subtle
47610d565efSmrgways.
47710d565efSmrg
47810d565efSmrgI strongly recommend you have a good grasp of how the C and C++
47910d565efSmrgstandards require macros to be expanded before diving into this
48010d565efSmrgsection, let alone the code!.  If you don't have a clear mental
48110d565efSmrgpicture of how things like nested macro expansion, stringizing and
48210d565efSmrgtoken pasting are supposed to work, damage to your sanity can quickly
48310d565efSmrgresult.
48410d565efSmrg
48510d565efSmrg@section Internal representation of macros
48610d565efSmrg@cindex macro representation (internal)
48710d565efSmrg
48810d565efSmrgThe preprocessor stores macro expansions in tokenized form.  This
48910d565efSmrgsaves repeated lexing passes during expansion, at the cost of a small
49010d565efSmrgincrease in memory consumption on average.  The tokens are stored
49110d565efSmrgcontiguously in memory, so a pointer to the first one and a token
49210d565efSmrgcount is all you need to get the replacement list of a macro.
49310d565efSmrg
49410d565efSmrgIf the macro is a function-like macro the preprocessor also stores its
49510d565efSmrgparameters, in the form of an ordered list of pointers to the hash
49610d565efSmrgtable entry of each parameter's identifier.  Further, in the macro's
49710d565efSmrgstored expansion each occurrence of a parameter is replaced with a
49810d565efSmrgspecial token of type @code{CPP_MACRO_ARG}.  Each such token holds the
49910d565efSmrgindex of the parameter it represents in the parameter list, which
50010d565efSmrgallows rapid replacement of parameters with their arguments during
50110d565efSmrgexpansion.  Despite this optimization it is still necessary to store
50210d565efSmrgthe original parameters to the macro, both for dumping with e.g.,
50310d565efSmrg@option{-dD}, and to warn about non-trivial macro redefinitions when
50410d565efSmrgthe parameter names have changed.
50510d565efSmrg
50610d565efSmrg@section Macro expansion overview
50710d565efSmrgThe preprocessor maintains a @dfn{context stack}, implemented as a
50810d565efSmrglinked list of @code{cpp_context} structures, which together represent
50910d565efSmrgthe macro expansion state at any one time.  The @code{struct
51010d565efSmrgcpp_reader} member variable @code{context} points to the current top
51110d565efSmrgof this stack.  The top normally holds the unexpanded replacement list
51210d565efSmrgof the innermost macro under expansion, except when cpplib is about to
51310d565efSmrgpre-expand an argument, in which case it holds that argument's
51410d565efSmrgunexpanded tokens.
51510d565efSmrg
51610d565efSmrgWhen there are no macros under expansion, cpplib is in @dfn{base
51710d565efSmrgcontext}.  All contexts other than the base context contain a
51810d565efSmrgcontiguous list of tokens delimited by a starting and ending token.
51910d565efSmrgWhen not in base context, cpplib obtains the next token from the list
52010d565efSmrgof the top context.  If there are no tokens left in the list, it pops
52110d565efSmrgthat context off the stack, and subsequent ones if necessary, until an
52210d565efSmrgunexhausted context is found or it returns to base context.  In base
52310d565efSmrgcontext, cpplib reads tokens directly from the lexer.
52410d565efSmrg
52510d565efSmrgIf it encounters an identifier that is both a macro and enabled for
52610d565efSmrgexpansion, cpplib prepares to push a new context for that macro on the
52710d565efSmrgstack by calling the routine @code{enter_macro_context}.  When this
52810d565efSmrgroutine returns, the new context will contain the unexpanded tokens of
52910d565efSmrgthe replacement list of that macro.  In the case of function-like
53010d565efSmrgmacros, @code{enter_macro_context} also replaces any parameters in the
53110d565efSmrgreplacement list, stored as @code{CPP_MACRO_ARG} tokens, with the
53210d565efSmrgappropriate macro argument.  If the standard requires that the
53310d565efSmrgparameter be replaced with its expanded argument, the argument will
53410d565efSmrghave been fully macro expanded first.
53510d565efSmrg
53610d565efSmrg@code{enter_macro_context} also handles special macros like
53710d565efSmrg@code{__LINE__}.  Although these macros expand to a single token which
53810d565efSmrgcannot contain any further macros, for reasons of token spacing
53910d565efSmrg(@pxref{Token Spacing}) and simplicity of implementation, cpplib
54010d565efSmrghandles these special macros by pushing a context containing just that
54110d565efSmrgone token.
54210d565efSmrg
54310d565efSmrgThe final thing that @code{enter_macro_context} does before returning
54410d565efSmrgis to mark the macro disabled for expansion (except for special macros
54510d565efSmrglike @code{__TIME__}).  The macro is re-enabled when its context is
54610d565efSmrglater popped from the context stack, as described above.  This strict
54710d565efSmrgordering ensures that a macro is disabled whilst its expansion is
54810d565efSmrgbeing scanned, but that it is @emph{not} disabled whilst any arguments
54910d565efSmrgto it are being expanded.
55010d565efSmrg
55110d565efSmrg@section Scanning the replacement list for macros to expand
55210d565efSmrgThe C standard states that, after any parameters have been replaced
55310d565efSmrgwith their possibly-expanded arguments, the replacement list is
55410d565efSmrgscanned for nested macros.  Further, any identifiers in the
55510d565efSmrgreplacement list that are not expanded during this scan are never
55610d565efSmrgagain eligible for expansion in the future, if the reason they were
55710d565efSmrgnot expanded is that the macro in question was disabled.
55810d565efSmrg
55910d565efSmrgClearly this latter condition can only apply to tokens resulting from
56010d565efSmrgargument pre-expansion.  Other tokens never have an opportunity to be
56110d565efSmrgre-tested for expansion.  It is possible for identifiers that are
56210d565efSmrgfunction-like macros to not expand initially but to expand during a
56310d565efSmrglater scan.  This occurs when the identifier is the last token of an
56410d565efSmrgargument (and therefore originally followed by a comma or a closing
56510d565efSmrgparenthesis in its macro's argument list), and when it replaces its
56610d565efSmrgparameter in the macro's replacement list, the subsequent token
56710d565efSmrghappens to be an opening parenthesis (itself possibly the first token
56810d565efSmrgof an argument).
56910d565efSmrg
57010d565efSmrgIt is important to note that when cpplib reads the last token of a
57110d565efSmrggiven context, that context still remains on the stack.  Only when
57210d565efSmrglooking for the @emph{next} token do we pop it off the stack and drop
57310d565efSmrgto a lower context.  This makes backing up by one token easy, but more
57410d565efSmrgimportantly ensures that the macro corresponding to the current
57510d565efSmrgcontext is still disabled when we are considering the last token of
57610d565efSmrgits replacement list for expansion (or indeed expanding it).  As an
57710d565efSmrgexample, which illustrates many of the points above, consider
57810d565efSmrg
57910d565efSmrg@smallexample
58010d565efSmrg#define foo(x) bar x
58110d565efSmrgfoo(foo) (2)
58210d565efSmrg@end smallexample
58310d565efSmrg
58410d565efSmrg@noindent which fully expands to @samp{bar foo (2)}.  During pre-expansion
58510d565efSmrgof the argument, @samp{foo} does not expand even though the macro is
58610d565efSmrgenabled, since it has no following parenthesis [pre-expansion of an
58710d565efSmrgargument only uses tokens from that argument; it cannot take tokens
58810d565efSmrgfrom whatever follows the macro invocation].  This still leaves the
58910d565efSmrgargument token @samp{foo} eligible for future expansion.  Then, when
59010d565efSmrgre-scanning after argument replacement, the token @samp{foo} is
59110d565efSmrgrejected for expansion, and marked ineligible for future expansion,
59210d565efSmrgsince the macro is now disabled.  It is disabled because the
59310d565efSmrgreplacement list @samp{bar foo} of the macro is still on the context
59410d565efSmrgstack.
59510d565efSmrg
59610d565efSmrgIf instead the algorithm looked for an opening parenthesis first and
59710d565efSmrgthen tested whether the macro were disabled it would be subtly wrong.
59810d565efSmrgIn the example above, the replacement list of @samp{foo} would be
59910d565efSmrgpopped in the process of finding the parenthesis, re-enabling
60010d565efSmrg@samp{foo} and expanding it a second time.
60110d565efSmrg
60210d565efSmrg@section Looking for a function-like macro's opening parenthesis
60310d565efSmrgFunction-like macros only expand when immediately followed by a
60410d565efSmrgparenthesis.  To do this cpplib needs to temporarily disable macros
60510d565efSmrgand read the next token.  Unfortunately, because of spacing issues
60610d565efSmrg(@pxref{Token Spacing}), there can be fake padding tokens in-between,
60710d565efSmrgand if the next real token is not a parenthesis cpplib needs to be
60810d565efSmrgable to back up that one token as well as retain the information in
60910d565efSmrgany intervening padding tokens.
61010d565efSmrg
61110d565efSmrgBacking up more than one token when macros are involved is not
61210d565efSmrgpermitted by cpplib, because in general it might involve issues like
61310d565efSmrgrestoring popped contexts onto the context stack, which are too hard.
61410d565efSmrgInstead, searching for the parenthesis is handled by a special
61510d565efSmrgfunction, @code{funlike_invocation_p}, which remembers padding
61610d565efSmrginformation as it reads tokens.  If the next real token is not an
61710d565efSmrgopening parenthesis, it backs up that one token, and then pushes an
61810d565efSmrgextra context just containing the padding information if necessary.
61910d565efSmrg
62010d565efSmrg@section Marking tokens ineligible for future expansion
62110d565efSmrgAs discussed above, cpplib needs a way of marking tokens as
62210d565efSmrgunexpandable.  Since the tokens cpplib handles are read-only once they
62310d565efSmrghave been lexed, it instead makes a copy of the token and adds the
62410d565efSmrgflag @code{NO_EXPAND} to the copy.
62510d565efSmrg
62610d565efSmrgFor efficiency and to simplify memory management by avoiding having to
62710d565efSmrgremember to free these tokens, they are allocated as temporary tokens
62810d565efSmrgfrom the lexer's current token run (@pxref{Lexing a line}) using the
62910d565efSmrgfunction @code{_cpp_temp_token}.  The tokens are then re-used once the
63010d565efSmrgcurrent line of tokens has been read in.
63110d565efSmrg
63210d565efSmrgThis might sound unsafe.  However, tokens runs are not re-used at the
63310d565efSmrgend of a line if it happens to be in the middle of a macro argument
63410d565efSmrglist, and cpplib only wants to back-up more than one lexer token in
63510d565efSmrgsituations where no macro expansion is involved, so the optimization
63610d565efSmrgis safe.
63710d565efSmrg
63810d565efSmrg@node Token Spacing
63910d565efSmrg@unnumbered Token Spacing
64010d565efSmrg@cindex paste avoidance
64110d565efSmrg@cindex spacing
64210d565efSmrg@cindex token spacing
64310d565efSmrg
64410d565efSmrgFirst, consider an issue that only concerns the stand-alone
64510d565efSmrgpreprocessor: there needs to be a guarantee that re-reading its preprocessed
64610d565efSmrgoutput results in an identical token stream.  Without taking special
64710d565efSmrgmeasures, this might not be the case because of macro substitution.
64810d565efSmrgFor example:
64910d565efSmrg
65010d565efSmrg@smallexample
65110d565efSmrg#define PLUS +
65210d565efSmrg#define EMPTY
65310d565efSmrg#define f(x) =x=
65410d565efSmrg+PLUS -EMPTY- PLUS+ f(=)
65510d565efSmrg        @expansion{} + + - - + + = = =
65610d565efSmrg@emph{not}
65710d565efSmrg        @expansion{} ++ -- ++ ===
65810d565efSmrg@end smallexample
65910d565efSmrg
66010d565efSmrgOne solution would be to simply insert a space between all adjacent
66110d565efSmrgtokens.  However, we would like to keep space insertion to a minimum,
66210d565efSmrgboth for aesthetic reasons and because it causes problems for people who
66310d565efSmrgstill try to abuse the preprocessor for things like Fortran source and
66410d565efSmrgMakefiles.
66510d565efSmrg
66610d565efSmrgFor now, just notice that when tokens are added (or removed, as shown by
66710d565efSmrgthe @code{EMPTY} example) from the original lexed token stream, we need
66810d565efSmrgto check for accidental token pasting.  We call this @dfn{paste
66910d565efSmrgavoidance}.  Token addition and removal can only occur because of macro
67010d565efSmrgexpansion, but accidental pasting can occur in many places: both before
67110d565efSmrgand after each macro replacement, each argument replacement, and
67210d565efSmrgadditionally each token created by the @samp{#} and @samp{##} operators.
67310d565efSmrg
67410d565efSmrgLook at how the preprocessor gets whitespace output correct
67510d565efSmrgnormally.  The @code{cpp_token} structure contains a flags byte, and one
67610d565efSmrgof those flags is @code{PREV_WHITE}.  This is flagged by the lexer, and
67710d565efSmrgindicates that the token was preceded by whitespace of some form other
67810d565efSmrgthan a new line.  The stand-alone preprocessor can use this flag to
67910d565efSmrgdecide whether to insert a space between tokens in the output.
68010d565efSmrg
68110d565efSmrgNow consider the result of the following macro expansion:
68210d565efSmrg
68310d565efSmrg@smallexample
68410d565efSmrg#define add(x, y, z) x + y +z;
68510d565efSmrgsum = add (1,2, 3);
68610d565efSmrg        @expansion{} sum = 1 + 2 +3;
68710d565efSmrg@end smallexample
68810d565efSmrg
68910d565efSmrgThe interesting thing here is that the tokens @samp{1} and @samp{2} are
69010d565efSmrgoutput with a preceding space, and @samp{3} is output without a
69110d565efSmrgpreceding space, but when lexed none of these tokens had that property.
69210d565efSmrgCareful consideration reveals that @samp{1} gets its preceding
69310d565efSmrgwhitespace from the space preceding @samp{add} in the macro invocation,
69410d565efSmrg@emph{not} replacement list.  @samp{2} gets its whitespace from the
69510d565efSmrgspace preceding the parameter @samp{y} in the macro replacement list,
69610d565efSmrgand @samp{3} has no preceding space because parameter @samp{z} has none
69710d565efSmrgin the replacement list.
69810d565efSmrg
69910d565efSmrgOnce lexed, tokens are effectively fixed and cannot be altered, since
70010d565efSmrgpointers to them might be held in many places, in particular by
70110d565efSmrgin-progress macro expansions.  So instead of modifying the two tokens
70210d565efSmrgabove, the preprocessor inserts a special token, which I call a
70310d565efSmrg@dfn{padding token}, into the token stream to indicate that spacing of
70410d565efSmrgthe subsequent token is special.  The preprocessor inserts padding
70510d565efSmrgtokens in front of every macro expansion and expanded macro argument.
70610d565efSmrgThese point to a @dfn{source token} from which the subsequent real token
70710d565efSmrgshould inherit its spacing.  In the above example, the source tokens are
70810d565efSmrg@samp{add} in the macro invocation, and @samp{y} and @samp{z} in the
70910d565efSmrgmacro replacement list, respectively.
71010d565efSmrg
71110d565efSmrgIt is quite easy to get multiple padding tokens in a row, for example if
71210d565efSmrga macro's first replacement token expands straight into another macro.
71310d565efSmrg
71410d565efSmrg@smallexample
71510d565efSmrg#define foo bar
71610d565efSmrg#define bar baz
71710d565efSmrg[foo]
71810d565efSmrg        @expansion{} [baz]
71910d565efSmrg@end smallexample
72010d565efSmrg
72110d565efSmrgHere, two padding tokens are generated with sources the @samp{foo} token
72210d565efSmrgbetween the brackets, and the @samp{bar} token from foo's replacement
72310d565efSmrglist, respectively.  Clearly the first padding token is the one to
72410d565efSmrguse, so the output code should contain a rule that the first
72510d565efSmrgpadding token in a sequence is the one that matters.
72610d565efSmrg
72710d565efSmrgBut what if a macro expansion is left?  Adjusting the above
72810d565efSmrgexample slightly:
72910d565efSmrg
73010d565efSmrg@smallexample
73110d565efSmrg#define foo bar
73210d565efSmrg#define bar EMPTY baz
73310d565efSmrg#define EMPTY
73410d565efSmrg[foo] EMPTY;
73510d565efSmrg        @expansion{} [ baz] ;
73610d565efSmrg@end smallexample
73710d565efSmrg
73810d565efSmrgAs shown, now there should be a space before @samp{baz} and the
73910d565efSmrgsemicolon in the output.
74010d565efSmrg
74110d565efSmrgThe rules we decided above fail for @samp{baz}: we generate three
74210d565efSmrgpadding tokens, one per macro invocation, before the token @samp{baz}.
74310d565efSmrgWe would then have it take its spacing from the first of these, which
74410d565efSmrgcarries source token @samp{foo} with no leading space.
74510d565efSmrg
74610d565efSmrgIt is vital that cpplib get spacing correct in these examples since any
74710d565efSmrgof these macro expansions could be stringized, where spacing matters.
74810d565efSmrg
74910d565efSmrgSo, this demonstrates that not just entering macro and argument
75010d565efSmrgexpansions, but leaving them requires special handling too.  I made
75110d565efSmrgcpplib insert a padding token with a @code{NULL} source token when
75210d565efSmrgleaving macro expansions, as well as after each replaced argument in a
75310d565efSmrgmacro's replacement list.  It also inserts appropriate padding tokens on
75410d565efSmrgeither side of tokens created by the @samp{#} and @samp{##} operators.
75510d565efSmrgI expanded the rule so that, if we see a padding token with a
75610d565efSmrg@code{NULL} source token, @emph{and} that source token has no leading
75710d565efSmrgspace, then we behave as if we have seen no padding tokens at all.  A
75810d565efSmrgquick check shows this rule will then get the above example correct as
75910d565efSmrgwell.
76010d565efSmrg
76110d565efSmrgNow a relationship with paste avoidance is apparent: we have to be
76210d565efSmrgcareful about paste avoidance in exactly the same locations we have
76310d565efSmrgpadding tokens in order to get white space correct.  This makes
76410d565efSmrgimplementation of paste avoidance easy: wherever the stand-alone
76510d565efSmrgpreprocessor is fixing up spacing because of padding tokens, and it
76610d565efSmrgturns out that no space is needed, it has to take the extra step to
76710d565efSmrgcheck that a space is not needed after all to avoid an accidental paste.
76810d565efSmrgThe function @code{cpp_avoid_paste} advises whether a space is required
76910d565efSmrgbetween two consecutive tokens.  To avoid excessive spacing, it tries
77010d565efSmrghard to only require a space if one is likely to be necessary, but for
77110d565efSmrgreasons of efficiency it is slightly conservative and might recommend a
77210d565efSmrgspace where one is not strictly needed.
77310d565efSmrg
77410d565efSmrg@node Line Numbering
77510d565efSmrg@unnumbered Line numbering
77610d565efSmrg@cindex line numbers
77710d565efSmrg
77810d565efSmrg@section Just which line number anyway?
77910d565efSmrg
78010d565efSmrgThere are three reasonable requirements a cpplib client might have for
78110d565efSmrgthe line number of a token passed to it:
78210d565efSmrg
78310d565efSmrg@itemize @bullet
78410d565efSmrg@item
78510d565efSmrgThe source line it was lexed on.
78610d565efSmrg@item
78710d565efSmrgThe line it is output on.  This can be different to the line it was
78810d565efSmrglexed on if, for example, there are intervening escaped newlines or
78910d565efSmrgC-style comments.  For example:
79010d565efSmrg
79110d565efSmrg@smallexample
79210d565efSmrgfoo /* @r{A long
79310d565efSmrgcomment} */ bar \
79410d565efSmrgbaz
79510d565efSmrg@result{}
79610d565efSmrgfoo bar baz
79710d565efSmrg@end smallexample
79810d565efSmrg
79910d565efSmrg@item
80010d565efSmrgIf the token results from a macro expansion, the line of the macro name,
80110d565efSmrgor possibly the line of the closing parenthesis in the case of
80210d565efSmrgfunction-like macro expansion.
80310d565efSmrg@end itemize
80410d565efSmrg
80510d565efSmrgThe @code{cpp_token} structure contains @code{line} and @code{col}
80610d565efSmrgmembers.  The lexer fills these in with the line and column of the first
80710d565efSmrgcharacter of the token.  Consequently, but maybe unexpectedly, a token
80810d565efSmrgfrom the replacement list of a macro expansion carries the location of
80910d565efSmrgthe token within the @code{#define} directive, because cpplib expands a
81010d565efSmrgmacro by returning pointers to the tokens in its replacement list.  The
81110d565efSmrgcurrent implementation of cpplib assigns tokens created from built-in
81210d565efSmrgmacros and the @samp{#} and @samp{##} operators the location of the most
81310d565efSmrgrecently lexed token.  This is a because they are allocated from the
81410d565efSmrglexer's token runs, and because of the way the diagnostic routines infer
81510d565efSmrgthe appropriate location to report.
81610d565efSmrg
81710d565efSmrgThe diagnostic routines in cpplib display the location of the most
81810d565efSmrgrecently @emph{lexed} token, unless they are passed a specific line and
81910d565efSmrgcolumn to report.  For diagnostics regarding tokens that arise from
82010d565efSmrgmacro expansions, it might also be helpful for the user to see the
82110d565efSmrgoriginal location in the macro definition that the token came from.
82210d565efSmrgSince that is exactly the information each token carries, such an
82310d565efSmrgenhancement could be made relatively easily in future.
82410d565efSmrg
82510d565efSmrgThe stand-alone preprocessor faces a similar problem when determining
82610d565efSmrgthe correct line to output the token on: the position attached to a
82710d565efSmrgtoken is fairly useless if the token came from a macro expansion.  All
82810d565efSmrgtokens on a logical line should be output on its first physical line, so
82910d565efSmrgthe token's reported location is also wrong if it is part of a physical
83010d565efSmrgline other than the first.
83110d565efSmrg
83210d565efSmrgTo solve these issues, cpplib provides a callback that is generated
83310d565efSmrgwhenever it lexes a preprocessing token that starts a new logical line
83410d565efSmrgother than a directive.  It passes this token (which may be a
83510d565efSmrg@code{CPP_EOF} token indicating the end of the translation unit) to the
83610d565efSmrgcallback routine, which can then use the line and column of this token
83710d565efSmrgto produce correct output.
83810d565efSmrg
83910d565efSmrg@section Representation of line numbers
84010d565efSmrg
84110d565efSmrgAs mentioned above, cpplib stores with each token the line number that
84210d565efSmrgit was lexed on.  In fact, this number is not the number of the line in
84310d565efSmrgthe source file, but instead bears more resemblance to the number of the
84410d565efSmrgline in the translation unit.
84510d565efSmrg
84610d565efSmrgThe preprocessor maintains a monotonic increasing line count, which is
84710d565efSmrgincremented at every new line character (and also at the end of any
84810d565efSmrgbuffer that does not end in a new line).  Since a line number of zero is
84910d565efSmrguseful to indicate certain special states and conditions, this variable
85010d565efSmrgstarts counting from one.
85110d565efSmrg
85210d565efSmrgThis variable therefore uniquely enumerates each line in the translation
85310d565efSmrgunit.  With some simple infrastructure, it is straight forward to map
85410d565efSmrgfrom this to the original source file and line number pair, saving space
85510d565efSmrgwhenever line number information needs to be saved.  The code the
85610d565efSmrgimplements this mapping lies in the files @file{line-map.c} and
85710d565efSmrg@file{line-map.h}.
85810d565efSmrg
85910d565efSmrgCommand-line macros and assertions are implemented by pushing a buffer
86010d565efSmrgcontaining the right hand side of an equivalent @code{#define} or
86110d565efSmrg@code{#assert} directive.  Some built-in macros are handled similarly.
86210d565efSmrgSince these are all processed before the first line of the main input
86310d565efSmrgfile, it will typically have an assigned line closer to twenty than to
86410d565efSmrgone.
86510d565efSmrg
86610d565efSmrg@node Guard Macros
86710d565efSmrg@unnumbered The Multiple-Include Optimization
86810d565efSmrg@cindex guard macros
86910d565efSmrg@cindex controlling macros
87010d565efSmrg@cindex multiple-include optimization
87110d565efSmrg
87210d565efSmrgHeader files are often of the form
87310d565efSmrg
87410d565efSmrg@smallexample
87510d565efSmrg#ifndef FOO
87610d565efSmrg#define FOO
87710d565efSmrg@dots{}
87810d565efSmrg#endif
87910d565efSmrg@end smallexample
88010d565efSmrg
88110d565efSmrg@noindent
88210d565efSmrgto prevent the compiler from processing them more than once.  The
88310d565efSmrgpreprocessor notices such header files, so that if the header file
88410d565efSmrgappears in a subsequent @code{#include} directive and @code{FOO} is
88510d565efSmrgdefined, then it is ignored and it doesn't preprocess or even re-open
88610d565efSmrgthe file a second time.  This is referred to as the @dfn{multiple
88710d565efSmrginclude optimization}.
88810d565efSmrg
88910d565efSmrgUnder what circumstances is such an optimization valid?  If the file
89010d565efSmrgwere included a second time, it can only be optimized away if that
89110d565efSmrginclusion would result in no tokens to return, and no relevant
89210d565efSmrgdirectives to process.  Therefore the current implementation imposes
89310d565efSmrgrequirements and makes some allowances as follows:
89410d565efSmrg
89510d565efSmrg@enumerate
89610d565efSmrg@item
89710d565efSmrgThere must be no tokens outside the controlling @code{#if}-@code{#endif}
89810d565efSmrgpair, but whitespace and comments are permitted.
89910d565efSmrg
90010d565efSmrg@item
90110d565efSmrgThere must be no directives outside the controlling directive pair, but
90210d565efSmrgthe @dfn{null directive} (a line containing nothing other than a single
90310d565efSmrg@samp{#} and possibly whitespace) is permitted.
90410d565efSmrg
90510d565efSmrg@item
90610d565efSmrgThe opening directive must be of the form
90710d565efSmrg
90810d565efSmrg@smallexample
90910d565efSmrg#ifndef FOO
91010d565efSmrg@end smallexample
91110d565efSmrg
91210d565efSmrgor
91310d565efSmrg
91410d565efSmrg@smallexample
91510d565efSmrg#if !defined FOO     [equivalently, #if !defined(FOO)]
91610d565efSmrg@end smallexample
91710d565efSmrg
91810d565efSmrg@item
91910d565efSmrgIn the second form above, the tokens forming the @code{#if} expression
92010d565efSmrgmust have come directly from the source file---no macro expansion must
92110d565efSmrghave been involved.  This is because macro definitions can change, and
92210d565efSmrgtracking whether or not a relevant change has been made is not worth the
92310d565efSmrgimplementation cost.
92410d565efSmrg
92510d565efSmrg@item
92610d565efSmrgThere can be no @code{#else} or @code{#elif} directives at the outer
92710d565efSmrgconditional block level, because they would probably contain something
92810d565efSmrgof interest to a subsequent pass.
92910d565efSmrg@end enumerate
93010d565efSmrg
93110d565efSmrgFirst, when pushing a new file on the buffer stack,
93210d565efSmrg@code{_stack_include_file} sets the controlling macro @code{mi_cmacro} to
93310d565efSmrg@code{NULL}, and sets @code{mi_valid} to @code{true}.  This indicates
93410d565efSmrgthat the preprocessor has not yet encountered anything that would
93510d565efSmrginvalidate the multiple-include optimization.  As described in the next
93610d565efSmrgfew paragraphs, these two variables having these values effectively
93710d565efSmrgindicates top-of-file.
93810d565efSmrg
93910d565efSmrgWhen about to return a token that is not part of a directive,
94010d565efSmrg@code{_cpp_lex_token} sets @code{mi_valid} to @code{false}.  This
94110d565efSmrgenforces the constraint that tokens outside the controlling conditional
94210d565efSmrgblock invalidate the optimization.
94310d565efSmrg
94410d565efSmrgThe @code{do_if}, when appropriate, and @code{do_ifndef} directive
94510d565efSmrghandlers pass the controlling macro to the function
94610d565efSmrg@code{push_conditional}.  cpplib maintains a stack of nested conditional
94710d565efSmrgblocks, and after processing every opening conditional this function
94810d565efSmrgpushes an @code{if_stack} structure onto the stack.  In this structure
94910d565efSmrgit records the controlling macro for the block, provided there is one
95010d565efSmrgand we're at top-of-file (as described above).  If an @code{#elif} or
95110d565efSmrg@code{#else} directive is encountered, the controlling macro for that
95210d565efSmrgblock is cleared to @code{NULL}.  Otherwise, it survives until the
95310d565efSmrg@code{#endif} closing the block, upon which @code{do_endif} sets
95410d565efSmrg@code{mi_valid} to true and stores the controlling macro in
95510d565efSmrg@code{mi_cmacro}.
95610d565efSmrg
95710d565efSmrg@code{_cpp_handle_directive} clears @code{mi_valid} when processing any
95810d565efSmrgdirective other than an opening conditional and the null directive.
95910d565efSmrgWith this, and requiring top-of-file to record a controlling macro, and
96010d565efSmrgno @code{#else} or @code{#elif} for it to survive and be copied to
96110d565efSmrg@code{mi_cmacro} by @code{do_endif}, we have enforced the absence of
96210d565efSmrgdirectives outside the main conditional block for the optimization to be
96310d565efSmrgon.
96410d565efSmrg
96510d565efSmrgNote that whilst we are inside the conditional block, @code{mi_valid} is
96610d565efSmrglikely to be reset to @code{false}, but this does not matter since
96710d565efSmrgthe closing @code{#endif} restores it to @code{true} if appropriate.
96810d565efSmrg
96910d565efSmrgFinally, since @code{_cpp_lex_direct} pops the file off the buffer stack
97010d565efSmrgat @code{EOF} without returning a token, if the @code{#endif} directive
97110d565efSmrgwas not followed by any tokens, @code{mi_valid} is @code{true} and
97210d565efSmrg@code{_cpp_pop_file_buffer} remembers the controlling macro associated
97310d565efSmrgwith the file.  Subsequent calls to @code{stack_include_file} result in
97410d565efSmrgno buffer being pushed if the controlling macro is defined, effecting
97510d565efSmrgthe optimization.
97610d565efSmrg
97710d565efSmrgA quick word on how we handle the
97810d565efSmrg
97910d565efSmrg@smallexample
98010d565efSmrg#if !defined FOO
98110d565efSmrg@end smallexample
98210d565efSmrg
98310d565efSmrg@noindent
98410d565efSmrgcase.  @code{_cpp_parse_expr} and @code{parse_defined} take steps to see
98510d565efSmrgwhether the three stages @samp{!}, @samp{defined-expression} and
98610d565efSmrg@samp{end-of-directive} occur in order in a @code{#if} expression.  If
98710d565efSmrgso, they return the guard macro to @code{do_if} in the variable
98810d565efSmrg@code{mi_ind_cmacro}, and otherwise set it to @code{NULL}.
98910d565efSmrg@code{enter_macro_context} sets @code{mi_valid} to false, so if a macro
99010d565efSmrgwas expanded whilst parsing any part of the expression, then the
99110d565efSmrgtop-of-file test in @code{push_conditional} fails and the optimization
99210d565efSmrgis turned off.
99310d565efSmrg
99410d565efSmrg@node Files
99510d565efSmrg@unnumbered File Handling
99610d565efSmrg@cindex files
99710d565efSmrg
99810d565efSmrgFairly obviously, the file handling code of cpplib resides in the file
99910d565efSmrg@file{files.c}.  It takes care of the details of file searching,
100010d565efSmrgopening, reading and caching, for both the main source file and all the
100110d565efSmrgheaders it recursively includes.
100210d565efSmrg
100310d565efSmrgThe basic strategy is to minimize the number of system calls.  On many
100410d565efSmrgsystems, the basic @code{open ()} and @code{fstat ()} system calls can
100510d565efSmrgbe quite expensive.  For every @code{#include}-d file, we need to try
100610d565efSmrgall the directories in the search path until we find a match.  Some
100710d565efSmrgprojects, such as glibc, pass twenty or thirty include paths on the
100810d565efSmrgcommand line, so this can rapidly become time consuming.
100910d565efSmrg
101010d565efSmrgFor a header file we have not encountered before we have little choice
101110d565efSmrgbut to do this.  However, it is often the case that the same headers are
101210d565efSmrgrepeatedly included, and in these cases we try to avoid repeating the
101310d565efSmrgfilesystem queries whilst searching for the correct file.
101410d565efSmrg
101510d565efSmrgFor each file we try to open, we store the constructed path in a splay
101610d565efSmrgtree.  This path first undergoes simplification by the function
101710d565efSmrg@code{_cpp_simplify_pathname}.  For example,
101810d565efSmrg@file{/usr/include/bits/../foo.h} is simplified to
101910d565efSmrg@file{/usr/include/foo.h} before we enter it in the splay tree and try
102010d565efSmrgto @code{open ()} the file.  CPP will then find subsequent uses of
102110d565efSmrg@file{foo.h}, even as @file{/usr/include/foo.h}, in the splay tree and
102210d565efSmrgsave system calls.
102310d565efSmrg
102410d565efSmrgFurther, it is likely the file contents have also been cached, saving a
102510d565efSmrg@code{read ()} system call.  We don't bother caching the contents of
102610d565efSmrgheader files that are re-inclusion protected, and whose re-inclusion
102710d565efSmrgmacro is defined when we leave the header file for the first time.  If
102810d565efSmrgthe host supports it, we try to map suitably large files into memory,
102910d565efSmrgrather than reading them in directly.
103010d565efSmrg
103110d565efSmrgThe include paths are internally stored on a null-terminated
103210d565efSmrgsingly-linked list, starting with the @code{"header.h"} directory search
103310d565efSmrgchain, which then links into the @code{<header.h>} directory chain.
103410d565efSmrg
103510d565efSmrgFiles included with the @code{<foo.h>} syntax start the lookup directly
103610d565efSmrgin the second half of this chain.  However, files included with the
103710d565efSmrg@code{"foo.h"} syntax start at the beginning of the chain, but with one
103810d565efSmrgextra directory prepended.  This is the directory of the current file;
103910d565efSmrgthe one containing the @code{#include} directive.  Prepending this
104010d565efSmrgdirectory on a per-file basis is handled by the function
104110d565efSmrg@code{search_from}.
104210d565efSmrg
104310d565efSmrgNote that a header included with a directory component, such as
104410d565efSmrg@code{#include "mydir/foo.h"} and opened as
104510d565efSmrg@file{/usr/local/include/mydir/foo.h}, will have the complete path minus
104610d565efSmrgthe basename @samp{foo.h} as the current directory.
104710d565efSmrg
104810d565efSmrgEnough information is stored in the splay tree that CPP can immediately
104910d565efSmrgtell whether it can skip the header file because of the multiple include
105010d565efSmrgoptimization, whether the file didn't exist or couldn't be opened for
105110d565efSmrgsome reason, or whether the header was flagged not to be re-used, as it
105210d565efSmrgis with the obsolete @code{#import} directive.
105310d565efSmrg
105410d565efSmrgFor the benefit of MS-DOS filesystems with an 8.3 filename limitation,
105510d565efSmrgCPP offers the ability to treat various include file names as aliases
105610d565efSmrgfor the real header files with shorter names.  The map from one to the
105710d565efSmrgother is found in a special file called @samp{header.gcc}, stored in the
105810d565efSmrgcommand line (or system) include directories to which the mapping
105910d565efSmrgapplies.  This may be higher up the directory tree than the full path to
106010d565efSmrgthe file minus the base name.
106110d565efSmrg
106210d565efSmrg@node Concept Index
106310d565efSmrg@unnumbered Concept Index
106410d565efSmrg@printindex cp
106510d565efSmrg
106610d565efSmrg@bye
1067