Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

cppinternals.info 49KB

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