OSDN Git Service

2000-07-31 Jakub Jelinek <jakub@redhat.com>
[pf3gnuchains/gcc-fork.git] / gcc / cppmacro.c
1 /* Part of CPP library.  (Macro handling.)
2    Copyright (C) 1986, 1987, 1989, 1992, 1993, 1994, 1995, 1996, 1998,
3    1999, 2000 Free Software Foundation, Inc.
4    Written by Per Bothner, 1994.
5    Based on CCCP program by Paul Rubin, June 1986
6    Adapted to ANSI C, Richard Stallman, Jan 1987
7
8 This program is free software; you can redistribute it and/or modify it
9 under the terms of the GNU General Public License as published by the
10 Free Software Foundation; either version 2, or (at your option) any
11 later version.
12
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with this program; if not, write to the Free Software
20 Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
21
22  In other words, you are welcome to use, share and improve this program.
23  You are forbidden to forbid anyone else to use, share and improve
24  what you give them.   Help stamp out software-hoarding!  */
25
26 #include "config.h"
27 #include "system.h"
28 #include "cpplib.h"
29 #include "cpphash.h"
30
31 /* Stores basic information about a macro, before it is allocated.  */
32 struct macro_info
33 {
34   const cpp_token *first_param; /* First parameter token.  */
35   const cpp_token *first;       /* First expansion token.  */
36   unsigned int paramlen;        /* Length of parameter names. */
37   unsigned int len;             /* Length of token strings.  */
38   unsigned int ntokens;         /* Number of tokens in expansion.  */
39   short paramc;                 /* Number of parameters.  */
40   unsigned char flags;
41 };
42
43 static void dump_funlike_macro  PARAMS ((cpp_reader *, cpp_hashnode *));
44 static void count_params PARAMS ((cpp_reader *, struct macro_info *));
45 static int is__va_args__ PARAMS ((cpp_reader *, const cpp_token *));
46
47 static int parse_define PARAMS((cpp_reader *, struct macro_info *));
48 static int check_macro_redefinition PARAMS((cpp_reader *, cpp_hashnode *hp,
49                                             const cpp_toklist *));
50 static const cpp_toklist * save_expansion PARAMS((cpp_reader *,
51                                                   struct macro_info *));
52 static unsigned int find_param PARAMS ((const cpp_token *,
53                                         const cpp_token *));
54 static cpp_toklist * alloc_macro PARAMS ((cpp_reader *, struct macro_info *));
55
56 /* These are all the tokens that can have something pasted after them.
57    Comma is included in the list only to support the GNU varargs extension
58    (where you write a ## b and a disappears if b is an empty rest argument).  */
59 #define CAN_PASTE_AFTER(type) \
60 ((type) <= CPP_LAST_EQ || (type) == CPP_COLON || (type) == CPP_HASH \
61  || (type) == CPP_DEREF || (type) == CPP_DOT || (type) == CPP_NAME \
62  || (type) == CPP_INT || (type) == CPP_FLOAT || (type) == CPP_NUMBER \
63  || (type) == CPP_MACRO_ARG || (type) == CPP_PLACEMARKER || (type) == CPP_COMMA)
64
65 /* Scans for a given token, returning the parameter number if found,
66    or 0 if not found.  Scans from FIRST to TOKEN - 1 or the first
67    CPP_CLOSE_PAREN for TOKEN.  */
68 static unsigned int
69 find_param (first, token)
70      const cpp_token *first, *token;
71 {
72   unsigned int param = 0;
73
74   for (; first < token && first->type != CPP_CLOSE_PAREN; first++)
75     if (first->type == CPP_NAME || first->type == CPP_DEFINED)
76       {
77         param++;
78         if (first->val.node == token->val.node)
79           return param;
80       }
81
82   return 0;
83 }
84
85 /* Constraint 6.10.3.5: __VA_ARGS__ should only appear in the
86    replacement list of a variable-arguments macro.  TOKEN is assumed
87    to be of type CPP_NAME.  */
88 static int
89 is__va_args__ (pfile, token)
90      cpp_reader *pfile;
91      const cpp_token *token;
92 {
93   if (!CPP_PEDANTIC (pfile)
94       || token->val.node != pfile->spec_nodes->n__VA_ARGS__)
95     return 0;
96
97   cpp_pedwarn_with_line (pfile, token->line, token->col,
98        "\"%s\" is only valid in the replacement list of a function-like macro",
99                        token->val.node->name);
100   return 1;
101 }
102
103 /* Counts the parameters to a function-like macro, the length of their
104    null-terminated names, and whether the macro is a variable-argument
105    one.  FIRST is the token immediately after the open parenthesis,
106    INFO stores the data.
107
108    On success, info->first is updated to the token after the closing
109    parenthesis, i.e. the first token of the expansion.  Otherwise
110    there was an error, which has been reported.  */
111 static void
112 count_params (pfile, info)
113      cpp_reader *pfile;
114      struct macro_info *info;
115 {
116   unsigned int prev_ident = 0;
117   const cpp_token *token;
118
119   info->paramc = 0;
120   info->paramlen = 0;
121   info->flags = 0;
122   info->first = info->first_param; /* Not a ')' indicating success.  */
123
124   for (token = info->first_param;; token++)
125     {
126       switch (token->type)
127         {
128         default:
129           cpp_error_with_line (pfile, token->line, token->col,
130                                "illegal token in macro parameter list");
131           return;
132
133         case CPP_EOF:
134         missing_paren:
135           cpp_error_with_line (pfile, token->line, token->col,
136                                "missing ')' in macro parameter list");
137           return;
138
139         case CPP_COMMENT:
140           continue;             /* Ignore -C comments.  */
141
142         case CPP_DEFINED:       /* 'defined' may be used as a macro
143                                    parameter name.  */
144         case CPP_NAME:
145           if (prev_ident)
146             {
147               cpp_error_with_line (pfile, token->line, token->col,
148                            "macro parameters must be comma-separated");
149               return;
150             }
151
152           /* Constraint 6.10.3.5  */
153           if (is__va_args__ (pfile, token))
154             return;
155
156           /* Constraint 6.10.3.6 - duplicate parameter names.  */
157           if (find_param (info->first, token))
158             {
159               cpp_error_with_line (pfile, token->line, token->col,
160                                    "duplicate macro parameter \"%s\"",
161                                    token->val.node->name);
162               return;
163             }
164
165           prev_ident = 1;
166           info->paramc++;
167           info->paramlen += token->val.node->length + 1;
168           continue;
169
170         case CPP_CLOSE_PAREN:
171           if (prev_ident || info->paramc == 0)
172             break;
173
174           /* Fall through to pick up the error.  */
175         case CPP_COMMA:
176           if (!prev_ident)
177             {
178               cpp_error_with_line (pfile, token->line, token->col,
179                                    "parameter name expected");
180               return;
181             }
182           prev_ident = 0;
183           continue;
184
185         case CPP_ELLIPSIS:
186           /* Convert ISO-style var_args to named varargs by changing
187              the ellipsis into an identifier with name __VA_ARGS__.
188              This simplifies other handling. */
189           if (!prev_ident)
190             {
191               cpp_token *tok = (cpp_token *) token;
192
193               tok->type = CPP_NAME;
194               tok->val.node = pfile->spec_nodes->n__VA_ARGS__;
195
196               info->paramc++;
197               info->paramlen += tok->val.node->length + 1;
198
199               if (CPP_PEDANTIC (pfile) && ! CPP_OPTION (pfile, c99))
200                 cpp_pedwarn (pfile,
201                              "C89 does not permit anon varargs macros");
202             }
203           else
204             {
205               if (CPP_PEDANTIC (pfile))
206                 cpp_pedwarn (pfile,
207                              "ISO C does not permit named varargs parameters");
208             }
209
210           info->flags |= VAR_ARGS;
211           token++;
212           if (token->type == CPP_CLOSE_PAREN)
213             break;
214           goto missing_paren;
215         }
216
217       /* Success.  */
218       info->first = token + 1;
219       if (!pfile->save_parameter_spellings)
220         info->paramlen = 0;
221       return;
222     }
223 }
224
225 /* Parses a #define directive.  On success, returns zero, and INFO is
226    filled in appropriately.  */
227 static int
228 parse_define (pfile, info)
229      cpp_reader *pfile;
230      struct macro_info *info;
231 {
232   const cpp_token *token;
233   int prev_white = 0;
234
235   /* The first token after the macro's name.  */
236   token = _cpp_get_token (pfile);
237
238   /* Constraint 6.10.3.5  */
239   if (is__va_args__ (pfile, token - 1))
240     return 1;
241
242   while (token->type == CPP_COMMENT)
243     token++, prev_white = 1;
244   prev_white |= token->flags & PREV_WHITE;
245
246   if (token->type == CPP_OPEN_PAREN && !prev_white)
247     {
248       /* A function-like macro.  */
249       info->first_param = token + 1;
250       count_params (pfile, info);
251       if (info->first[-1].type != CPP_CLOSE_PAREN)
252         return 1;
253     }
254   else
255     {
256       /* An object-like macro.  */
257       info->paramc = -1;
258       info->paramlen = 0;
259       info->flags = 0;
260       info->first = token;
261       if (!prev_white && token->type != CPP_EOF)
262         cpp_pedwarn (pfile, "ISO C requires whitespace after the macro name");
263     }
264
265   /* Count tokens in expansion.  We drop paste tokens, and stringize
266      tokens, so don't count them.  */
267   info->ntokens = info->len = 0;
268   for (token = info->first; token->type != CPP_EOF; token++)
269     {
270       if (token->type == CPP_PASTE)
271         {
272           /* Token-paste ##, can appear in both object-like and
273              function-like macros, but not at the ends.  Constraint
274              6.10.3.3.1 */
275           if (token == info->first || token[1].type == CPP_EOF)
276             {
277               cpp_error_with_line (pfile, token->line, token->col,
278                 "'##' cannot appear at either end of a macro expansion");
279               return 1;
280             }
281           continue;
282         }
283       else if (token->type == CPP_HASH)
284         {
285           /* Stringifying #, but a normal character in object-like
286              macros.  Must come before a parameter name.  Constraint
287              6.10.3.2.1.  */
288           if (info->paramc >= 0)
289             {
290               if (token[1].type == CPP_NAME
291                   && find_param (info->first_param, token + 1))
292                 continue;
293               if (! CPP_OPTION (pfile, lang_asm))
294                 {
295                   cpp_error_with_line (pfile, token->line, token->col,
296                                "'#' is not followed by a macro parameter");
297                   return 1;
298                 }
299             }
300         }
301       else if (token->type == CPP_NAME)
302         {
303           /* Constraint 6.10.3.5  */
304           if (!(info->flags & VAR_ARGS) && is__va_args__ (pfile, token))
305             return 1;
306         }
307       info->ntokens++;
308       if (TOKEN_SPELL (token) == SPELL_STRING)
309         info->len += token->val.str.len;
310     }
311   
312   return 0;
313 }
314
315 /* Returns non-zero if a macro redefinition is trivial.  */
316 static int
317 check_macro_redefinition (pfile, hp, list2)
318      cpp_reader *pfile;
319      cpp_hashnode *hp;
320      const cpp_toklist *list2;
321 {
322   const cpp_toklist *list1;
323
324   if (hp->type != T_MACRO)
325     return ! pfile->done_initializing;
326
327   /* Clear the whitespace and BOL flags of the first tokens.  They get
328      altered during macro expansion, but is not significant here.  */
329   list1  = hp->value.expansion;
330   list1->tokens[0].flags &= ~(PREV_WHITE|BOL);
331   list2->tokens[0].flags &= ~(PREV_WHITE|BOL);
332
333   if (!_cpp_equiv_toklists (list1, list2))
334     return 0;
335
336   if (CPP_OPTION (pfile, pedantic)
337       && list1->paramc > 0
338       && (list1->params_len != list2->params_len
339           || memcmp (list1->namebuf, list2->namebuf, list1->params_len)))
340     return 0;
341
342   return 1;
343 }
344
345 /* This is a dummy structure whose only purpose is getting alignment
346    correct.  */
347 struct toklist_dummy
348 {
349   cpp_toklist list;
350   cpp_token first_token;
351 };
352
353 /* Allocate space to hold the token list, its tokens, their text, and
354    the parameter names if needed.  Empty expansions are stored as a
355    single placemarker token.
356
357    These are all allocated in a block together for performance
358    reasons.  Therefore, this token list cannot be expanded like a
359    normal token list.  Try to do so, and you lose.  */
360 static cpp_toklist *
361 alloc_macro (pfile, info)
362      cpp_reader *pfile;
363      struct macro_info *info;
364 {
365   unsigned int size;
366   struct toklist_dummy *dummy;
367   cpp_toklist *list;
368
369   /* Empty macros become a single placemarker token.  */
370   if (info->ntokens == 0)
371     info->ntokens = 1;
372
373   size = sizeof (struct toklist_dummy);
374   size += (info->ntokens - 1) * sizeof(cpp_token);
375   size += info->len + info->paramlen;
376
377   dummy = (struct toklist_dummy *) xmalloc (size);
378   list = (cpp_toklist *) dummy;
379   
380   /* Initialize the monster.  */
381   list->tokens = &dummy->first_token;
382   list->tokens_used = list->tokens_cap = info->ntokens;
383
384   list->namebuf = (unsigned char *) &list->tokens[info->ntokens];
385   list->name_used = list->name_cap = info->len + info->paramlen;
386
387   list->directive = 0;
388   list->line = pfile->token_list.line;
389   list->file = pfile->token_list.file;
390   list->params_len = info->paramlen;
391   list->paramc = info->paramc;
392   list->flags = info->flags;
393
394   return list;
395 }
396
397 /* Free the definition of macro H.  */
398
399 void
400 _cpp_free_definition (h)
401      cpp_hashnode *h;
402 {
403   if (h->type == T_MACRO)
404     free ((PTR) h->value.expansion);
405   h->value.expansion = NULL;
406 }
407
408 /* Copy the tokens of the expansion, beginning with info->first until
409    CPP_EOF.  INFO contains information about the macro.
410
411    Change the type of macro arguments in the expansion from CPP_NAME
412    to CPP_MACRO_ARG.  Remove #'s that represent stringification,
413    flagging the CPP_MACRO_ARG it operates on STRINGIFY.  Remove ##'s,
414    flagging the token on its immediate left PASTE_LEFT.  Returns the
415    token list for the macro expansion.  */
416 static const cpp_toklist *
417 save_expansion (pfile, info)
418      cpp_reader *pfile;
419      struct macro_info *info;
420 {
421   const cpp_token *token;
422   cpp_toklist *list;
423   cpp_token *dest;
424   unsigned char *buf;
425       
426   list = alloc_macro (pfile, info);
427   buf = list->namebuf;
428
429   /* Store the null-terminated parameter spellings of a macro, to
430      provide pedantic warnings to satisfy 6.10.3.2, or for use when
431      dumping macro definitions.  They must go first.  */
432   if (list->params_len)
433     for (token = info->first_param; token < info->first; token++)
434       if (token->type == CPP_NAME || token->type == CPP_DEFINED)
435         {
436           /* Copy null too.  */
437           memcpy (buf, token->val.node->name, token->val.node->length + 1);
438           buf += token->val.node->length + 1;
439         }
440
441   dest = list->tokens;
442   for (token = info->first; token->type != CPP_EOF; token++)
443     {
444       unsigned int param_no;
445
446       switch (token->type)
447         {
448         case CPP_DEFINED:
449         case CPP_NAME:
450           if (list->paramc == -1)
451             break;
452
453           /* Check if the name is a macro parameter.  */
454           param_no = find_param (info->first_param, token);
455           if (param_no == 0)
456             break;
457           dest->val.aux = param_no - 1;
458
459           dest->type = CPP_MACRO_ARG;
460           if (token[-1].type == CPP_HASH)
461             dest->flags = token[-1].flags | STRINGIFY_ARG;
462           else
463             dest->flags = token->flags;  /* Particularly PREV_WHITE.  */
464           /* Turn off PREV_WHITE if we immediately follow a paste.
465              That way, even if the paste turns out to be illegal, there
466              will be no space between the two tokens in the output.  */
467           if (token[-1].type == CPP_PASTE)
468             dest->flags &= ~PREV_WHITE;
469           dest++;
470           continue;
471
472         case CPP_PASTE:
473           /* Set the paste flag on the token to our left, unless there
474              is no possible token to which it might be pasted.  That
475              is critical for correct operation under some circumstances;
476              see gcc.dg/cpp/paste6.c. */
477           if (CAN_PASTE_AFTER (dest[-1].type) || (dest[-1].flags & NAMED_OP))
478             dest[-1].flags |= PASTE_LEFT;
479           else if (CPP_OPTION (pfile, warn_paste))
480             cpp_warning_with_line (pfile, dest[-1].line, dest[-1].col,
481                                    "nothing can be pasted after this token");
482           continue;
483
484         case CPP_HASH:
485           /* Stringifying #.  Constraint 6.10.3.2.1  */
486           if (list->paramc >= 0 && token[1].type == CPP_NAME
487               && find_param (info->first_param, token + 1))
488             continue;
489           break;
490
491         default:
492           break;
493         }
494
495       /* Copy the token.  */
496       *dest = *token;
497       if (TOKEN_SPELL (token) == SPELL_STRING)
498         {
499           memcpy (buf, token->val.str.text, token->val.str.len);
500           dest->val.str.text = buf;
501           buf += dest->val.str.len;
502         }
503       if (token[-1].type == CPP_PASTE)
504         dest->flags &= ~PREV_WHITE;
505       dest++;
506     }
507
508   /* Empty macros become a single placemarker token.  */
509   if (dest == list->tokens)
510     {
511       dest->type = CPP_PLACEMARKER;
512       dest->flags = 0;
513       dest->val.aux = 0;
514     }
515
516   return list;
517 }
518
519 /* Parse a macro and save its expansion.  Returns non-zero on success.  */
520 int
521 _cpp_create_definition (pfile, hp)
522      cpp_reader *pfile;
523      cpp_hashnode *hp;
524 {
525   struct macro_info info;
526   const cpp_toklist *list;
527
528   if (parse_define (pfile, &info))
529     return 0;
530   list = save_expansion (pfile, &info);
531
532   /* Check for a redefinition.  Redefinition of a macro is allowed if
533      and only if the old and new definitions are the same.
534      (6.10.3 paragraph 2). */
535
536   if (hp->type != T_VOID)
537     {
538       if (!check_macro_redefinition (pfile, hp, list))
539         {
540           cpp_pedwarn (pfile, "\"%s\" redefined", hp->name);
541           if (pfile->done_initializing && hp->type == T_MACRO)
542             cpp_pedwarn_with_file_and_line (pfile,
543                                             hp->value.expansion->file,
544                                             hp->value.expansion->line, 1,
545                             "this is the location of the previous definition");
546         }
547       _cpp_free_definition (hp);
548     }
549
550   /* Enter definition in hash table.  */
551   hp->type = T_MACRO;
552   hp->value.expansion = list;
553
554   return 1;
555 }
556
557 /* Dump the definition of macro MACRO on stdout.  The format is suitable
558    to be read back in again. */
559
560 void
561 _cpp_dump_definition (pfile, hp)
562      cpp_reader *pfile;
563      cpp_hashnode *hp;
564 {
565   CPP_RESERVE (pfile, hp->length + sizeof "#define ");
566   CPP_PUTS_Q (pfile, "#define ", sizeof "#define " - 1);
567   CPP_PUTS_Q (pfile, hp->name, hp->length);
568
569   if (hp->type == T_MACRO)
570     {
571       if (hp->value.expansion->paramc >= 0)
572         dump_funlike_macro (pfile, hp);
573       else
574         {
575           const cpp_toklist *list = hp->value.expansion;
576           list->tokens[0].flags &= ~BOL;
577           list->tokens[0].flags |= PREV_WHITE;
578           _cpp_dump_list (pfile, list, list->tokens, 1);
579         }
580     }
581   else
582     cpp_ice (pfile, "invalid hash type %d in dump_definition", hp->type);
583
584   if (CPP_BUFFER (pfile) == 0 || ! pfile->done_initializing)
585     CPP_PUTC (pfile, '\n');
586 }
587
588 static void
589 dump_funlike_macro (pfile, node)
590      cpp_reader *pfile;
591      cpp_hashnode *node;
592 {
593   int i = 0;
594   const cpp_toklist * list = node->value.expansion;
595   const U_CHAR *param;
596
597   param = list->namebuf;
598   CPP_PUTC_Q (pfile, '(');
599   for (i = 0; i++ < list->paramc;)
600     {
601       unsigned int len;
602
603       len = ustrlen (param);
604       CPP_PUTS (pfile, param, len);
605       if (i < list->paramc)
606         CPP_PUTS(pfile, ", ", 2);
607       else if (list->flags & VAR_ARGS)
608         {
609           if (!ustrcmp (param, U"__VA_ARGS__"))
610             pfile->limit -= sizeof (U"__VA_ARGS__") - 1;
611           CPP_PUTS_Q (pfile, "...", 3);
612         }
613       param += len + 1;
614     }
615   CPP_PUTC (pfile, ')');
616   list->tokens[0].flags &= ~BOL;
617   list->tokens[0].flags |= PREV_WHITE;
618   _cpp_dump_list (pfile, list, list->tokens, 1);
619 }