OSDN Git Service

* cpplib.c (do_include_common): Revert to correct line number
[pf3gnuchains/gcc-fork.git] / gcc / cpptrad.c
1 /* CPP Library - traditional lexical analysis and macro expansion.
2    Copyright (C) 2002 Free Software Foundation, Inc.
3    Contributed by Neil Booth, May 2002
4
5 This program is free software; you can redistribute it and/or modify it
6 under the terms of the GNU General Public License as published by the
7 Free Software Foundation; either version 2, or (at your option) any
8 later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
18
19 #include "config.h"
20 #include "system.h"
21 #include "cpplib.h"
22 #include "cpphash.h"
23
24 /* The replacement text of a function-like macro is stored as a
25    contiguous sequence of aligned blocks, each representing the text
26    between subsequent parameters in that text.
27
28    Each block comprises the length of text contained therein, the
29    one-based index of the argument that immediately follows that text,
30    and the text itself.  The final block in the macro expansion is
31    easily recognizable as it has an argument index of zero.  */
32
33 struct block
34 {
35   unsigned int text_len;
36   unsigned short arg_index;
37   uchar text[1];
38 };
39
40 #define BLOCK_HEADER_LEN offsetof (struct block, text)
41 #define BLOCK_LEN(TEXT_LEN) CPP_ALIGN (BLOCK_HEADER_LEN + (TEXT_LEN))
42
43 /* Structure holding information about a function-like macro
44    invocation.  */
45 struct fun_macro
46 {
47   /* Memory buffer holding the trad_arg array.  */
48   _cpp_buff *buff;
49
50   /* An array of size the number of macro parameters + 1, containing
51      the offsets of the start of each macro argument in the output
52      buffer.  The argument continues until the character before the
53      start of the next one.  */
54   size_t *args;
55
56   /* The hashnode of the macro.  */
57   cpp_hashnode *node;
58
59   /* The offset of the macro name in the output buffer.  */
60   size_t offset;
61
62   /* The line the macro name appeared on.  */
63   unsigned int line;
64
65   /* Zero-based index of argument being currently lexed.  */
66   unsigned int argc;
67 };
68
69 /* Lexing state.  It is mostly used to prevent macro expansion.  */
70 enum ls {ls_none = 0,           /* Normal state.  */
71          ls_fun_open,           /* When looking for '('.  */
72          ls_fun_close,          /* When looking for ')'.  */
73          ls_defined,            /* After defined.  */
74          ls_defined_close,      /* Looking for ')' of defined().  */
75          ls_hash,               /* After # in preprocessor conditional.  */
76          ls_predicate,          /* After the predicate, maybe paren?  */
77          ls_answer};            /* In answer to predicate.  */
78
79 /* Lexing TODO: Maybe handle space in escaped newlines.  Stop cpplex.c
80    from recognizing comments and directives during its lexing pass.  */
81
82 static const uchar *handle_newline PARAMS ((cpp_reader *, const uchar *));
83 static const uchar *skip_escaped_newlines PARAMS ((cpp_reader *,
84                                                    const uchar *));
85 static const uchar *skip_whitespace PARAMS ((cpp_reader *, const uchar *,
86                                              int));
87 static cpp_hashnode *lex_identifier PARAMS ((cpp_reader *, const uchar *));
88 static const uchar *copy_comment PARAMS ((cpp_reader *, const uchar *, int));
89 static void scan_out_logical_line PARAMS ((cpp_reader *pfile, cpp_macro *));
90 static void check_output_buffer PARAMS ((cpp_reader *, size_t));
91 static void push_replacement_text PARAMS ((cpp_reader *, cpp_hashnode *));
92 static bool scan_parameters PARAMS ((cpp_reader *, cpp_macro *));
93 static bool recursive_macro PARAMS ((cpp_reader *, cpp_hashnode *));
94 static void save_replacement_text PARAMS ((cpp_reader *, cpp_macro *,
95                                            unsigned int));
96 static void maybe_start_funlike PARAMS ((cpp_reader *, cpp_hashnode *,
97                                          const uchar *, struct fun_macro *));
98 static void save_argument PARAMS ((struct fun_macro *, size_t));
99 static void replace_args_and_push PARAMS ((cpp_reader *, struct fun_macro *));
100 static size_t canonicalize_text PARAMS ((uchar *, const uchar *, size_t,
101                                          uchar *));
102
103 /* Ensures we have N bytes' space in the output buffer, and
104    reallocates it if not.  */
105 static void
106 check_output_buffer (pfile, n)
107      cpp_reader *pfile;
108      size_t n;
109 {
110   /* We might need two bytes to terminate an unterminated comment, and
111      one more to terminate the line with a NUL.  */
112   n += 2 + 1;
113
114   if (n > (size_t) (pfile->out.limit - pfile->out.cur))
115     {
116       size_t size = pfile->out.cur - pfile->out.base;
117       size_t new_size = (size + n) * 3 / 2;
118
119       pfile->out.base
120         = (uchar *) xrealloc (pfile->out.base, new_size);
121       pfile->out.limit = pfile->out.base + new_size;
122       pfile->out.cur = pfile->out.base + size;
123     }
124 }
125
126 /* To be called whenever a newline character is encountered in the
127    input file, at CUR.  Handles DOS, Mac and Unix ends of line, and
128    increments pfile->line.
129
130    Returns a pointer the character after the newline sequence.  */
131 static const uchar *
132 handle_newline (pfile, cur)
133      cpp_reader *pfile;
134      const uchar *cur;
135 {
136   pfile->line++;
137   if (cur[0] + cur[1] == '\r' + '\n')
138     cur++;
139   return cur + 1;
140 }
141
142 /* CUR points to any character in the buffer, not necessarily a
143    backslash.  Advances CUR until all escaped newlines are skipped,
144    and returns the new position.
145
146    Warns if a file buffer ends in an escaped newline.  */
147 static const uchar *
148 skip_escaped_newlines (pfile, cur)
149      cpp_reader *pfile;
150      const uchar *cur;
151 {
152   const uchar *orig_cur = cur;
153
154   while (*cur == '\\' && is_vspace (cur[1]))
155     cur = handle_newline (pfile, cur + 1);
156
157   if (cur != orig_cur && cur == RLIMIT (pfile->context) && pfile->buffer->inc)
158     cpp_error (pfile, DL_PEDWARN, "backslash-newline at end of file");
159
160   return cur;
161 }
162
163 /* CUR points to the asterisk introducing a comment in the input
164    buffer.  IN_DEFINE is true if we are in the replacement text
165    of a macro.
166
167    The asterisk and following comment is copied to the buffer pointed
168    to by pfile->out.cur, which must be of sufficient size.
169    Unterminated comments are diagnosed, and correctly terminated in
170    the output.  pfile->out.cur is updated depending upon IN_DEFINE,
171    -C, -CC and pfile->state.in_directive.
172
173    Returns a pointer to the first character after the comment in the
174    input buffer.  */
175 static const uchar *
176 copy_comment (pfile, cur, in_define)
177      cpp_reader *pfile;
178      const uchar *cur;
179      int in_define;
180 {
181   unsigned int from_line = pfile->line;
182   const uchar *limit = RLIMIT (pfile->context);
183   uchar *out = pfile->out.cur;
184
185   do
186     {
187       unsigned int c = *cur++;
188       *out++ = c;
189
190       if (c == '/')
191         {
192           /* An immediate slash does not terminate the comment.  */
193           if (out[-2] == '*' && out - 2 > pfile->out.cur)
194             goto done;
195
196           if (*cur == '*' && cur[1] != '/'
197               && CPP_OPTION (pfile, warn_comments))
198             cpp_error_with_line (pfile, DL_WARNING, pfile->line, 0,
199                                  "\"/*\" within comment");
200         }
201       else if (is_vspace (c))
202         {
203           cur = handle_newline (pfile, cur - 1);
204           /* Canonicalize newline sequences and skip escaped ones.  */
205           if (out[-2] == '\\')
206             out -= 2;
207           else
208             out[-1] = '\n';
209         }
210     }
211   while (cur < limit);
212
213   cpp_error_with_line (pfile, DL_ERROR, from_line, 0, "unterminated comment");
214   *out++ = '*';
215   *out++ = '/';
216
217  done:
218   /* Comments in directives become spaces so that tokens are properly
219      separated when the ISO preprocessor re-lexes the line.  The
220      exception is #define.  */
221   if (pfile->state.in_directive)
222     {
223       if (in_define)
224         {
225           if (CPP_OPTION (pfile, discard_comments_in_macro_exp))
226             pfile->out.cur--;
227           else
228             pfile->out.cur = out;
229         }
230       else
231         pfile->out.cur[-1] = ' ';
232     }
233   else if (CPP_OPTION (pfile, discard_comments))
234     pfile->out.cur--;
235   else
236     pfile->out.cur = out;
237
238   return cur;
239 }
240
241 /* CUR points to any character in the input buffer.  Skips over all
242    contiguous horizontal white space and NULs, including comments if
243    SKIP_COMMENTS, until reaching the first non-horizontal-whitespace
244    character or the end of the current context.  Escaped newlines are
245    removed.
246
247    The whitespace is copied verbatim to the output buffer, except that
248    comments are handled as described in copy_comment().
249    pfile->out.cur is updated.
250
251    Returns a pointer to the first character after the whitespace in
252    the input buffer.  */
253 static const uchar *
254 skip_whitespace (pfile, cur, skip_comments)
255      cpp_reader *pfile;
256      const uchar *cur;
257      int skip_comments;
258 {
259   uchar *out = pfile->out.cur;
260
261   for (;;)
262     {
263       unsigned int c = *cur++;
264       *out++ = c;
265
266       if (is_nvspace (c) && c)
267         continue;
268
269       if (!c && cur - 1 != RLIMIT (pfile->context))
270         continue;
271
272       if (c == '/' && skip_comments)
273         {
274           const uchar *tmp = skip_escaped_newlines (pfile, cur);
275           if (*tmp == '*')
276             {
277               pfile->out.cur = out;
278               cur = copy_comment (pfile, tmp, false /* in_define */);
279               out = pfile->out.cur;
280               continue;
281             }
282         }
283
284       out--;
285       if (c == '\\' && is_vspace (*cur))
286         {
287           cur = skip_escaped_newlines (pfile, cur);
288           continue;
289         }
290
291       break;
292     }
293
294   pfile->out.cur = out;
295   return cur - 1;
296 }
297
298 /* Lexes and outputs an identifier starting at CUR, which is assumed
299    to point to a valid first character of an identifier.  Returns
300    the hashnode, and updates out.cur.  */
301 static cpp_hashnode *
302 lex_identifier (pfile, cur)
303      cpp_reader *pfile;
304      const uchar *cur;
305 {
306   size_t len;
307   uchar *out = pfile->out.cur;
308   cpp_hashnode *result;
309
310   do
311     {
312       do
313         *out++ = *cur++;
314       while (is_numchar (*cur));
315       cur = skip_escaped_newlines (pfile, cur);
316     }
317   while (is_numchar (*cur));
318
319   CUR (pfile->context) = cur;
320   len = out - pfile->out.cur;
321   result = (cpp_hashnode *) ht_lookup (pfile->hash_table, pfile->out.cur,
322                                        len, HT_ALLOC);
323   pfile->out.cur = out;
324   return result;
325 }
326
327 /* Overlays the true file buffer temporarily with text of length LEN
328    starting at START.  The true buffer is restored upon calling
329    restore_buff().  */
330 void
331 _cpp_overlay_buffer (pfile, start, len)
332      cpp_reader *pfile;
333      const uchar *start;
334      size_t len;
335 {
336   cpp_buffer *buffer = pfile->buffer;
337
338   pfile->overlaid_buffer = buffer;
339   buffer->saved_cur = buffer->cur;
340   buffer->saved_rlimit = buffer->rlimit;
341
342   buffer->cur = start;
343   buffer->rlimit = start + len;
344
345   pfile->saved_line = pfile->line;
346 }
347
348 /* Restores a buffer overlaid by _cpp_overlay_buffer().  */
349 void
350 _cpp_remove_overlay (pfile)
351      cpp_reader *pfile;
352 {
353   cpp_buffer *buffer = pfile->overlaid_buffer;
354
355   buffer->cur = buffer->saved_cur;
356   buffer->rlimit = buffer->saved_rlimit;
357
358   pfile->line = pfile->saved_line;
359 }
360
361 /* Reads a logical line into the output buffer.  Returns TRUE if there
362    is more text left in the buffer.  */
363 bool
364 _cpp_read_logical_line_trad (pfile)
365      cpp_reader *pfile;
366 {
367   cpp_buffer *buffer = pfile->buffer;
368
369   do
370     {
371       if (buffer->cur == buffer->rlimit)
372         {
373           bool stop = true;
374
375           /* Don't pop the last buffer.  */
376           if (buffer->prev)
377             {
378               stop = buffer->return_at_eof;
379               _cpp_pop_buffer (pfile);
380               buffer = pfile->buffer;
381             }
382
383           if (stop)
384             return false;
385         }
386
387       CUR (pfile->context) = buffer->cur;
388       RLIMIT (pfile->context) = buffer->rlimit;
389       scan_out_logical_line (pfile, NULL);
390       buffer = pfile->buffer;
391       buffer->cur = CUR (pfile->context);
392     }
393   while (pfile->state.skipping);
394
395   return true;
396 }
397
398 /* Set up state for finding the opening '(' of a function-like
399    macro.  */
400 static void
401 maybe_start_funlike (pfile, node, start, macro)
402      cpp_reader *pfile;
403      cpp_hashnode *node;
404      const uchar *start;
405      struct fun_macro *macro;
406 {
407   unsigned int n = node->value.macro->paramc + 1;
408
409   if (macro->buff)
410     _cpp_release_buff (pfile, macro->buff);
411   macro->buff = _cpp_get_buff (pfile, n * sizeof (size_t));
412   macro->args = (size_t *) BUFF_FRONT (macro->buff);
413   macro->node = node;
414   macro->offset = start - pfile->out.base;
415   macro->argc = 0;
416 }
417
418 /* Save the OFFSET of the start of the next argument to MACRO.  */
419 static void
420 save_argument (macro, offset)
421      struct fun_macro *macro;
422      size_t offset;
423 {
424   macro->argc++;
425   if (macro->argc <= macro->node->value.macro->paramc)
426     macro->args[macro->argc] = offset;
427 }
428
429 /* Copies the next logical line in the current buffer to the output
430    buffer.  The output is guaranteed to terminate with a NUL
431    character.
432
433    If MACRO is non-NULL, then we are scanning the replacement list of
434    MACRO, and we call save_replacement_text() every time we meet an
435    argument.  */
436 static void
437 scan_out_logical_line (pfile, macro)
438      cpp_reader *pfile;
439      cpp_macro *macro;
440 {
441   cpp_context *context;
442   const uchar *cur;
443   uchar *out;
444   struct fun_macro fmacro;
445   unsigned int c, paren_depth = 0, quote = 0;
446   enum ls lex_state = ls_none;
447
448   fmacro.buff = NULL;
449
450  start_logical_line:
451   pfile->out.cur = pfile->out.base;
452   pfile->out.first_line = pfile->line;
453  new_context:
454   context = pfile->context;
455   cur = CUR (context);
456   check_output_buffer (pfile, RLIMIT (context) - cur);
457   out = pfile->out.cur;
458
459   for (;;)
460     {
461       c = *cur++;
462       *out++ = c;
463
464       /* Whitespace should "continue" out of the switch,
465          non-whitespace should "break" out of it.  */
466       switch (c)
467         {
468         case ' ':
469         case '\t':
470         case '\f':
471         case '\v':
472           continue;
473
474         case '\0':
475           if (cur - 1 != RLIMIT (context))
476             continue;
477
478           /* If this is a macro's expansion, pop it.  */
479           if (context->prev)
480             {
481               pfile->out.cur = out - 1;
482               _cpp_pop_context (pfile);
483               goto new_context;
484             }
485
486           /* Premature end of file.  Fake a new line.  */
487           cur--;
488           if (!pfile->buffer->from_stage3)
489             cpp_error (pfile, DL_PEDWARN, "no newline at end of file");
490           pfile->line++;
491           goto done;
492
493         case '\r': case '\n':
494           cur = handle_newline (pfile, cur - 1);
495           if ((lex_state == ls_fun_open || lex_state == ls_fun_close)
496               && !pfile->state.in_directive)
497             {
498               /* Newlines in arguments become a space.  */
499               if (lex_state == ls_fun_close)
500                 out[-1] = ' ';
501               continue;
502             }
503           goto done;
504
505         case '<':
506           if (pfile->state.angled_headers && !quote)
507             quote = '>';
508           break;
509         case '>':
510           if (pfile->state.angled_headers && c == quote)
511             {
512               pfile->state.angled_headers = false;
513               quote = 0;
514             }
515           break;
516
517         case '"':
518         case '\'':
519           if (c == quote)
520             quote = 0;
521           else if (!quote)
522             quote = c;
523           break;
524
525         case '\\':
526           if (is_vspace (*cur))
527             {
528               out--;
529               cur = skip_escaped_newlines (pfile, cur - 1);
530               continue;
531             }
532           else
533             {
534               /* Skip escaped quotes here, it's easier than above, but
535                  take care to first skip escaped newlines.  */
536               cur = skip_escaped_newlines (pfile, cur);
537               if (*cur == '\\' || *cur == '"' || *cur == '\'')
538                 *out++ = *cur++;
539             }
540           break;
541
542         case '/':
543           /* Traditional CPP does not recognize comments within
544              literals.  */
545           if (!quote)
546             {
547               cur = skip_escaped_newlines (pfile, cur);
548               if (*cur == '*')
549                 {
550                   pfile->out.cur = out;
551                   cur = copy_comment (pfile, cur, macro != 0);
552                   out = pfile->out.cur;
553                   continue;
554                 }
555             }
556           break;
557
558         case '_':
559         case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
560         case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
561         case 'm': case 'n': case 'o': case 'p': case 'q': case 'r':
562         case 's': case 't': case 'u': case 'v': case 'w': case 'x':
563         case 'y': case 'z':
564         case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
565         case 'G': case 'H': case 'I': case 'J': case 'K': case 'L':
566         case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R':
567         case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
568         case 'Y': case 'Z':
569           if (!pfile->state.skipping && (quote == 0 || macro))
570             {
571               cpp_hashnode *node;
572               uchar *out_start = out - 1;
573
574               pfile->out.cur = out_start;
575               node = lex_identifier (pfile, cur - 1);
576               out = pfile->out.cur;
577               cur = CUR (context);
578
579               if (node->type == NT_MACRO
580                   /* Should we expand for ls_answer?  */
581                   && (lex_state == ls_none || lex_state == ls_fun_open)
582                   && !pfile->state.prevent_expansion)
583                 {
584                   /* Macros invalidate MI optimization.  */
585                   pfile->mi_valid = false;
586                   if (! (node->flags & NODE_BUILTIN)
587                       && node->value.macro->fun_like)
588                     {
589                       maybe_start_funlike (pfile, node, out_start, &fmacro);
590                       lex_state = ls_fun_open;
591                       fmacro.line = pfile->line;
592                       continue;
593                     }
594                   else if (!recursive_macro (pfile, node))
595                     {
596                       /* Remove the object-like macro's name from the
597                          output, and push its replacement text.  */
598                       pfile->out.cur = out_start;
599                       push_replacement_text (pfile, node);
600                       lex_state = ls_none;
601                       goto new_context;
602                     }
603                 }
604               else if (macro && node->arg_index)
605                 {
606                   /* Found a parameter in the replacement text of a
607                      #define.  Remove its name from the output.  */
608                   pfile->out.cur = out_start;
609                   save_replacement_text (pfile, macro, node->arg_index);
610                   out = pfile->out.base;
611                 }
612               else if (lex_state == ls_hash)
613                 {
614                   lex_state = ls_predicate;
615                   continue;
616                 }
617               else if (pfile->state.in_expression
618                        && node == pfile->spec_nodes.n_defined)
619                 {
620                   lex_state = ls_defined;
621                   continue;
622                 }
623             }
624           break;
625
626         case '(':
627           if (quote == 0)
628             {
629               paren_depth++;
630               if (lex_state == ls_fun_open)
631                 {
632                   if (recursive_macro (pfile, fmacro.node))
633                     lex_state = ls_none;
634                   else
635                     {
636                       lex_state = ls_fun_close;
637                       paren_depth = 1;
638                       out = pfile->out.base + fmacro.offset;
639                       fmacro.args[0] = fmacro.offset;
640                     }
641                 }
642               else if (lex_state == ls_predicate)
643                 lex_state = ls_answer;
644               else if (lex_state == ls_defined)
645                 lex_state = ls_defined_close;
646             }
647           break;
648
649         case ',':
650           if (quote == 0 && lex_state == ls_fun_close && paren_depth == 1)
651             save_argument (&fmacro, out - pfile->out.base);
652           break;
653
654         case ')':
655           if (quote == 0)
656             {
657               paren_depth--;
658               if (lex_state == ls_fun_close && paren_depth == 0)
659                 {
660                   cpp_macro *m = fmacro.node->value.macro;
661
662                   lex_state = ls_none;
663                   save_argument (&fmacro, out - pfile->out.base);
664
665                   /* A single zero-length argument is no argument.  */
666                   if (fmacro.argc == 1
667                       && m->paramc == 0
668                       && out == pfile->out.base + fmacro.offset + 1)
669                     fmacro.argc = 0;
670
671                   if (_cpp_arguments_ok (pfile, m, fmacro.node, fmacro.argc))
672                     {
673                       /* Remove the macro's invocation from the
674                          output, and push its replacement text.  */
675                       pfile->out.cur = (pfile->out.base
676                                              + fmacro.offset);
677                       CUR (context) = cur;
678                       replace_args_and_push (pfile, &fmacro);
679                       goto new_context;
680                     }
681                 }
682               else if (lex_state == ls_answer || lex_state == ls_defined_close)
683                 lex_state = ls_none;
684             }
685           break;
686
687         case '#':
688           if (out - 1 == pfile->out.base && !pfile->state.in_directive)
689             {
690               /* A directive.  With the way _cpp_handle_directive
691                  currently works, we only want to call it if either we
692                  know the directive is OK, or we want it to fail and
693                  be removed from the output.  If we want it to be
694                  passed through (the assembler case) then we must not
695                  call _cpp_handle_directive.  */
696               pfile->out.cur = out;
697               cur = skip_whitespace (pfile, cur, true /* skip_comments */);
698               out = pfile->out.cur;
699
700               if (is_vspace (*cur))
701                 {
702                   /* Null directive.  Ignore it and don't invalidate
703                      the MI optimization.  */
704                   out = pfile->out.base;
705                   continue;
706                 }
707               else
708                 {
709                   bool do_it = false;
710
711                   if (is_numstart (*cur))
712                     do_it = true;
713                   else if (is_idstart (*cur))
714                     /* Check whether we know this directive, but don't
715                        advance.  */
716                     do_it = lex_identifier (pfile, cur)->directive_index != 0;
717
718                   if (do_it || CPP_OPTION (pfile, lang) != CLK_ASM)
719                     {
720                       /* This is a kludge.  We want to have the ISO
721                          preprocessor lex the next token.  */
722                       pfile->buffer->cur = cur;
723                       _cpp_handle_directive (pfile, false /* indented */);
724                       goto start_logical_line;
725                     }
726                 }
727             }
728
729           if (pfile->state.in_expression)
730             {
731               lex_state = ls_hash;
732               continue;
733             }
734           break;
735
736         default:
737           break;
738         }
739
740       /* Non-whitespace disables MI optimization.  */
741       if (!pfile->state.in_directive)
742         pfile->mi_valid = false;
743
744       if (lex_state == ls_none)
745         continue;
746
747       /* Some of these transitions of state are syntax errors.  The
748          ISO preprocessor will issue errors later.  */
749       if (lex_state == ls_fun_open)
750         /* Missing '('.  */
751         lex_state = ls_none;
752       else if (lex_state == ls_hash
753                || lex_state == ls_predicate
754                || lex_state == ls_defined)
755         lex_state = ls_none;
756
757       /* ls_answer and ls_defined_close keep going until ')'.  */
758     }
759
760  done:
761   out[-1] = '\0';
762   CUR (context) = cur;
763   pfile->out.cur = out - 1;
764   if (fmacro.buff)
765     _cpp_release_buff (pfile, fmacro.buff);
766
767   if (lex_state == ls_fun_close)
768     cpp_error_with_line (pfile, DL_ERROR, fmacro.line, 0,
769                          "unterminated argument list invoking macro \"%s\"",
770                          NODE_NAME (fmacro.node));
771 }
772
773 /* Push a context holding the replacement text of the macro NODE on
774    the context stack.  NODE is either object-like, or a function-like
775    macro with no arguments.  */
776 static void
777 push_replacement_text (pfile, node)
778      cpp_reader *pfile;
779      cpp_hashnode *node;
780 {
781   size_t len;
782   const uchar *text;
783
784   if (node->flags & NODE_BUILTIN)
785     {
786       text = _cpp_builtin_macro_text (pfile, node);
787       len = ustrlen (text);
788     }
789   else
790     {
791       cpp_macro *macro = node->value.macro;
792       text = macro->exp.text;
793       len = macro->count;
794     }
795
796   _cpp_push_text_context (pfile, node, text, len);
797 }
798
799 /* Returns TRUE if traditional macro recursion is detected.  */
800 static bool
801 recursive_macro (pfile, node)
802      cpp_reader *pfile;
803      cpp_hashnode *node;
804 {
805   bool recursing = node->flags & NODE_DISABLED;
806
807   /* Object-like macros that are already expanding are necessarily
808      recursive.
809
810      However, it is possible to have traditional function-like macros
811      that are not infinitely recursive but recurse to any given depth.
812      Further, it is easy to construct examples that get ever longer
813      until the point they stop recursing.  So there is no easy way to
814      detect true recursion; instead we assume any expansion more than
815      20 deep since the first invocation of this macro must be
816      recursing.  */
817   if (recursing && node->value.macro->fun_like)
818     {
819       size_t depth = 0;
820       cpp_context *context = pfile->context;
821
822       do
823         {
824           depth++;
825           if (context->macro == node && depth > 20)
826             break;
827           context = context->prev;
828         }
829       while (context);
830       recursing = context != NULL;
831     }
832
833   if (recursing)
834     cpp_error (pfile, DL_ERROR,
835                "detected recursion whilst expanding macro \"%s\"",
836                NODE_NAME (node));
837
838   return recursing;
839 }
840
841 /* Return the length of the replacement text of a function-like or
842    object-like non-builtin macro.  */
843 size_t
844 _cpp_replacement_text_len (macro)
845      const cpp_macro *macro;
846 {
847   size_t len;
848
849   if (macro->fun_like)
850     {
851       const uchar *exp;
852
853       len = 0;
854       for (exp = macro->exp.text;;)
855         {
856           struct block *b = (struct block *) exp;
857
858           len += b->text_len;
859           if (b->arg_index == 0)
860             break;
861           len += NODE_LEN (macro->params[b->arg_index - 1]);
862           exp += BLOCK_LEN (b->text_len);
863         }
864     }
865   else
866     len = macro->count;
867   
868   return len;
869 }
870
871 /* Copy the replacement text of MACRO to DEST, which must be of
872    sufficient size.  It is not NUL-terminated.  The next character is
873    returned.  */
874 uchar *
875 _cpp_copy_replacement_text (macro, dest)
876      const cpp_macro *macro;
877      uchar *dest;
878 {
879   if (macro->fun_like)
880     {
881       const uchar *exp;
882
883       for (exp = macro->exp.text;;)
884         {
885           struct block *b = (struct block *) exp;
886           cpp_hashnode *param;
887
888           memcpy (dest, b->text, b->text_len);
889           dest += b->text_len;
890           if (b->arg_index == 0)
891             break;
892           param = macro->params[b->arg_index - 1];
893           memcpy (dest, NODE_NAME (param), NODE_LEN (param));
894           dest += NODE_LEN (param);
895           exp += BLOCK_LEN (b->text_len);
896         }
897     }
898   else
899     {
900       memcpy (dest, macro->exp.text, macro->count);
901       dest += macro->count;
902     }
903
904   return dest;
905 }
906
907 /* Push a context holding the replacement text of the macro NODE on
908    the context stack.  NODE is either object-like, or a function-like
909    macro with no arguments.  */
910 static void
911 replace_args_and_push (pfile, fmacro)
912      cpp_reader *pfile;
913      struct fun_macro *fmacro;
914 {
915   cpp_macro *macro = fmacro->node->value.macro;
916
917   if (macro->paramc == 0)
918     push_replacement_text (pfile, fmacro->node);
919   else
920     {
921       const uchar *exp;
922       uchar *p;
923       _cpp_buff *buff;
924       size_t len = 0;
925
926       /* Calculate the length of the argument-replaced text.  */
927       for (exp = macro->exp.text;;)
928         {
929           struct block *b = (struct block *) exp;
930
931           len += b->text_len;
932           if (b->arg_index == 0)
933             break;
934           len += (fmacro->args[b->arg_index]
935                   - fmacro->args[b->arg_index - 1] - 1);
936           exp += BLOCK_LEN (b->text_len);
937         }
938
939       /* Allocate room for the expansion plus NUL.  */
940       buff = _cpp_get_buff (pfile, len + 1);
941
942       /* Copy the expansion and replace arguments.  */
943       p = BUFF_FRONT (buff);
944       for (exp = macro->exp.text;;)
945         {
946           struct block *b = (struct block *) exp;
947           size_t arglen;
948
949           memcpy (p, b->text, b->text_len);
950           p += b->text_len;
951           if (b->arg_index == 0)
952             break;
953           arglen = (fmacro->args[b->arg_index]
954                     - fmacro->args[b->arg_index - 1] - 1);
955           memcpy (p, pfile->out.base + fmacro->args[b->arg_index - 1],
956                   arglen);
957           p += arglen;
958           exp += BLOCK_LEN (b->text_len);
959         }
960
961       /* NUL-terminate.  */
962       *p = '\0';
963       _cpp_push_text_context (pfile, fmacro->node, BUFF_FRONT (buff), len);
964
965       /* So we free buffer allocation when macro is left.  */
966       pfile->context->buff = buff;
967     }
968 }
969
970 /* Read and record the parameters, if any, of a function-like macro
971    definition.  Destroys pfile->out.cur.
972
973    Returns true on success, false on failure (syntax error or a
974    duplicate parameter).  On success, CUR (pfile->context) is just
975    past the closing parenthesis.  */
976 static bool
977 scan_parameters (pfile, macro)
978      cpp_reader *pfile;
979      cpp_macro *macro;
980 {
981   const uchar *cur = CUR (pfile->context) + 1;
982   bool ok;
983
984   for (;;)
985     {
986       cur = skip_whitespace (pfile, cur, true /* skip_comments */);
987
988       if (is_idstart (*cur))
989         {
990           ok = false;
991           if (_cpp_save_parameter (pfile, macro, lex_identifier (pfile, cur)))
992             break;
993           cur = skip_whitespace (pfile, CUR (pfile->context),
994                                  true /* skip_comments */);
995           if (*cur == ',')
996             {
997               cur++;
998               continue;
999             }
1000           ok = (*cur == ')');
1001           break;
1002         }
1003
1004       ok = (*cur == ')' && macro->paramc == 0);
1005       break;
1006     }
1007
1008   CUR (pfile->context) = cur + (*cur == ')');
1009
1010   return ok;
1011 }
1012
1013 /* Save the text from pfile->out.base to pfile->out.cur as
1014    the replacement text for the current macro, followed by argument
1015    ARG_INDEX, with zero indicating the end of the replacement
1016    text.  */
1017 static void
1018 save_replacement_text (pfile, macro, arg_index)
1019      cpp_reader *pfile;
1020      cpp_macro *macro;
1021      unsigned int arg_index;
1022 {
1023   size_t len = pfile->out.cur - pfile->out.base;
1024   uchar *exp;
1025
1026   if (macro->paramc == 0)
1027     {
1028       /* Object-like and function-like macros without parameters
1029          simply store their NUL-terminated replacement text.  */
1030       exp = _cpp_unaligned_alloc (pfile, len + 1);
1031       memcpy (exp, pfile->out.base, len);
1032       exp[len] = '\0';
1033       macro->exp.text = exp;
1034       macro->count = len;
1035     }
1036   else
1037     {
1038       /* Store the text's length (unsigned int), the argument index
1039          (unsigned short, base 1) and then the text.  */
1040       size_t blen = BLOCK_LEN (len);
1041       struct block *block;
1042
1043       if (macro->count + blen > BUFF_ROOM (pfile->a_buff))
1044         _cpp_extend_buff (pfile, &pfile->a_buff, macro->count + blen);
1045
1046       exp = BUFF_FRONT (pfile->a_buff);
1047       block = (struct block *) (exp + macro->count);
1048       macro->exp.text = exp;
1049
1050       /* Write out the block information.  */
1051       block->text_len = len;
1052       block->arg_index = arg_index;
1053       memcpy (block->text, pfile->out.base, len);
1054
1055       /* Lex the rest into the start of the output buffer.  */
1056       pfile->out.cur = pfile->out.base;
1057
1058       macro->count += blen;
1059
1060       /* If we've finished, commit the memory.  */
1061       if (arg_index == 0)
1062         BUFF_FRONT (pfile->a_buff) += macro->count;
1063     }
1064 }
1065
1066 /* Analyze and save the replacement text of a macro.  Returns true on
1067    success.  */
1068 bool
1069 _cpp_create_trad_definition (pfile, macro)
1070      cpp_reader *pfile;
1071      cpp_macro *macro;
1072 {
1073   const uchar *cur;
1074   uchar *limit;
1075
1076   CUR (pfile->context) = pfile->buffer->cur;
1077
1078   /* Is this a function-like macro?  */
1079   if (* CUR (pfile->context) == '(')
1080     {
1081       /* Setting macro to NULL indicates an error occurred, and
1082          prevents unnecessary work in scan_out_logical_line.  */
1083       if (!scan_parameters (pfile, macro))
1084         macro = NULL;
1085       else
1086         {
1087           /* Success.  Commit the parameter array.  */
1088           macro->params = (cpp_hashnode **) BUFF_FRONT (pfile->a_buff);
1089           BUFF_FRONT (pfile->a_buff) = (uchar *) &macro->params[macro->paramc];
1090           macro->fun_like = 1;
1091         }
1092     }
1093
1094   /* Skip leading whitespace in the replacement text.  */
1095   CUR (pfile->context)
1096     = skip_whitespace (pfile, CUR (pfile->context),
1097                        CPP_OPTION (pfile, discard_comments_in_macro_exp));
1098
1099   pfile->state.prevent_expansion++;
1100   scan_out_logical_line (pfile, macro);
1101   pfile->state.prevent_expansion--;
1102
1103   if (!macro)
1104     return false;
1105
1106   /* Skip trailing white space.  */
1107   cur = pfile->out.base;
1108   limit = pfile->out.cur;
1109   while (limit > cur && is_space (limit[-1]))
1110     limit--;
1111   pfile->out.cur = limit;
1112   save_replacement_text (pfile, macro, 0);
1113
1114   return true;
1115 }
1116
1117 /* Copy SRC of length LEN to DEST, but convert all contiguous
1118    whitespace to a single space, provided it is not in quotes.  The
1119    quote currently in effect is pointed to by PQUOTE, and is updated
1120    by the function.  Returns the number of bytes copied.  */
1121 static size_t
1122 canonicalize_text (dest, src, len, pquote)
1123      uchar *dest;
1124      const uchar *src;
1125      size_t len;
1126      uchar *pquote;
1127 {
1128   uchar *orig_dest = dest;
1129   uchar quote = *pquote;
1130
1131   while (len)
1132     {
1133       if (is_space (*src) && !quote)
1134         {
1135           do
1136             src++, len--;
1137           while (len && is_space (*src));
1138           *dest++ = ' ';
1139         }
1140       else
1141         {
1142           if (*src == '\'' || *src == '"')
1143             {
1144               if (!quote)
1145                 quote = *src;
1146               else if (quote == *src)
1147                 quote = 0;
1148             }
1149           *dest++ = *src++, len--;
1150         }
1151     }
1152
1153   *pquote = quote;
1154   return dest - orig_dest;
1155 }
1156
1157 /* Returns true if MACRO1 and MACRO2 have expansions different other
1158    than in the form of their whitespace.  */
1159 bool
1160 _cpp_expansions_different_trad (macro1, macro2)
1161      const cpp_macro *macro1, *macro2;
1162 {
1163   uchar *p1 = xmalloc (macro1->count + macro2->count);
1164   uchar *p2 = p1 + macro1->count;
1165   uchar quote1 = 0, quote2 = 0;
1166   bool mismatch;
1167   size_t len1, len2;
1168
1169   if (macro1->paramc > 0)
1170     {
1171       const uchar *exp1 = macro1->exp.text, *exp2 = macro2->exp.text;
1172
1173       mismatch = true;
1174       for (;;)
1175         {
1176           struct block *b1 = (struct block *) exp1;
1177           struct block *b2 = (struct block *) exp2;
1178
1179           if (b1->arg_index != b2->arg_index)
1180             break;
1181
1182           len1 = canonicalize_text (p1, b1->text, b1->text_len, &quote1);
1183           len2 = canonicalize_text (p2, b2->text, b2->text_len, &quote2);
1184           if (len1 != len2 || memcmp (p1, p2, len1))
1185             break;
1186           if (b1->arg_index == 0)
1187             {
1188               mismatch = false;
1189               break;
1190             }
1191           exp1 += BLOCK_LEN (b1->text_len);
1192           exp2 += BLOCK_LEN (b2->text_len);
1193         }
1194     }
1195   else
1196     {
1197       len1 = canonicalize_text (p1, macro1->exp.text, macro1->count, &quote1);
1198       len2 = canonicalize_text (p2, macro2->exp.text, macro2->count, &quote2);
1199       mismatch = (len1 != len2 || memcmp (p1, p2, len1));
1200     }
1201
1202   free (p1);
1203   return mismatch;
1204 }
1205
1206 /* Prepare to be able to scan the current buffer.  */
1207 void
1208 _cpp_set_trad_context (pfile)
1209      cpp_reader *pfile;
1210 {
1211   cpp_buffer *buffer = pfile->buffer;
1212   cpp_context *context = pfile->context;
1213
1214   if (pfile->context->prev)
1215     abort ();
1216
1217   pfile->out.cur = pfile->out.base;
1218   CUR (context) = buffer->cur;
1219   RLIMIT (context) = buffer->rlimit;
1220   check_output_buffer (pfile, RLIMIT (context) - CUR (context));
1221 }