OSDN Git Service

toplevel:
[pf3gnuchains/gcc-fork.git] / gcc / cpphash.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 #include "hashtab.h"
31 #include "obstack.h"
32
33 #define obstack_chunk_alloc xmalloc
34 #define obstack_chunk_free free
35
36 /* This is the second argument to eq_HASHNODE.  */
37 struct hashdummy
38 {
39   const U_CHAR *name;
40   unsigned short length;
41 };
42
43 /* Initial hash table size.  (It can grow if necessary - see hashtab.c.)  */
44 #define HASHSIZE 500
45
46 static unsigned int hash_HASHNODE PARAMS ((const void *));
47 static int eq_HASHNODE            PARAMS ((const void *, const void *));
48 static int dump_hash_helper       PARAMS ((void **, void *));
49
50 static void dump_funlike_macro  PARAMS ((cpp_reader *, cpp_hashnode *));
51
52 static const cpp_token *count_params PARAMS ((cpp_reader *,
53                                               const cpp_token *,
54                                               cpp_toklist *));
55 static cpp_toklist *parse_define PARAMS((cpp_reader *));
56 static int check_macro_redefinition PARAMS((cpp_reader *, cpp_hashnode *hp,
57                                              const cpp_toklist *));
58 static int save_expansion PARAMS((cpp_reader *, cpp_toklist *,
59                                   const cpp_token *, const cpp_token *));
60 static unsigned int find_param PARAMS ((const cpp_token *,
61                                         const cpp_token *));
62
63 static const unsigned char var_args_str[] = "__VA_ARGS__";
64
65 /* Calculate hash of a string of length LEN.  */
66 unsigned int
67 _cpp_calc_hash (str, len)
68      const U_CHAR *str;
69      size_t len;
70 {
71   size_t n = len;
72   unsigned int r = 0;
73
74   do
75     r = r * 67 + (*str++ - 113);
76   while (--n);
77   return r + len;
78 }
79
80 /* Calculate hash of a cpp_hashnode structure.  */
81 static unsigned int
82 hash_HASHNODE (x)
83      const void *x;
84 {
85   const cpp_hashnode *h = (const cpp_hashnode *)x;
86   return h->hash;
87 }
88
89 /* Compare a cpp_hashnode structure (already in the table) with a
90    hashdummy structure (not yet in the table).  This relies on the
91    rule that the existing entry is the first argument, the potential
92    entry the second.  It also relies on the comparison function never
93    being called except as a direct consequence of a call to
94    htab_find(_slot)_with_hash.  */
95 static int
96 eq_HASHNODE (x, y)
97      const void *x;
98      const void *y;
99 {
100   const cpp_hashnode *a = (const cpp_hashnode *)x;
101   const struct hashdummy *b = (const struct hashdummy *)y;
102
103   return (a->length == b->length
104           && !ustrncmp (a->name, b->name, a->length));
105 }
106
107 /* Find the hash node for name "name", of length LEN.  */
108
109 cpp_hashnode *
110 cpp_lookup (pfile, name, len)
111      cpp_reader *pfile;
112      const U_CHAR *name;
113      int len;
114 {
115   struct hashdummy dummy;
116   cpp_hashnode *new, **slot;
117   unsigned int hash;
118   U_CHAR *p;
119
120   dummy.name = name;
121   dummy.length = len;
122   hash = _cpp_calc_hash (name, len);
123
124   slot = (cpp_hashnode **)
125     htab_find_slot_with_hash (pfile->hashtab, (void *)&dummy, hash, INSERT);
126   if (*slot)
127     return *slot;
128
129   /* Create a new hash node.  */
130   p = obstack_alloc (pfile->hash_ob, sizeof (cpp_hashnode) + len);
131   new = (cpp_hashnode *)p;
132   p += offsetof (cpp_hashnode, name);
133   
134   new->type = T_VOID;
135   new->length = len;
136   new->hash = hash;
137   new->fe_value = 0;
138   new->value.expansion = NULL;
139
140   memcpy (p, name, len);
141   p[len] = 0;
142
143   *slot = new;
144   return new;
145 }
146
147 /* Set up and tear down internal structures for macro expansion.  */
148 void
149 _cpp_init_macros (pfile)
150      cpp_reader *pfile;
151 {
152   pfile->hashtab = htab_create (HASHSIZE, hash_HASHNODE,
153                                 eq_HASHNODE, (htab_del) _cpp_free_definition);
154   pfile->hash_ob = xnew (struct obstack);
155   obstack_init (pfile->hash_ob);
156 }
157
158 void
159 _cpp_cleanup_macros (pfile)
160      cpp_reader *pfile;
161 {
162   htab_delete (pfile->hashtab);
163   obstack_free (pfile->hash_ob, 0);
164   free (pfile->hash_ob);
165 }
166
167 /* Free the definition of macro H.  */
168
169 void
170 _cpp_free_definition (h)
171      cpp_hashnode *h;
172 {
173   if (h->type == T_MACRO)
174     _cpp_free_toklist (h->value.expansion);
175   h->value.expansion = NULL;
176 }
177
178 /* Scans for a given token, returning the parameter number if found,
179    or 0 if not found.  Scans from FIRST to TOKEN - 1 or the first
180    CPP_CLOSE_PAREN for TOKEN.  */
181 static unsigned int
182 find_param (first, token)
183      const cpp_token *first, *token;
184 {
185   unsigned int param = 0;
186
187   for (; first < token && first->type != CPP_CLOSE_PAREN; first++)
188     if (first->type == CPP_NAME)
189       {
190         param++;
191         if (first->val.name.len == token->val.name.len
192             && !memcmp (first->val.name.text, token->val.name.text,
193                         token->val.name.len))
194           return param;
195       }
196
197   return 0;
198 }
199
200 /* Counts the parameters to a function like macro, and saves their
201    spellings if necessary.  Returns the token that we stopped scanning
202    at; if it's type isn't CPP_CLOSE_PAREN there was an error, which
203    has been reported.  */
204 static const cpp_token *
205 count_params (pfile, first, list)
206      cpp_reader *pfile;
207      const cpp_token *first;
208      cpp_toklist *list;
209 {
210   unsigned int params_len = 0, prev_ident = 0;
211   unsigned int line = pfile->token_list.line;
212   const cpp_token *token, *temp;
213
214   list->paramc = 0;
215   for (token = first;; token++)
216     {
217       switch (token->type)
218         {
219         case CPP_EOF:
220           cpp_error_with_line (pfile, line, token->col,
221                                "missing ')' in macro parameter list");
222           goto out;
223
224         case CPP_COMMENT:
225           continue;             /* Ignore -C comments.  */
226
227         case CPP_NAME:
228           if (prev_ident)
229             {
230               cpp_error_with_line (pfile, line, token->col,
231                            "macro parameters must be comma-separated");
232               goto out;
233             }
234
235           /* Constraint 6.10.3.5  */
236           if (token->val.name.len == sizeof (var_args_str) - 1
237               && !ustrncmp (token->val.name.text, var_args_str,
238                             sizeof (var_args_str) - 1))
239             {
240               cpp_error_with_line (pfile, line, token->col,
241                                    "\"%s\" is not a valid parameter name",
242                                    var_args_str);
243               goto out;
244             }
245
246           params_len += token->val.name.len + 1;
247           prev_ident = 1;
248           list->paramc++;
249
250           /* Constraint 6.10.3.6 - duplicate parameter names.  */
251           if (find_param (first, token))
252             {
253               cpp_error_with_line (pfile, line, token->col,
254                                    "duplicate macro parameter \"%.*s\"",
255                                    (int) token->val.name.len,
256                                    token->val.name.text);
257               goto out;
258             }
259           break;
260
261         default:
262           cpp_error_with_line (pfile, line, token->col,
263                                "illegal token in macro parameter list");
264           goto out;
265
266         case CPP_CLOSE_PAREN:
267           if (prev_ident || list->paramc == 0)
268             goto scanned;
269
270           /* Fall through to pick up the error.  */
271         case CPP_COMMA:
272           if (!prev_ident)
273             {
274               cpp_error_with_line (pfile, line, token->col,
275                                    "missing parameter name");
276               goto out;
277             }
278           prev_ident = 0;
279           break;
280
281         case CPP_ELLIPSIS:
282           /* Convert ISO-style var_args to named varargs by changing
283              the ellipsis into an identifier with name __VA_ARGS__.
284              This simplifies other handling.  We can safely have its
285              text outside list->namebuf because there is no reason to
286              extend the size of the list's namebuf (and thus change
287              the pointer) in do_define.  */
288           if (!prev_ident)
289             {
290               cpp_token *tok = (cpp_token *) token;
291
292               tok->type = CPP_NAME;
293               tok->val.name.len = sizeof (var_args_str) - 1;
294               tok->val.name.text = var_args_str; /* Safe.  */
295               list->paramc++;
296
297               if (CPP_PEDANTIC (pfile) && ! CPP_OPTION (pfile, c99))
298                 cpp_pedwarn (pfile,
299                              "C89 does not permit anon varargs macros");
300             }
301           else if (CPP_PEDANTIC (pfile))
302             cpp_pedwarn (pfile,
303                          "ISO C does not permit named varargs parameters");
304
305           list->flags |= VAR_ARGS;
306           token++;
307           if (token->type == CPP_CLOSE_PAREN)
308             goto scanned;
309           cpp_error_with_line (pfile, line, token->col,
310                                "')' expected after \"...\"");
311           goto out;
312         }
313     }
314
315  scanned:
316   /* Store the null-terminated parameter spellings of a function, to
317      provide pedantic warnings to satisfy 6.10.3.2, or for use when
318      dumping macro definitions.  */
319   if (list->paramc > 0 && pfile->save_parameter_spellings)
320     {
321       U_CHAR *buf;
322
323       _cpp_reserve_name_space (list, params_len);
324       list->params_len = list->name_used = params_len;
325       buf = list->namebuf;
326       for (temp = first; temp <= token; temp++)
327         if (temp->type == CPP_NAME)
328           {
329             memcpy (buf, temp->val.name.text, temp->val.name.len);
330             buf += temp->val.name.len;
331             *buf++ = '\0';
332           }
333     }
334
335  out:
336   return token;
337 }
338
339 /* Parses a #define directive.  Returns null pointer on error.  */
340 static cpp_toklist *
341 parse_define (pfile)
342      cpp_reader *pfile;
343 {
344   const cpp_token *token, *first_param;
345   cpp_toklist *list;
346   int prev_white = 0;
347
348   while ((token = cpp_get_token (pfile))->type == CPP_COMMENT)
349     prev_white = 1;
350
351   /* Allocate the expansion's list.  It will go in the hash table.  */
352   list = (cpp_toklist *) xmalloc (sizeof (cpp_toklist));
353   _cpp_init_toklist (list, 0);
354   first_param = token + 1;
355   list->paramc = -1;            /* Object-like macro.  */
356
357   if (!prev_white && !(token->flags & PREV_WHITE))
358     {
359       if (token->type == CPP_OPEN_PAREN)
360         {
361           token = count_params (pfile, first_param, list);
362           if (token->type != CPP_CLOSE_PAREN)
363             goto error;
364           token++;
365         }
366       else if (token->type != CPP_EOF)
367         cpp_pedwarn (pfile,
368                      "ISO C requires whitespace after the macro name");
369     }
370
371   if (save_expansion (pfile, list, token, first_param))
372     {
373     error:
374       _cpp_free_toklist (list);
375       list = 0;
376     }
377
378   return list;
379 }
380
381 static int
382 check_macro_redefinition (pfile, hp, list2)
383      cpp_reader *pfile;
384      cpp_hashnode *hp;
385      const cpp_toklist *list2;
386 {
387   const cpp_toklist *list1;
388
389   if (hp->type != T_MACRO)
390     return ! pfile->done_initializing;
391
392   /* Clear the whitespace and BOL flags of the first tokens.  They get
393      altered during macro expansion, but is not significant here.  */
394   list1  = hp->value.expansion;
395   list1->tokens[0].flags &= ~(PREV_WHITE|BOL);
396   list2->tokens[0].flags &= ~(PREV_WHITE|BOL);
397
398   if (!_cpp_equiv_toklists (list1, list2))
399     return 0;
400
401   if (CPP_OPTION (pfile, pedantic)
402       && list1->paramc > 0
403       && (list1->params_len != list2->params_len
404           || memcmp (list1->namebuf, list2->namebuf, list1->params_len)))
405     return 0;
406
407   return 1;
408 }
409
410 /* Copy the tokens of the expansion.  Change the type of macro
411    arguments from CPP_NAME to CPP_MACRO_ARG.  Remove #'s that
412    represent stringification, flagging the CPP_MACRO_ARG it operates
413    on STRINGIFY.  Remove ##'s, flagging the token on its immediate
414    left PASTE_LEFT.  Returns non-zero on error.  */
415 static int
416 save_expansion (pfile, list, first, first_param)
417      cpp_reader *pfile;
418      cpp_toklist *list;
419      const cpp_token *first;
420      const cpp_token *first_param;
421 {
422   const cpp_token *token;
423   cpp_token *dest;
424   unsigned int len, ntokens;
425   unsigned char *buf;
426       
427   /* Count tokens in expansion.  We drop paste tokens, and stringize
428      tokens, so don't count them.  */
429   ntokens = len = 0;
430   for (token = first; token->type != CPP_EOF; token++)
431     {
432       const char *msg;
433
434       if (token->type == CPP_PASTE)
435         {
436           /* Token-paste ##, but is a normal token if traditional.  */
437           if (! CPP_TRADITIONAL (pfile))
438             {
439               msg = "\"##\" cannot appear at either end of a macro expansion";
440               /* Constraint 6.10.3.3.1  */
441               if (token == first || token[1].type == CPP_EOF)
442                 goto error;
443               continue;
444             }
445         }
446       else if (token->type == CPP_HASH)
447         {
448           /* Stringifying #, but is a normal character if traditional,
449              or in object-like macros.  Constraint 6.10.3.2.1.  */
450           if (list->paramc >= 0 && ! CPP_TRADITIONAL (pfile))
451             {
452               if (token[1].type == CPP_NAME
453                   && find_param (first_param, token + 1))
454                 continue;
455               if (! CPP_OPTION (pfile, lang_asm))
456                 {
457                   msg = "'#' is not followed by a macro parameter";
458                 error:
459                   cpp_error_with_line (pfile, token->line, token->col, msg);
460                   return 1;
461                 }
462             }
463         }
464       ntokens++;
465       if (token_spellings[token->type].type > SPELL_NONE)
466         len += token->val.name.len;
467     }
468
469   /* Allocate space to hold the tokens.  Empty expansions are stored
470      as a single placemarker token.  */
471   if (ntokens == 0)
472     ntokens++;
473   _cpp_expand_token_space (list, ntokens);
474   if (len > 0)
475     _cpp_expand_name_space (list, len);
476
477   dest = list->tokens;
478   buf = list->namebuf + list->name_used;
479   for (token = first; token->type != CPP_EOF; token++)
480     {
481       unsigned int param_no;
482
483       switch (token->type)
484         {
485         case CPP_NAME:
486           if (list->paramc == -1)
487             break;
488
489           /* Check if the name is a macro parameter.  */
490           param_no = find_param (first_param, token);
491           if (param_no == 0)
492             break;
493           dest->val.aux = param_no - 1;
494
495           dest->type = CPP_MACRO_ARG;
496           if (token[-1].type == CPP_HASH && ! CPP_TRADITIONAL (pfile))
497             dest->flags = token[-1].flags | STRINGIFY_ARG;
498           else
499             dest->flags = token->flags;  /* Particularly PREV_WHITE.  */
500
501           if ((int) param_no == list->paramc && list->flags & VAR_ARGS
502               && dest != list->tokens && dest[-1].flags & PASTE_LEFT)
503             dest[-1].flags |= GNU_VARARGS;
504           dest++;
505           continue;
506
507         case CPP_PASTE:
508           if (! CPP_TRADITIONAL (pfile))
509             {
510               dest[-1].flags |= PASTE_LEFT;
511               continue;
512             }
513           break;
514
515         case CPP_HASH:
516           /* Stringifying #.  Constraint 6.10.3.2.1  */
517           if (list->paramc >= 0 && ! CPP_TRADITIONAL (pfile)
518               && token[1].type == CPP_NAME
519               && find_param (first_param, token + 1))
520             continue;
521           break;
522
523         default:
524           break;
525         }
526
527       /* Copy the token.  */
528       *dest = *token;
529       if (token_spellings[token->type].type > SPELL_NONE)
530         {
531           memcpy (buf, token->val.name.text, token->val.name.len);
532           dest->val.name.text = buf;
533           buf += dest->val.name.len;
534         }
535       dest++;
536     }
537
538   if (dest == list->tokens)
539     {
540       dest->type = CPP_PLACEMARKER;
541       dest->flags = 0;
542     }
543
544   list->tokens_used = ntokens;
545   list->line = pfile->token_list.line;
546   list->file = pfile->token_list.file;
547   list->name_used = len;
548
549   return 0;
550 }
551
552 int
553 _cpp_create_definition (pfile, hp)
554      cpp_reader *pfile;
555      cpp_hashnode *hp;
556 {
557   cpp_toklist *list;
558
559   list = parse_define (pfile);
560   if (!list)
561     return 0;
562
563   /* Check for a redefinition.  Redefinition of a macro is allowed if
564      and only if the old and new definitions are the same.
565      (6.10.3 paragraph 2). */
566
567   if (hp->type != T_VOID)
568     {
569       if (!check_macro_redefinition (pfile, hp, list))
570         {
571           cpp_pedwarn (pfile, "\"%s\" redefined", hp->name);
572           if (pfile->done_initializing && hp->type == T_MACRO)
573             cpp_pedwarn_with_file_and_line (pfile,
574                                             hp->value.expansion->file,
575                                             hp->value.expansion->line, 1,
576                             "this is the location of the previous definition");
577         }
578       _cpp_free_definition (hp);
579     }
580
581   /* Enter definition in hash table.  */
582   hp->type = T_MACRO;
583   hp->value.expansion = list;
584
585   return 1;
586 }
587
588 /* Dump the definition of macro MACRO on stdout.  The format is suitable
589    to be read back in again. */
590
591 void
592 _cpp_dump_definition (pfile, hp)
593      cpp_reader *pfile;
594      cpp_hashnode *hp;
595 {
596   CPP_RESERVE (pfile, hp->length + sizeof "#define ");
597   CPP_PUTS_Q (pfile, "#define ", sizeof "#define " - 1);
598   CPP_PUTS_Q (pfile, hp->name, hp->length);
599
600   if (hp->type == T_MACRO)
601     {
602       if (hp->value.expansion->paramc >= 0)
603         dump_funlike_macro (pfile, hp);
604       else
605         {
606           const cpp_toklist *list = hp->value.expansion;
607           list->tokens[0].flags &= ~BOL;
608           list->tokens[0].flags |= PREV_WHITE;
609           _cpp_dump_list (pfile, list, list->tokens, 1);
610         }
611     }
612   else
613     cpp_ice (pfile, "invalid hash type %d in dump_definition", hp->type);
614
615   if (CPP_BUFFER (pfile) == 0 || ! pfile->done_initializing)
616     CPP_PUTC (pfile, '\n');
617 }
618
619 static void
620 dump_funlike_macro (pfile, node)
621      cpp_reader *pfile;
622      cpp_hashnode *node;
623 {
624   int i = 0;
625   const cpp_toklist * list = node->value.expansion;
626   const U_CHAR *param;
627
628   param = list->namebuf;
629   CPP_PUTC_Q (pfile, '(');
630   for (i = 0; i++ < list->paramc;)
631     {
632       unsigned int len;
633
634       len = ustrlen (param);
635       CPP_PUTS (pfile, param, len);
636       if (i < list->paramc)
637         CPP_PUTS(pfile, ", ", 2);
638       else if (list->flags & VAR_ARGS)
639         {
640           if (!ustrcmp (param, var_args_str))
641             pfile->limit -= sizeof (var_args_str) - 1;
642           CPP_PUTS (pfile, "...", 3);
643         }
644       param += len + 1;
645     }
646   CPP_PUTC (pfile, ')');
647   list->tokens[0].flags &= ~BOL;
648   list->tokens[0].flags |= PREV_WHITE;
649   _cpp_dump_list (pfile, list, list->tokens, 1);
650 }
651
652 /* Dump out the hash table.  */
653 static int
654 dump_hash_helper (h, p)
655      void **h;
656      void *p;
657 {
658   cpp_hashnode *hp = (cpp_hashnode *)*h;
659   cpp_reader *pfile = (cpp_reader *)p;
660
661   if (hp->type == T_MACRO)
662     _cpp_dump_definition (pfile, hp);
663   return 1;
664 }
665
666 void
667 _cpp_dump_macro_hash (pfile)
668      cpp_reader *pfile;
669 {
670   htab_traverse (pfile->hashtab, dump_hash_helper, pfile);
671 }