OSDN Git Service

Integrated preprocessor.
[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   else if (h->type == T_ASSERTION)
408     {
409       struct answer *temp, *next;
410
411       for (temp = h->value.answers; temp; temp = next)
412         {
413           next = temp->next;
414           FREE_ANSWER (temp);
415         }
416     }
417
418   h->type = T_VOID;
419   h->value.expansion = NULL;
420 }
421
422 /* Copy the tokens of the expansion, beginning with info->first until
423    CPP_EOF.  INFO contains information about the macro.
424
425    Change the type of macro arguments in the expansion from CPP_NAME
426    to CPP_MACRO_ARG.  Remove #'s that represent stringification,
427    flagging the CPP_MACRO_ARG it operates on STRINGIFY.  Remove ##'s,
428    flagging the token on its immediate left PASTE_LEFT.  Returns the
429    token list for the macro expansion.  */
430 static const cpp_toklist *
431 save_expansion (pfile, info)
432      cpp_reader *pfile;
433      struct macro_info *info;
434 {
435   const cpp_token *token;
436   cpp_toklist *list;
437   cpp_token *dest;
438   unsigned char *buf;
439       
440   list = alloc_macro (pfile, info);
441   buf = list->namebuf;
442
443   /* Store the null-terminated parameter spellings of a macro, to
444      provide pedantic warnings to satisfy 6.10.3.2, or for use when
445      dumping macro definitions.  They must go first.  */
446   if (list->params_len)
447     for (token = info->first_param; token < info->first; token++)
448       if (token->type == CPP_NAME || token->type == CPP_DEFINED)
449         {
450           /* Copy null too.  */
451           memcpy (buf, token->val.node->name, token->val.node->length + 1);
452           buf += token->val.node->length + 1;
453         }
454
455   dest = list->tokens;
456   for (token = info->first; token->type != CPP_EOF; token++)
457     {
458       unsigned int param_no;
459
460       switch (token->type)
461         {
462         case CPP_DEFINED:
463         case CPP_NAME:
464           if (list->paramc == -1)
465             break;
466
467           /* Check if the name is a macro parameter.  */
468           param_no = find_param (info->first_param, token);
469           if (param_no == 0)
470             break;
471           dest->val.aux = param_no - 1;
472
473           dest->type = CPP_MACRO_ARG;
474           if (token[-1].type == CPP_HASH)
475             dest->flags = token[-1].flags | STRINGIFY_ARG;
476           else
477             dest->flags = token->flags;  /* Particularly PREV_WHITE.  */
478           /* Turn off PREV_WHITE if we immediately follow a paste.
479              That way, even if the paste turns out to be invalid, there
480              will be no space between the two tokens in the output.  */
481           if (token[-1].type == CPP_PASTE)
482             dest->flags &= ~PREV_WHITE;
483           dest++;
484           continue;
485
486         case CPP_PASTE:
487           /* Set the paste flag on the token to our left, unless there
488              is no possible token to which it might be pasted.  That
489              is critical for correct operation under some circumstances;
490              see gcc.dg/cpp/paste6.c. */
491           if (CAN_PASTE_AFTER (dest[-1].type) || (dest[-1].flags & NAMED_OP))
492             dest[-1].flags |= PASTE_LEFT;
493           else if (CPP_OPTION (pfile, warn_paste))
494             cpp_warning_with_line (pfile, dest[-1].line, dest[-1].col,
495                                    "nothing can be pasted after this token");
496           continue;
497
498         case CPP_HASH:
499           /* Stringifying #.  Constraint 6.10.3.2.1  */
500           if (list->paramc >= 0 && token[1].type == CPP_NAME
501               && find_param (info->first_param, token + 1))
502             continue;
503           break;
504
505         default:
506           break;
507         }
508
509       /* Copy the token.  */
510       *dest = *token;
511       if (TOKEN_SPELL (token) == SPELL_STRING)
512         {
513           memcpy (buf, token->val.str.text, token->val.str.len);
514           dest->val.str.text = buf;
515           buf += dest->val.str.len;
516         }
517       if (token[-1].type == CPP_PASTE)
518         dest->flags &= ~PREV_WHITE;
519       dest++;
520     }
521
522   /* Empty macros become a single placemarker token.  */
523   if (dest == list->tokens)
524     {
525       dest->type = CPP_PLACEMARKER;
526       dest->flags = 0;
527       dest->val.aux = 0;
528     }
529
530   return list;
531 }
532
533 /* Parse a macro and save its expansion.  Returns non-zero on success.  */
534 int
535 _cpp_create_definition (pfile, hp)
536      cpp_reader *pfile;
537      cpp_hashnode *hp;
538 {
539   struct macro_info info;
540   const cpp_toklist *list;
541
542   if (parse_define (pfile, &info))
543     return 0;
544   list = save_expansion (pfile, &info);
545
546   /* Check for a redefinition.  Redefinition of a macro is allowed if
547      and only if the old and new definitions are the same.
548      (6.10.3 paragraph 2). */
549
550   if (hp->type != T_VOID)
551     {
552       if (!check_macro_redefinition (pfile, hp, list))
553         {
554           cpp_pedwarn (pfile, "\"%s\" redefined", hp->name);
555           if (pfile->done_initializing && hp->type == T_MACRO)
556             cpp_pedwarn_with_file_and_line (pfile,
557                                             hp->value.expansion->file,
558                                             hp->value.expansion->line, 1,
559                             "this is the location of the previous definition");
560         }
561       _cpp_free_definition (hp);
562     }
563
564   /* Enter definition in hash table.  */
565   hp->type = T_MACRO;
566   hp->value.expansion = list;
567
568   return 1;
569 }
570
571 /* Dump the definition of macro MACRO on FP.  The format is suitable
572    to be read back in again.  Caller is expected to generate the
573    "#define NAME" bit.  */
574
575 void
576 cpp_dump_definition (pfile, fp, hp)
577      cpp_reader *pfile;
578      FILE *fp;
579      const cpp_hashnode *hp;
580 {
581   const cpp_toklist *list = hp->value.expansion;
582
583   if (hp->type != T_MACRO)
584     {
585       cpp_ice (pfile, "invalid hash type %d in dump_definition", hp->type);
586       return;
587     }
588
589   if (list->paramc >= 0)
590     dump_macro_args (fp, list);
591
592   putc (' ', fp);
593   cpp_output_list (pfile, fp, list, list->tokens);
594 }
595
596 static void
597 dump_macro_args (fp, list)
598      FILE *fp;
599      const cpp_toklist *list;
600 {
601   int i;
602   const U_CHAR *param = list->namebuf;
603
604   putc ('(', fp);
605   for (i = 0; i++ < list->paramc;)
606     {
607       unsigned int len;
608
609       len = ustrlen (param);
610       if (!(list->flags & VAR_ARGS) || ustrcmp (param, U"__VA_ARGS__"))
611         ufputs (param, fp);
612       if (i < list->paramc)
613         fputs (", ", fp);
614       else if (list->flags & VAR_ARGS)
615         fputs ("...", fp);
616
617       param += len + 1;
618     }
619   putc (')', fp);
620 }