OSDN Git Service

* cpphash.h (_cpp_set_trad_context): Remove.
[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.
27
28    Each block comprises the text between its surrounding parameters,
29    the length of that text, and the one-based index of the following
30    parameter.  The final block in the replacement text is easily
31    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 current context, not necessarily
143    a backslash.  Advances CUR until all escaped newlines are skipped,
144    and returns the new position without updating the context.
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 current
164    context.  IN_DEFINE is true if we are in the replacement text of a
165    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   do
368     {
369       if (pfile->buffer->cur == pfile->buffer->rlimit)
370         {
371           bool stop = true;
372
373           /* Don't pop the last buffer.  */
374           if (pfile->buffer->prev)
375             {
376               stop = pfile->buffer->return_at_eof;
377               _cpp_pop_buffer (pfile);
378             }
379
380           if (stop)
381             return false;
382         }
383
384       scan_out_logical_line (pfile, NULL);
385     }
386   while (pfile->state.skipping);
387
388   return true;
389 }
390
391 /* Set up state for finding the opening '(' of a function-like
392    macro.  */
393 static void
394 maybe_start_funlike (pfile, node, start, macro)
395      cpp_reader *pfile;
396      cpp_hashnode *node;
397      const uchar *start;
398      struct fun_macro *macro;
399 {
400   unsigned int n = node->value.macro->paramc + 1;
401
402   if (macro->buff)
403     _cpp_release_buff (pfile, macro->buff);
404   macro->buff = _cpp_get_buff (pfile, n * sizeof (size_t));
405   macro->args = (size_t *) BUFF_FRONT (macro->buff);
406   macro->node = node;
407   macro->offset = start - pfile->out.base;
408   macro->argc = 0;
409 }
410
411 /* Save the OFFSET of the start of the next argument to MACRO.  */
412 static void
413 save_argument (macro, offset)
414      struct fun_macro *macro;
415      size_t offset;
416 {
417   macro->argc++;
418   if (macro->argc <= macro->node->value.macro->paramc)
419     macro->args[macro->argc] = offset;
420 }
421
422 /* Copies the next logical line in the current buffer (starting at
423    buffer->cur) to the output buffer.  The output is guaranteed to
424    terminate with a NUL character.  buffer->cur is updated.
425
426    If MACRO is non-NULL, then we are scanning the replacement list of
427    MACRO, and we call save_replacement_text() every time we meet an
428    argument.  */
429 static void
430 scan_out_logical_line (pfile, macro)
431      cpp_reader *pfile;
432      cpp_macro *macro;
433 {
434   cpp_context *context;
435   const uchar *cur;
436   uchar *out;
437   struct fun_macro fmacro;
438   unsigned int c, paren_depth = 0, quote = 0;
439   enum ls lex_state = ls_none;
440
441   fmacro.buff = NULL;
442
443  start_logical_line:
444   CUR (pfile->context) = pfile->buffer->cur;
445   RLIMIT (pfile->context) = pfile->buffer->rlimit;
446   pfile->out.cur = pfile->out.base;
447   pfile->out.first_line = pfile->line;
448  new_context:
449   context = pfile->context;
450   cur = CUR (context);
451   check_output_buffer (pfile, RLIMIT (context) - cur);
452   out = pfile->out.cur;
453
454   for (;;)
455     {
456       c = *cur++;
457       *out++ = c;
458
459       /* Whitespace should "continue" out of the switch,
460          non-whitespace should "break" out of it.  */
461       switch (c)
462         {
463         case ' ':
464         case '\t':
465         case '\f':
466         case '\v':
467           continue;
468
469         case '\0':
470           if (cur - 1 != RLIMIT (context))
471             continue;
472
473           /* If this is a macro's expansion, pop it.  */
474           if (context->prev)
475             {
476               pfile->out.cur = out - 1;
477               _cpp_pop_context (pfile);
478               goto new_context;
479             }
480
481           /* Premature end of file.  Fake a new line.  */
482           cur--;
483           if (!pfile->buffer->from_stage3)
484             cpp_error (pfile, DL_PEDWARN, "no newline at end of file");
485           pfile->line++;
486           goto done;
487
488         case '\r': case '\n':
489           cur = handle_newline (pfile, cur - 1);
490           if ((lex_state == ls_fun_open || lex_state == ls_fun_close)
491               && !pfile->state.in_directive)
492             {
493               /* Newlines in arguments become a space.  */
494               if (lex_state == ls_fun_close)
495                 out[-1] = ' ';
496               continue;
497             }
498           goto done;
499
500         case '<':
501           if (pfile->state.angled_headers && !quote)
502             quote = '>';
503           break;
504         case '>':
505           if (pfile->state.angled_headers && c == quote)
506             {
507               pfile->state.angled_headers = false;
508               quote = 0;
509             }
510           break;
511
512         case '"':
513         case '\'':
514           if (c == quote)
515             quote = 0;
516           else if (!quote)
517             quote = c;
518           break;
519
520         case '\\':
521           if (is_vspace (*cur))
522             {
523               out--;
524               cur = skip_escaped_newlines (pfile, cur - 1);
525               continue;
526             }
527           else
528             {
529               /* Skip escaped quotes here, it's easier than above, but
530                  take care to first skip escaped newlines.  */
531               cur = skip_escaped_newlines (pfile, cur);
532               if (*cur == '\\' || *cur == '"' || *cur == '\'')
533                 *out++ = *cur++;
534             }
535           break;
536
537         case '/':
538           /* Traditional CPP does not recognize comments within
539              literals.  */
540           if (!quote)
541             {
542               cur = skip_escaped_newlines (pfile, cur);
543               if (*cur == '*')
544                 {
545                   pfile->out.cur = out;
546                   cur = copy_comment (pfile, cur, macro != 0);
547                   out = pfile->out.cur;
548                   continue;
549                 }
550             }
551           break;
552
553         case '_':
554         case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
555         case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
556         case 'm': case 'n': case 'o': case 'p': case 'q': case 'r':
557         case 's': case 't': case 'u': case 'v': case 'w': case 'x':
558         case 'y': case 'z':
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           if (!pfile->state.skipping && (quote == 0 || macro))
565             {
566               cpp_hashnode *node;
567               uchar *out_start = out - 1;
568
569               pfile->out.cur = out_start;
570               node = lex_identifier (pfile, cur - 1);
571               out = pfile->out.cur;
572               cur = CUR (context);
573
574               if (node->type == NT_MACRO
575                   /* Should we expand for ls_answer?  */
576                   && (lex_state == ls_none || lex_state == ls_fun_open)
577                   && !pfile->state.prevent_expansion)
578                 {
579                   /* Macros invalidate MI optimization.  */
580                   pfile->mi_valid = false;
581                   if (! (node->flags & NODE_BUILTIN)
582                       && node->value.macro->fun_like)
583                     {
584                       maybe_start_funlike (pfile, node, out_start, &fmacro);
585                       lex_state = ls_fun_open;
586                       fmacro.line = pfile->line;
587                       continue;
588                     }
589                   else if (!recursive_macro (pfile, node))
590                     {
591                       /* Remove the object-like macro's name from the
592                          output, and push its replacement text.  */
593                       pfile->out.cur = out_start;
594                       push_replacement_text (pfile, node);
595                       lex_state = ls_none;
596                       goto new_context;
597                     }
598                 }
599               else if (macro && node->arg_index)
600                 {
601                   /* Found a parameter in the replacement text of a
602                      #define.  Remove its name from the output.  */
603                   pfile->out.cur = out_start;
604                   save_replacement_text (pfile, macro, node->arg_index);
605                   out = pfile->out.base;
606                 }
607               else if (lex_state == ls_hash)
608                 {
609                   lex_state = ls_predicate;
610                   continue;
611                 }
612               else if (pfile->state.in_expression
613                        && node == pfile->spec_nodes.n_defined)
614                 {
615                   lex_state = ls_defined;
616                   continue;
617                 }
618             }
619           break;
620
621         case '(':
622           if (quote == 0)
623             {
624               paren_depth++;
625               if (lex_state == ls_fun_open)
626                 {
627                   if (recursive_macro (pfile, fmacro.node))
628                     lex_state = ls_none;
629                   else
630                     {
631                       lex_state = ls_fun_close;
632                       paren_depth = 1;
633                       out = pfile->out.base + fmacro.offset;
634                       fmacro.args[0] = fmacro.offset;
635                     }
636                 }
637               else if (lex_state == ls_predicate)
638                 lex_state = ls_answer;
639               else if (lex_state == ls_defined)
640                 lex_state = ls_defined_close;
641             }
642           break;
643
644         case ',':
645           if (quote == 0 && lex_state == ls_fun_close && paren_depth == 1)
646             save_argument (&fmacro, out - pfile->out.base);
647           break;
648
649         case ')':
650           if (quote == 0)
651             {
652               paren_depth--;
653               if (lex_state == ls_fun_close && paren_depth == 0)
654                 {
655                   cpp_macro *m = fmacro.node->value.macro;
656
657                   lex_state = ls_none;
658                   save_argument (&fmacro, out - pfile->out.base);
659
660                   /* A single zero-length argument is no argument.  */
661                   if (fmacro.argc == 1
662                       && m->paramc == 0
663                       && out == pfile->out.base + fmacro.offset + 1)
664                     fmacro.argc = 0;
665
666                   if (_cpp_arguments_ok (pfile, m, fmacro.node, fmacro.argc))
667                     {
668                       /* Remove the macro's invocation from the
669                          output, and push its replacement text.  */
670                       pfile->out.cur = (pfile->out.base
671                                              + fmacro.offset);
672                       CUR (context) = cur;
673                       replace_args_and_push (pfile, &fmacro);
674                       goto new_context;
675                     }
676                 }
677               else if (lex_state == ls_answer || lex_state == ls_defined_close)
678                 lex_state = ls_none;
679             }
680           break;
681
682         case '#':
683           if (out - 1 == pfile->out.base && !pfile->state.in_directive)
684             {
685               /* A directive.  With the way _cpp_handle_directive
686                  currently works, we only want to call it if either we
687                  know the directive is OK, or we want it to fail and
688                  be removed from the output.  If we want it to be
689                  passed through (the assembler case) then we must not
690                  call _cpp_handle_directive.  */
691               pfile->out.cur = out;
692               cur = skip_whitespace (pfile, cur, true /* skip_comments */);
693               out = pfile->out.cur;
694
695               if (is_vspace (*cur))
696                 {
697                   /* Null directive.  Ignore it and don't invalidate
698                      the MI optimization.  */
699                   out = pfile->out.base;
700                   continue;
701                 }
702               else
703                 {
704                   bool do_it = false;
705
706                   if (is_numstart (*cur))
707                     do_it = true;
708                   else if (is_idstart (*cur))
709                     /* Check whether we know this directive, but don't
710                        advance.  */
711                     do_it = lex_identifier (pfile, cur)->directive_index != 0;
712
713                   if (do_it || CPP_OPTION (pfile, lang) != CLK_ASM)
714                     {
715                       /* This is a kludge.  We want to have the ISO
716                          preprocessor lex the next token.  */
717                       pfile->buffer->cur = cur;
718                       _cpp_handle_directive (pfile, false /* indented */);
719                       /* #include changes pfile->buffer so we need to
720                          update the limits of the current context.  */
721                       goto start_logical_line;
722                     }
723                 }
724             }
725
726           if (pfile->state.in_expression)
727             {
728               lex_state = ls_hash;
729               continue;
730             }
731           break;
732
733         default:
734           break;
735         }
736
737       /* Non-whitespace disables MI optimization.  */
738       if (!pfile->state.in_directive)
739         pfile->mi_valid = false;
740
741       if (lex_state == ls_none)
742         continue;
743
744       /* Some of these transitions of state are syntax errors.  The
745          ISO preprocessor will issue errors later.  */
746       if (lex_state == ls_fun_open)
747         /* Missing '('.  */
748         lex_state = ls_none;
749       else if (lex_state == ls_hash
750                || lex_state == ls_predicate
751                || lex_state == ls_defined)
752         lex_state = ls_none;
753
754       /* ls_answer and ls_defined_close keep going until ')'.  */
755     }
756
757  done:
758   out[-1] = '\0';
759   pfile->buffer->cur = cur;
760   pfile->out.cur = out - 1;
761   if (fmacro.buff)
762     _cpp_release_buff (pfile, fmacro.buff);
763
764   if (lex_state == ls_fun_close)
765     cpp_error_with_line (pfile, DL_ERROR, fmacro.line, 0,
766                          "unterminated argument list invoking macro \"%s\"",
767                          NODE_NAME (fmacro.node));
768 }
769
770 /* Push a context holding the replacement text of the macro NODE on
771    the context stack.  NODE is either object-like, or a function-like
772    macro with no arguments.  */
773 static void
774 push_replacement_text (pfile, node)
775      cpp_reader *pfile;
776      cpp_hashnode *node;
777 {
778   size_t len;
779   const uchar *text;
780
781   if (node->flags & NODE_BUILTIN)
782     {
783       text = _cpp_builtin_macro_text (pfile, node);
784       len = ustrlen (text);
785     }
786   else
787     {
788       cpp_macro *macro = node->value.macro;
789       text = macro->exp.text;
790       len = macro->count;
791     }
792
793   _cpp_push_text_context (pfile, node, text, len);
794 }
795
796 /* Returns TRUE if traditional macro recursion is detected.  */
797 static bool
798 recursive_macro (pfile, node)
799      cpp_reader *pfile;
800      cpp_hashnode *node;
801 {
802   bool recursing = node->flags & NODE_DISABLED;
803
804   /* Object-like macros that are already expanding are necessarily
805      recursive.
806
807      However, it is possible to have traditional function-like macros
808      that are not infinitely recursive but recurse to any given depth.
809      Further, it is easy to construct examples that get ever longer
810      until the point they stop recursing.  So there is no easy way to
811      detect true recursion; instead we assume any expansion more than
812      20 deep since the first invocation of this macro must be
813      recursing.  */
814   if (recursing && node->value.macro->fun_like)
815     {
816       size_t depth = 0;
817       cpp_context *context = pfile->context;
818
819       do
820         {
821           depth++;
822           if (context->macro == node && depth > 20)
823             break;
824           context = context->prev;
825         }
826       while (context);
827       recursing = context != NULL;
828     }
829
830   if (recursing)
831     cpp_error (pfile, DL_ERROR,
832                "detected recursion whilst expanding macro \"%s\"",
833                NODE_NAME (node));
834
835   return recursing;
836 }
837
838 /* Return the length of the replacement text of a function-like or
839    object-like non-builtin macro.  */
840 size_t
841 _cpp_replacement_text_len (macro)
842      const cpp_macro *macro;
843 {
844   size_t len;
845
846   if (macro->fun_like)
847     {
848       const uchar *exp;
849
850       len = 0;
851       for (exp = macro->exp.text;;)
852         {
853           struct block *b = (struct block *) exp;
854
855           len += b->text_len;
856           if (b->arg_index == 0)
857             break;
858           len += NODE_LEN (macro->params[b->arg_index - 1]);
859           exp += BLOCK_LEN (b->text_len);
860         }
861     }
862   else
863     len = macro->count;
864   
865   return len;
866 }
867
868 /* Copy the replacement text of MACRO to DEST, which must be of
869    sufficient size.  It is not NUL-terminated.  The next character is
870    returned.  */
871 uchar *
872 _cpp_copy_replacement_text (macro, dest)
873      const cpp_macro *macro;
874      uchar *dest;
875 {
876   if (macro->fun_like)
877     {
878       const uchar *exp;
879
880       for (exp = macro->exp.text;;)
881         {
882           struct block *b = (struct block *) exp;
883           cpp_hashnode *param;
884
885           memcpy (dest, b->text, b->text_len);
886           dest += b->text_len;
887           if (b->arg_index == 0)
888             break;
889           param = macro->params[b->arg_index - 1];
890           memcpy (dest, NODE_NAME (param), NODE_LEN (param));
891           dest += NODE_LEN (param);
892           exp += BLOCK_LEN (b->text_len);
893         }
894     }
895   else
896     {
897       memcpy (dest, macro->exp.text, macro->count);
898       dest += macro->count;
899     }
900
901   return dest;
902 }
903
904 /* Push a context holding the replacement text of the macro NODE on
905    the context stack.  NODE is either object-like, or a function-like
906    macro with no arguments.  */
907 static void
908 replace_args_and_push (pfile, fmacro)
909      cpp_reader *pfile;
910      struct fun_macro *fmacro;
911 {
912   cpp_macro *macro = fmacro->node->value.macro;
913
914   if (macro->paramc == 0)
915     push_replacement_text (pfile, fmacro->node);
916   else
917     {
918       const uchar *exp;
919       uchar *p;
920       _cpp_buff *buff;
921       size_t len = 0;
922
923       /* Calculate the length of the argument-replaced text.  */
924       for (exp = macro->exp.text;;)
925         {
926           struct block *b = (struct block *) exp;
927
928           len += b->text_len;
929           if (b->arg_index == 0)
930             break;
931           len += (fmacro->args[b->arg_index]
932                   - fmacro->args[b->arg_index - 1] - 1);
933           exp += BLOCK_LEN (b->text_len);
934         }
935
936       /* Allocate room for the expansion plus NUL.  */
937       buff = _cpp_get_buff (pfile, len + 1);
938
939       /* Copy the expansion and replace arguments.  */
940       p = BUFF_FRONT (buff);
941       for (exp = macro->exp.text;;)
942         {
943           struct block *b = (struct block *) exp;
944           size_t arglen;
945
946           memcpy (p, b->text, b->text_len);
947           p += b->text_len;
948           if (b->arg_index == 0)
949             break;
950           arglen = (fmacro->args[b->arg_index]
951                     - fmacro->args[b->arg_index - 1] - 1);
952           memcpy (p, pfile->out.base + fmacro->args[b->arg_index - 1],
953                   arglen);
954           p += arglen;
955           exp += BLOCK_LEN (b->text_len);
956         }
957
958       /* NUL-terminate.  */
959       *p = '\0';
960       _cpp_push_text_context (pfile, fmacro->node, BUFF_FRONT (buff), len);
961
962       /* So we free buffer allocation when macro is left.  */
963       pfile->context->buff = buff;
964     }
965 }
966
967 /* Read and record the parameters, if any, of a function-like macro
968    definition.  Destroys pfile->out.cur.
969
970    Returns true on success, false on failure (syntax error or a
971    duplicate parameter).  On success, CUR (pfile->context) is just
972    past the closing parenthesis.  */
973 static bool
974 scan_parameters (pfile, macro)
975      cpp_reader *pfile;
976      cpp_macro *macro;
977 {
978   const uchar *cur = CUR (pfile->context) + 1;
979   bool ok;
980
981   for (;;)
982     {
983       cur = skip_whitespace (pfile, cur, true /* skip_comments */);
984
985       if (is_idstart (*cur))
986         {
987           ok = false;
988           if (_cpp_save_parameter (pfile, macro, lex_identifier (pfile, cur)))
989             break;
990           cur = skip_whitespace (pfile, CUR (pfile->context),
991                                  true /* skip_comments */);
992           if (*cur == ',')
993             {
994               cur++;
995               continue;
996             }
997           ok = (*cur == ')');
998           break;
999         }
1000
1001       ok = (*cur == ')' && macro->paramc == 0);
1002       break;
1003     }
1004
1005   CUR (pfile->context) = cur + (*cur == ')');
1006
1007   return ok;
1008 }
1009
1010 /* Save the text from pfile->out.base to pfile->out.cur as
1011    the replacement text for the current macro, followed by argument
1012    ARG_INDEX, with zero indicating the end of the replacement
1013    text.  */
1014 static void
1015 save_replacement_text (pfile, macro, arg_index)
1016      cpp_reader *pfile;
1017      cpp_macro *macro;
1018      unsigned int arg_index;
1019 {
1020   size_t len = pfile->out.cur - pfile->out.base;
1021   uchar *exp;
1022
1023   if (macro->paramc == 0)
1024     {
1025       /* Object-like and function-like macros without parameters
1026          simply store their NUL-terminated replacement text.  */
1027       exp = _cpp_unaligned_alloc (pfile, len + 1);
1028       memcpy (exp, pfile->out.base, len);
1029       exp[len] = '\0';
1030       macro->exp.text = exp;
1031       macro->count = len;
1032     }
1033   else
1034     {
1035       /* Store the text's length (unsigned int), the argument index
1036          (unsigned short, base 1) and then the text.  */
1037       size_t blen = BLOCK_LEN (len);
1038       struct block *block;
1039
1040       if (macro->count + blen > BUFF_ROOM (pfile->a_buff))
1041         _cpp_extend_buff (pfile, &pfile->a_buff, macro->count + blen);
1042
1043       exp = BUFF_FRONT (pfile->a_buff);
1044       block = (struct block *) (exp + macro->count);
1045       macro->exp.text = exp;
1046
1047       /* Write out the block information.  */
1048       block->text_len = len;
1049       block->arg_index = arg_index;
1050       memcpy (block->text, pfile->out.base, len);
1051
1052       /* Lex the rest into the start of the output buffer.  */
1053       pfile->out.cur = pfile->out.base;
1054
1055       macro->count += blen;
1056
1057       /* If we've finished, commit the memory.  */
1058       if (arg_index == 0)
1059         BUFF_FRONT (pfile->a_buff) += macro->count;
1060     }
1061 }
1062
1063 /* Analyze and save the replacement text of a macro.  Returns true on
1064    success.  */
1065 bool
1066 _cpp_create_trad_definition (pfile, macro)
1067      cpp_reader *pfile;
1068      cpp_macro *macro;
1069 {
1070   const uchar *cur;
1071   uchar *limit;
1072   cpp_context *context = pfile->context;
1073
1074   /* The context has not been set up for command line defines, and CUR
1075      has not been updated for the macro name for in-file defines.  */
1076   pfile->out.cur = pfile->out.base;
1077   CUR (context) = pfile->buffer->cur;
1078   RLIMIT (context) = pfile->buffer->rlimit;
1079   check_output_buffer (pfile, RLIMIT (context) - CUR (context));
1080
1081   /* Is this a function-like macro?  */
1082   if (* CUR (context) == '(')
1083     {
1084       /* Setting macro to NULL indicates an error occurred, and
1085          prevents unnecessary work in scan_out_logical_line.  */
1086       if (!scan_parameters (pfile, macro))
1087         macro = NULL;
1088       else
1089         {
1090           /* Success.  Commit the parameter array.  */
1091           macro->params = (cpp_hashnode **) BUFF_FRONT (pfile->a_buff);
1092           BUFF_FRONT (pfile->a_buff) = (uchar *) &macro->params[macro->paramc];
1093           macro->fun_like = 1;
1094         }
1095     }
1096
1097   /* Skip leading whitespace in the replacement text.  */
1098   pfile->buffer->cur
1099     = skip_whitespace (pfile, CUR (context),
1100                        CPP_OPTION (pfile, discard_comments_in_macro_exp));
1101
1102   pfile->state.prevent_expansion++;
1103   scan_out_logical_line (pfile, macro);
1104   pfile->state.prevent_expansion--;
1105
1106   if (!macro)
1107     return false;
1108
1109   /* Skip trailing white space.  */
1110   cur = pfile->out.base;
1111   limit = pfile->out.cur;
1112   while (limit > cur && is_space (limit[-1]))
1113     limit--;
1114   pfile->out.cur = limit;
1115   save_replacement_text (pfile, macro, 0);
1116
1117   return true;
1118 }
1119
1120 /* Copy SRC of length LEN to DEST, but convert all contiguous
1121    whitespace to a single space, provided it is not in quotes.  The
1122    quote currently in effect is pointed to by PQUOTE, and is updated
1123    by the function.  Returns the number of bytes copied.  */
1124 static size_t
1125 canonicalize_text (dest, src, len, pquote)
1126      uchar *dest;
1127      const uchar *src;
1128      size_t len;
1129      uchar *pquote;
1130 {
1131   uchar *orig_dest = dest;
1132   uchar quote = *pquote;
1133
1134   while (len)
1135     {
1136       if (is_space (*src) && !quote)
1137         {
1138           do
1139             src++, len--;
1140           while (len && is_space (*src));
1141           *dest++ = ' ';
1142         }
1143       else
1144         {
1145           if (*src == '\'' || *src == '"')
1146             {
1147               if (!quote)
1148                 quote = *src;
1149               else if (quote == *src)
1150                 quote = 0;
1151             }
1152           *dest++ = *src++, len--;
1153         }
1154     }
1155
1156   *pquote = quote;
1157   return dest - orig_dest;
1158 }
1159
1160 /* Returns true if MACRO1 and MACRO2 have expansions different other
1161    than in the form of their whitespace.  */
1162 bool
1163 _cpp_expansions_different_trad (macro1, macro2)
1164      const cpp_macro *macro1, *macro2;
1165 {
1166   uchar *p1 = xmalloc (macro1->count + macro2->count);
1167   uchar *p2 = p1 + macro1->count;
1168   uchar quote1 = 0, quote2 = 0;
1169   bool mismatch;
1170   size_t len1, len2;
1171
1172   if (macro1->paramc > 0)
1173     {
1174       const uchar *exp1 = macro1->exp.text, *exp2 = macro2->exp.text;
1175
1176       mismatch = true;
1177       for (;;)
1178         {
1179           struct block *b1 = (struct block *) exp1;
1180           struct block *b2 = (struct block *) exp2;
1181
1182           if (b1->arg_index != b2->arg_index)
1183             break;
1184
1185           len1 = canonicalize_text (p1, b1->text, b1->text_len, &quote1);
1186           len2 = canonicalize_text (p2, b2->text, b2->text_len, &quote2);
1187           if (len1 != len2 || memcmp (p1, p2, len1))
1188             break;
1189           if (b1->arg_index == 0)
1190             {
1191               mismatch = false;
1192               break;
1193             }
1194           exp1 += BLOCK_LEN (b1->text_len);
1195           exp2 += BLOCK_LEN (b2->text_len);
1196         }
1197     }
1198   else
1199     {
1200       len1 = canonicalize_text (p1, macro1->exp.text, macro1->count, &quote1);
1201       len2 = canonicalize_text (p2, macro2->exp.text, macro2->count, &quote2);
1202       mismatch = (len1 != len2 || memcmp (p1, p2, len1));
1203     }
1204
1205   free (p1);
1206   return mismatch;
1207 }