OSDN Git Service

* machmode.def: Add BImode. Add a column for bitsize.
[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_macro_args PARAMS ((FILE *, const cpp_toklist *));
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 static void check_trad_stringification PARAMS ((cpp_reader *,
56                                                 const struct macro_info *,
57                                                 const cpp_string *));
58
59 /* These are all the tokens that can have something pasted after them.
60    Comma is included in the list only to support the GNU varargs extension
61    (where you write a ## b and a disappears if b is an empty rest argument).
62    CPP_OTHER is included because of Objective C's use of '@'.  */
63 #define CAN_PASTE_AFTER(type) \
64 ((type) <= CPP_LAST_EQ || (type) == CPP_COLON || (type) == CPP_HASH \
65  || (type) == CPP_DEREF || (type) == CPP_DOT || (type) == CPP_NAME \
66  || (type) == CPP_INT || (type) == CPP_FLOAT || (type) == CPP_NUMBER \
67  || (type) == CPP_MACRO_ARG || (type) == CPP_PLACEMARKER \
68  || (type) == CPP_COMMA || (type) == CPP_OTHER)
69
70 /* Scans for a given token, returning the parameter number if found,
71    or 0 if not found.  Scans from FIRST to TOKEN - 1 or the first
72    CPP_CLOSE_PAREN for TOKEN.  */
73 static unsigned int
74 find_param (first, token)
75      const cpp_token *first, *token;
76 {
77   unsigned int param = 0;
78
79   for (; first < token && first->type != CPP_CLOSE_PAREN; first++)
80     if (first->type == CPP_NAME || first->type == CPP_DEFINED)
81       {
82         param++;
83         if (first->val.node == token->val.node)
84           return param;
85       }
86
87   return 0;
88 }
89
90 /* Constraint 6.10.3.5: __VA_ARGS__ should only appear in the
91    replacement list of a variable-arguments macro.  TOKEN is assumed
92    to be of type CPP_NAME.  */
93 static int
94 is__va_args__ (pfile, token)
95      cpp_reader *pfile;
96      const cpp_token *token;
97 {
98   if (!CPP_PEDANTIC (pfile)
99       || token->val.node != pfile->spec_nodes->n__VA_ARGS__)
100     return 0;
101
102   cpp_pedwarn_with_line (pfile, token->line, token->col,
103        "\"%s\" is only valid in the replacement list of a function-like macro",
104                        token->val.node->name);
105   return 1;
106 }
107
108 /* Counts the parameters to a function-like macro, the length of their
109    null-terminated names, and whether the macro is a variable-argument
110    one.  FIRST is the token immediately after the open parenthesis,
111    INFO stores the data.
112
113    On success, info->first is updated to the token after the closing
114    parenthesis, i.e. the first token of the expansion.  Otherwise
115    there was an error, which has been reported.  */
116 static void
117 count_params (pfile, info)
118      cpp_reader *pfile;
119      struct macro_info *info;
120 {
121   unsigned int prev_ident = 0;
122   const cpp_token *token;
123
124   info->paramc = 0;
125   info->paramlen = 0;
126   info->flags = 0;
127   info->first = info->first_param; /* Not a ')' indicating success.  */
128
129   for (token = info->first_param;; token++)
130     {
131       switch (token->type)
132         {
133         default:
134           cpp_error_with_line (pfile, token->line, token->col,
135                                "token may not appear in macro parameter list");
136           return;
137
138         case CPP_EOF:
139         missing_paren:
140           cpp_error_with_line (pfile, token->line, token->col,
141                                "missing ')' in macro parameter list");
142           return;
143
144         case CPP_COMMENT:
145           continue;             /* Ignore -C comments.  */
146
147         case CPP_DEFINED:       /* 'defined' may be used as a macro
148                                    parameter name.  */
149         case CPP_NAME:
150           if (prev_ident)
151             {
152               cpp_error_with_line (pfile, token->line, token->col,
153                            "macro parameters must be comma-separated");
154               return;
155             }
156
157           /* Constraint 6.10.3.5  */
158           if (is__va_args__ (pfile, token))
159             return;
160
161           /* Constraint 6.10.3.6 - duplicate parameter names.  */
162           if (find_param (info->first, token))
163             {
164               cpp_error_with_line (pfile, token->line, token->col,
165                                    "duplicate macro parameter \"%s\"",
166                                    token->val.node->name);
167               return;
168             }
169
170           prev_ident = 1;
171           info->paramc++;
172           info->paramlen += token->val.node->length + 1;
173           continue;
174
175         case CPP_CLOSE_PAREN:
176           if (prev_ident || info->paramc == 0)
177             break;
178
179           /* Fall through to pick up the error.  */
180         case CPP_COMMA:
181           if (!prev_ident)
182             {
183               cpp_error_with_line (pfile, token->line, token->col,
184                                    "parameter name expected");
185               return;
186             }
187           prev_ident = 0;
188           continue;
189
190         case CPP_ELLIPSIS:
191           /* Convert ISO-style var_args to named varargs by changing
192              the ellipsis into an identifier with name __VA_ARGS__.
193              This simplifies other handling. */
194           if (!prev_ident)
195             {
196               cpp_token *tok = (cpp_token *) token;
197
198               tok->type = CPP_NAME;
199               tok->val.node = pfile->spec_nodes->n__VA_ARGS__;
200
201               info->paramc++;
202               info->paramlen += tok->val.node->length + 1;
203
204               if (CPP_PEDANTIC (pfile) && ! CPP_OPTION (pfile, c99))
205                 cpp_pedwarn (pfile,
206                              "C89 does not permit anon varargs macros");
207             }
208           else
209             {
210               if (CPP_PEDANTIC (pfile))
211                 cpp_pedwarn (pfile,
212                              "ISO C does not permit named varargs parameters");
213             }
214
215           info->flags |= VAR_ARGS;
216           token++;
217           if (token->type == CPP_CLOSE_PAREN)
218             break;
219           goto missing_paren;
220         }
221
222       /* Success.  */
223       info->first = token + 1;
224       if (!pfile->save_parameter_spellings)
225         info->paramlen = 0;
226       return;
227     }
228 }
229
230 /* Parses a #define directive.  On success, returns zero, and INFO is
231    filled in appropriately.  */
232 static int
233 parse_define (pfile, info)
234      cpp_reader *pfile;
235      struct macro_info *info;
236 {
237   const cpp_token *token;
238   int prev_white = 0;
239
240   /* The first token after the macro's name.  */
241   token = _cpp_get_token (pfile);
242
243   /* Constraint 6.10.3.5  */
244   if (is__va_args__ (pfile, token - 1))
245     return 1;
246
247   while (token->type == CPP_COMMENT)
248     token++, prev_white = 1;
249   prev_white |= token->flags & PREV_WHITE;
250
251   if (token->type == CPP_OPEN_PAREN && !prev_white)
252     {
253       /* A function-like macro.  */
254       info->first_param = token + 1;
255       count_params (pfile, info);
256       if (info->first[-1].type != CPP_CLOSE_PAREN)
257         return 1;
258     }
259   else
260     {
261       /* An object-like macro.  */
262       info->paramc = -1;
263       info->paramlen = 0;
264       info->flags = 0;
265       info->first = token;
266       if (!prev_white && token->type != CPP_EOF)
267         cpp_pedwarn (pfile, "ISO C requires whitespace after the macro name");
268     }
269
270   /* Count tokens in expansion.  We drop paste tokens, and stringize
271      tokens, so don't count them.  */
272   info->ntokens = info->len = 0;
273   for (token = info->first; token->type != CPP_EOF; token++)
274     {
275       if (token->type == CPP_PASTE)
276         {
277           /* Token-paste ##, can appear in both object-like and
278              function-like macros, but not at the ends.  Constraint
279              6.10.3.3.1 */
280           if (token == info->first || token[1].type == CPP_EOF)
281             {
282               cpp_error_with_line (pfile, token->line, token->col,
283                 "'##' cannot appear at either end of a macro expansion");
284               return 1;
285             }
286           continue;
287         }
288       else if (token->type == CPP_HASH)
289         {
290           /* Stringifying #, but a normal character in object-like
291              macros.  Must come before a parameter name.  Constraint
292              6.10.3.2.1.  */
293           if (info->paramc >= 0)
294             {
295               if (token[1].type == CPP_NAME
296                   && find_param (info->first_param, token + 1))
297                 continue;
298               if (! CPP_OPTION (pfile, lang_asm))
299                 {
300                   cpp_error_with_line (pfile, token->line, token->col,
301                                "'#' is not followed by a macro parameter");
302                   return 1;
303                 }
304             }
305         }
306       else if (token->type == CPP_NAME)
307         {
308           /* Constraint 6.10.3.5  */
309           if (!(info->flags & VAR_ARGS) && is__va_args__ (pfile, token))
310             return 1;
311         }
312       info->ntokens++;
313       if (TOKEN_SPELL (token) == SPELL_STRING)
314         info->len += token->val.str.len;
315     }
316   
317   return 0;
318 }
319
320 /* Returns non-zero if a macro redefinition is trivial.  */
321 static int
322 check_macro_redefinition (pfile, hp, list2)
323      cpp_reader *pfile;
324      cpp_hashnode *hp;
325      const cpp_toklist *list2;
326 {
327   const cpp_toklist *list1;
328
329   if (hp->type != T_MACRO)
330     return ! pfile->done_initializing;
331
332   /* Clear the whitespace and BOL flags of the first tokens.  They get
333      altered during macro expansion, but is not significant here.  */
334   list1  = hp->value.expansion;
335   list1->tokens[0].flags &= ~(PREV_WHITE|BOL);
336   list2->tokens[0].flags &= ~(PREV_WHITE|BOL);
337
338   if (!_cpp_equiv_toklists (list1, list2))
339     return 0;
340
341   if (CPP_OPTION (pfile, pedantic)
342       && list1->paramc > 0
343       && (list1->params_len != list2->params_len
344           || memcmp (list1->namebuf, list2->namebuf, list1->params_len)))
345     return 0;
346
347   return 1;
348 }
349
350 /* This is a dummy structure whose only purpose is getting alignment
351    correct.  */
352 struct toklist_dummy
353 {
354   cpp_toklist list;
355   cpp_token first_token;
356 };
357
358 /* Allocate space to hold the token list, its tokens, their text, and
359    the parameter names if needed.  Empty expansions are stored as a
360    single placemarker token.
361
362    These are all allocated in a block together for performance
363    reasons.  Therefore, this token list cannot be expanded like a
364    normal token list.  Try to do so, and you lose.  */
365 static cpp_toklist *
366 alloc_macro (pfile, info)
367      cpp_reader *pfile;
368      struct macro_info *info;
369 {
370   unsigned int size;
371   struct toklist_dummy *dummy;
372   cpp_toklist *list;
373
374   /* Empty macros become a single placemarker token.  */
375   if (info->ntokens == 0)
376     info->ntokens = 1;
377
378   size = sizeof (struct toklist_dummy);
379   size += (info->ntokens - 1) * sizeof(cpp_token);
380   size += info->len + info->paramlen;
381
382   dummy = (struct toklist_dummy *) xmalloc (size);
383   list = (cpp_toklist *) dummy;
384   
385   /* Initialize the monster.  */
386   list->tokens = &dummy->first_token;
387   list->tokens_used = list->tokens_cap = info->ntokens;
388
389   list->namebuf = (unsigned char *) &list->tokens[info->ntokens];
390   list->name_used = list->name_cap = info->len + info->paramlen;
391
392   list->directive = 0;
393   list->line = pfile->token_list.line;
394   list->file = pfile->token_list.file;
395   list->params_len = info->paramlen;
396   list->paramc = info->paramc;
397   list->flags = info->flags;
398
399   return list;
400 }
401
402 /* Free the definition of macro H.  */
403
404 void
405 _cpp_free_definition (h)
406      cpp_hashnode *h;
407 {
408   if (h->type == T_MACRO)
409     free ((PTR) h->value.expansion);
410   else if (h->type == T_ASSERTION)
411     {
412       struct answer *temp, *next;
413
414       for (temp = h->value.answers; temp; temp = next)
415         {
416           next = temp->next;
417           FREE_ANSWER (temp);
418         }
419     }
420
421   h->type = T_VOID;
422   h->value.expansion = NULL;
423 }
424
425 /* Copy the tokens of the expansion, beginning with info->first until
426    CPP_EOF.  INFO contains information about the macro.
427
428    Change the type of macro arguments in the expansion from CPP_NAME
429    to CPP_MACRO_ARG.  Remove #'s that represent stringification,
430    flagging the CPP_MACRO_ARG it operates on STRINGIFY.  Remove ##'s,
431    flagging the token on its immediate left PASTE_LEFT.  Returns the
432    token list for the macro expansion.  */
433 static const cpp_toklist *
434 save_expansion (pfile, info)
435      cpp_reader *pfile;
436      struct macro_info *info;
437 {
438   const cpp_token *token;
439   cpp_toklist *list;
440   cpp_token *dest;
441   unsigned char *buf;
442       
443   list = alloc_macro (pfile, info);
444   buf = list->namebuf;
445
446   /* Store the null-terminated parameter spellings of a macro, to
447      provide pedantic warnings to satisfy 6.10.3.2, or for use when
448      dumping macro definitions.  They must go first.  */
449   if (list->params_len)
450     for (token = info->first_param; token < info->first; token++)
451       if (token->type == CPP_NAME || token->type == CPP_DEFINED)
452         {
453           /* Copy null too.  */
454           memcpy (buf, token->val.node->name, token->val.node->length + 1);
455           buf += token->val.node->length + 1;
456         }
457
458   dest = list->tokens;
459   for (token = info->first; token->type != CPP_EOF; token++)
460     {
461       unsigned int param_no;
462
463       switch (token->type)
464         {
465         case CPP_DEFINED:
466         case CPP_NAME:
467           if (list->paramc == -1)
468             break;
469
470           /* Check if the name is a macro parameter.  */
471           param_no = find_param (info->first_param, token);
472           if (param_no == 0)
473             break;
474           dest->val.aux = param_no - 1;
475
476           dest->type = CPP_MACRO_ARG;
477           if (token[-1].type == CPP_HASH)
478             dest->flags = token[-1].flags | STRINGIFY_ARG;
479           else
480             dest->flags = token->flags;  /* Particularly PREV_WHITE.  */
481           /* Turn off PREV_WHITE if we immediately follow a paste.
482              That way, even if the paste turns out to be invalid, there
483              will be no space between the two tokens in the output.  */
484           if (token[-1].type == CPP_PASTE)
485             dest->flags &= ~PREV_WHITE;
486           dest++;
487           continue;
488
489         case CPP_PASTE:
490           /* Set the paste flag on the token to our left, unless there
491              is no possible token to which it might be pasted.  That
492              is critical for correct operation under some circumstances;
493              see gcc.dg/cpp/paste6.c. */
494           if (CAN_PASTE_AFTER (dest[-1].type) || (dest[-1].flags & NAMED_OP))
495             dest[-1].flags |= PASTE_LEFT;
496           else if (CPP_OPTION (pfile, warn_paste))
497             cpp_warning_with_line (pfile, dest[-1].line, dest[-1].col,
498                                    "nothing can be pasted after this token");
499           continue;
500
501         case CPP_HASH:
502           /* Stringifying #.  Constraint 6.10.3.2.1  */
503           if (list->paramc >= 0 && token[1].type == CPP_NAME
504               && find_param (info->first_param, token + 1))
505             continue;
506           break;
507
508         case CPP_STRING:
509         case CPP_CHAR:
510           if (CPP_WTRADITIONAL (pfile) && list->paramc > 0)
511             check_trad_stringification (pfile, info, &token->val.str);
512           break;
513           
514         default:
515           break;
516         }
517
518       /* Copy the token.  */
519       *dest = *token;
520       if (TOKEN_SPELL (token) == SPELL_STRING)
521         {
522           memcpy (buf, token->val.str.text, token->val.str.len);
523           dest->val.str.text = buf;
524           buf += dest->val.str.len;
525         }
526       if (token[-1].type == CPP_PASTE)
527         dest->flags &= ~PREV_WHITE;
528       dest++;
529     }
530
531   /* Empty macros become a single placemarker token.  */
532   if (dest == list->tokens)
533     {
534       dest->type = CPP_PLACEMARKER;
535       dest->flags = 0;
536       dest->val.aux = 0;
537     }
538
539   return list;
540 }
541
542 /* Parse a macro and save its expansion.  Returns non-zero on success.  */
543 int
544 _cpp_create_definition (pfile, hp)
545      cpp_reader *pfile;
546      cpp_hashnode *hp;
547 {
548   struct macro_info info;
549   const cpp_toklist *list;
550
551   if (parse_define (pfile, &info))
552     return 0;
553   list = save_expansion (pfile, &info);
554
555   /* Check for a redefinition.  Redefinition of a macro is allowed if
556      and only if the old and new definitions are the same.
557      (6.10.3 paragraph 2). */
558
559   if (hp->type != T_VOID)
560     {
561       if (!check_macro_redefinition (pfile, hp, list))
562         {
563           cpp_pedwarn (pfile, "\"%s\" redefined", hp->name);
564           if (pfile->done_initializing && hp->type == T_MACRO)
565             cpp_pedwarn_with_file_and_line (pfile,
566                                             hp->value.expansion->file,
567                                             hp->value.expansion->line, 1,
568                             "this is the location of the previous definition");
569         }
570       _cpp_free_definition (hp);
571     }
572
573   /* Enter definition in hash table.  */
574   hp->type = T_MACRO;
575   hp->value.expansion = list;
576
577   return 1;
578 }
579
580 /* Dump the definition of macro MACRO on FP.  The format is suitable
581    to be read back in again.  Caller is expected to generate the
582    "#define NAME" bit.  */
583
584 void
585 cpp_dump_definition (pfile, fp, hp)
586      cpp_reader *pfile;
587      FILE *fp;
588      const cpp_hashnode *hp;
589 {
590   const cpp_toklist *list = hp->value.expansion;
591
592   if (hp->type != T_MACRO)
593     {
594       cpp_ice (pfile, "invalid hash type %d in dump_definition", hp->type);
595       return;
596     }
597
598   if (list->paramc >= 0)
599     dump_macro_args (fp, list);
600
601   putc (' ', fp);
602   cpp_output_list (pfile, fp, list, list->tokens);
603 }
604
605 static void
606 dump_macro_args (fp, list)
607      FILE *fp;
608      const cpp_toklist *list;
609 {
610   int i;
611   const U_CHAR *param = list->namebuf;
612
613   putc ('(', fp);
614   for (i = 0; i++ < list->paramc;)
615     {
616       unsigned int len;
617
618       len = ustrlen (param);
619       if (!(list->flags & VAR_ARGS) || ustrcmp (param, U"__VA_ARGS__"))
620         ufputs (param, fp);
621       if (i < list->paramc)
622         fputs (", ", fp);
623       else if (list->flags & VAR_ARGS)
624         fputs ("...", fp);
625
626       param += len + 1;
627     }
628   putc (')', fp);
629 }
630
631 /* Warn if a token in `string' matches one of the function macro
632    arguments in `info'.  This function assumes that the macro is a
633    function macro and not an object macro.  */
634 static void
635 check_trad_stringification (pfile, info, string)
636      cpp_reader *pfile;
637      const struct macro_info *info;
638      const cpp_string *string;
639 {
640   const U_CHAR *p, *q, *limit = string->text + string->len;
641   
642   /* Loop over the string.  */
643   for (p = string->text; p < limit; p = q)
644     {
645       const cpp_token *token;
646
647       /* Find the start of an identifier.  */
648       while (p < limit && !is_idstart (*p))
649         p++;
650
651       /* Find the end of the identifier.  */
652       q = p;
653       while (q < limit && is_idchar (*q))
654         q++;
655      
656       /* Loop over the function macro arguments to see if the
657          identifier inside the string matches one of them.  */
658       for (token = info->first_param; token < info->first; token++)
659         {
660           /* Skip the commas in between the arguments.  */
661           if (token->type != CPP_NAME)
662             continue;
663
664           if (token->val.node->length == (q - p)
665               && !memcmp (p, token->val.node->name, (q - p)))
666             {
667               cpp_warning (pfile,
668                            "macro arg \"%.*s\" would be stringified with -traditional.",
669                            (int) (q - p), p);
670               break;
671             }
672         }
673     }
674 }