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