OSDN Git Service

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