OSDN Git Service

* cpplib.h (enum cpp_ttype): Add token types for all
[pf3gnuchains/gcc-fork.git] / gcc / cppexp.c
1 /* Parse C expressions for cpplib.
2    Copyright (C) 1987, 92, 94, 95, 97, 98, 1999, 2000 Free Software Foundation.
3    Contributed by Per Bothner, 1994.
4
5 This program is free software; you can redistribute it and/or modify it
6 under the terms of the GNU General Public License as published by the
7 Free Software Foundation; either version 2, or (at your option) any
8 later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.  */
19
20 /* Parse a C expression from text in a string  */
21    
22 #include "config.h"
23 #include "system.h"
24 #include "cpplib.h"
25 #include "hashtab.h"
26 #include "cpphash.h"
27
28 #ifndef CHAR_TYPE_SIZE
29 #define CHAR_TYPE_SIZE BITS_PER_UNIT
30 #endif
31
32 #ifndef INT_TYPE_SIZE
33 #define INT_TYPE_SIZE BITS_PER_WORD
34 #endif
35
36 #ifndef LONG_TYPE_SIZE
37 #define LONG_TYPE_SIZE BITS_PER_WORD
38 #endif
39
40 #ifndef WCHAR_TYPE_SIZE
41 #define WCHAR_TYPE_SIZE INT_TYPE_SIZE
42 #endif
43
44 #ifndef MAX_CHAR_TYPE_SIZE
45 #define MAX_CHAR_TYPE_SIZE CHAR_TYPE_SIZE
46 #endif
47
48 #ifndef MAX_INT_TYPE_SIZE
49 #define MAX_INT_TYPE_SIZE INT_TYPE_SIZE
50 #endif
51
52 #ifndef MAX_LONG_TYPE_SIZE
53 #define MAX_LONG_TYPE_SIZE LONG_TYPE_SIZE
54 #endif
55
56 #ifndef MAX_WCHAR_TYPE_SIZE
57 #define MAX_WCHAR_TYPE_SIZE WCHAR_TYPE_SIZE
58 #endif
59
60 #define MAX_CHAR_TYPE_MASK (MAX_CHAR_TYPE_SIZE < HOST_BITS_PER_WIDEST_INT \
61                     ? (~(~(HOST_WIDEST_INT) 0 << MAX_CHAR_TYPE_SIZE)) \
62                     : ~ (HOST_WIDEST_INT) 0)
63
64 #define MAX_WCHAR_TYPE_MASK (MAX_WCHAR_TYPE_SIZE < HOST_BITS_PER_WIDEST_INT \
65                              ? ~(~(HOST_WIDEST_INT) 0 << MAX_WCHAR_TYPE_SIZE) \
66                              : ~ (HOST_WIDEST_INT) 0)
67
68 /* Yield nonzero if adding two numbers with A's and B's signs can yield a
69    number with SUM's sign, where A, B, and SUM are all C integers.  */
70 #define possible_sum_sign(a, b, sum) ((((a) ^ (b)) | ~ ((a) ^ (sum))) < 0)
71
72 typedef short op_t;
73
74 static void integer_overflow PARAMS ((cpp_reader *));
75 static HOST_WIDEST_INT left_shift PARAMS ((cpp_reader *, HOST_WIDEST_INT,
76                                            unsigned int,
77                                            unsigned HOST_WIDEST_INT));
78 static HOST_WIDEST_INT right_shift PARAMS ((cpp_reader *, HOST_WIDEST_INT,
79                                             unsigned int,
80                                             unsigned HOST_WIDEST_INT));
81 static struct operation parse_number PARAMS ((cpp_reader *, U_CHAR *,
82                                               U_CHAR *));
83 static struct operation parse_charconst PARAMS ((cpp_reader *, U_CHAR *,
84                                                  U_CHAR *));
85 static struct operation parse_defined PARAMS ((cpp_reader *));
86 static HOST_WIDEST_INT parse_escape PARAMS ((cpp_reader *, U_CHAR **,
87                                              HOST_WIDEST_INT));
88 static struct operation lex PARAMS ((cpp_reader *, int));
89 static const char * op_to_str PARAMS ((op_t, char *));
90
91 #define ERROR 299
92 #define OROR 300
93 #define ANDAND 301
94 #define EQUAL 302
95 #define NOTEQUAL 303
96 #define LEQ 304
97 #define GEQ 305
98 #define LSH 306
99 #define RSH 307
100 #define NAME 308
101 #define INT 309
102 #define CHAR 310
103 #define FINISHED 311
104
105 struct operation
106 {
107   op_t op;
108   U_CHAR prio;         /* Priority of op.  */
109   U_CHAR flags;
110   U_CHAR unsignedp;    /* True if value should be treated as unsigned.  */
111   HOST_WIDEST_INT value; /* The value logically "right" of op.  */
112 };
113
114 /* Parse and convert an integer for #if.  Accepts decimal, hex, or octal
115    with or without size suffixes.  */
116
117 static struct operation
118 parse_number (pfile, start, end)
119      cpp_reader *pfile;
120      U_CHAR *start;
121      U_CHAR *end;
122 {
123   struct operation op;
124   U_CHAR *p = start;
125   int c;
126   unsigned HOST_WIDEST_INT n = 0, nd, MAX_over_base;
127   int base = 10;
128   int overflow = 0;
129   int digit, largest_digit = 0;
130   int spec_long = 0;
131
132   op.unsignedp = 0;
133
134   if (p[0] == '0')
135     {
136       if (end - start >= 3 && (p[1] == 'x' || p[1] == 'X'))
137         {
138           p += 2;
139           base = 16;
140         }
141       else
142         {
143           p += 1;
144           base = 8;
145         }
146     }
147
148   /* Some buggy compilers (e.g. MPW C) seem to need both casts.  */
149   MAX_over_base = (((unsigned HOST_WIDEST_INT) -1)
150                    / ((unsigned HOST_WIDEST_INT) base));
151
152   while (p < end)
153     {
154       c = *p++;
155
156       if (c >= '0' && c <= '9')
157         digit = c - '0';
158       /* FIXME: assumes ASCII */
159       else if (base == 16 && c >= 'a' && c <= 'f')
160         digit = c - 'a' + 10;
161       else if (base == 16 && c >= 'A' && c <= 'F')
162         digit = c - 'A' + 10;
163       else if (c == '.')
164         {
165           /* It's a float since it contains a point.  */
166           cpp_error (pfile,
167              "floating point numbers are not allowed in #if expressions");
168           goto error;
169         }
170       else
171         {
172           /* `l' means long, and `u' means unsigned.  */
173           for (;;)
174             {
175               if (c == 'l' || c == 'L')
176                   spec_long++;
177               else if (c == 'u' || c == 'U')
178                   op.unsignedp++;
179               else
180                 {
181                   /* Decrement p here so that the error for an invalid
182                      number will be generated below in the case where
183                      this is the last character in the buffer.  */
184                   p--;
185                   break;
186                 }
187               if (p == end)
188                 break;
189               c = *p++;
190             }
191           /* Don't look for any more digits after the suffixes.  */
192           break;
193         }
194       
195       if (largest_digit < digit)
196         largest_digit = digit;
197       nd = n * base + digit;
198       overflow |= MAX_over_base < n || nd < n;
199       n = nd;
200     }
201
202   if (p != end)
203     {
204       cpp_error (pfile, "invalid number in #if expression");
205       goto error;
206     }
207   else if (spec_long > (CPP_OPTION (pfile, c89) ? 1 : 2))
208     {
209       cpp_error (pfile, "too many 'l' suffixes in integer constant");
210       goto error;
211     }
212   else if (op.unsignedp > 1)
213     {
214       cpp_error (pfile, "too many 'u' suffixes in integer constant");
215       goto error;
216     }
217   
218   if (base <= largest_digit)
219     cpp_pedwarn (pfile,
220                  "integer constant contains digits beyond the radix");
221
222   if (overflow)
223     cpp_pedwarn (pfile, "integer constant out of range");
224
225   /* If too big to be signed, consider it unsigned.  */
226   else if ((HOST_WIDEST_INT) n < 0 && ! op.unsignedp)
227     {
228       if (base == 10)
229         cpp_warning (pfile,
230                      "integer constant is so large that it is unsigned");
231       op.unsignedp = 1;
232     }
233
234   op.value = n;
235   op.op = INT;
236   return op;
237
238  error:
239   op.op = ERROR;
240   return op;
241 }
242
243 /* Parse and convert a character constant for #if.  Understands backslash
244    escapes (\n, \031) and multibyte characters (if so configured).  */
245 static struct operation
246 parse_charconst (pfile, start, end)
247      cpp_reader *pfile;
248      U_CHAR *start;
249      U_CHAR *end;
250 {
251   struct operation op;
252   HOST_WIDEST_INT result = 0;
253   int num_chars = 0;
254   int num_bits;
255   unsigned int width = MAX_CHAR_TYPE_SIZE, mask = MAX_CHAR_TYPE_MASK;
256   int max_chars;
257   U_CHAR *ptr = start;
258
259   int c = -1;
260
261   if (*ptr == 'L')
262     {
263       ++ptr;
264       width = MAX_WCHAR_TYPE_SIZE, mask = MAX_WCHAR_TYPE_MASK;
265     }
266   max_chars = MAX_LONG_TYPE_SIZE / width;
267
268   ++ptr;  /* skip initial quote */
269
270   while (ptr < end)
271     {
272       c = *ptr++;
273       if (c == '\'')
274         break;
275       else if (c == '\\')
276         {
277           c = parse_escape (pfile, &ptr, mask);
278           if (width < HOST_BITS_PER_INT
279               && (unsigned int) c >= (unsigned int)(1 << width))
280             cpp_pedwarn (pfile,
281                          "escape sequence out of range for character");
282         }
283           
284       /* Merge character into result; ignore excess chars.  */
285       if (++num_chars <= max_chars)
286         {
287           if (width < HOST_BITS_PER_INT)
288             result = (result << width) | (c & ((1 << width) - 1));
289           else
290             result = c;
291         }
292     }
293
294   if (num_chars == 0)
295     {
296       cpp_error (pfile, "empty character constant");
297       goto error;
298     }
299   else if (c != '\'')
300     {
301       /* cpp_get_token has already emitted an error if !traditional. */
302       if (! CPP_TRADITIONAL (pfile))
303         cpp_error (pfile, "malformatted character constant");
304       goto error;
305     }
306   else if (num_chars > max_chars)
307     {
308       cpp_error (pfile, "character constant too long");
309       goto error;
310     }
311   else if (num_chars != 1 && ! CPP_TRADITIONAL (pfile))
312     cpp_warning (pfile, "multi-character character constant");
313
314   /* If char type is signed, sign-extend the constant.  */
315   num_bits = num_chars * width;
316       
317   if (cpp_defined (pfile, (const U_CHAR *)"__CHAR_UNSIGNED__",
318                    sizeof ("__CHAR_UNSIGNED__")-1)
319       || ((result >> (num_bits - 1)) & 1) == 0)
320     op.value = result & ((unsigned HOST_WIDEST_INT) ~0
321                          >> (HOST_BITS_PER_WIDEST_INT - num_bits));
322   else
323     op.value = result | ~((unsigned HOST_WIDEST_INT) ~0
324                           >> (HOST_BITS_PER_WIDEST_INT - num_bits));
325
326   /* This is always a signed type.  */
327   op.unsignedp = 0;
328   op.op = CHAR;
329   return op;
330
331  error:
332   op.op = ERROR;
333   return op;
334 }
335
336 static struct operation
337 parse_defined (pfile)
338      cpp_reader *pfile;
339 {
340   int paren = 0, len;
341   U_CHAR *tok;
342   enum cpp_ttype token;
343   struct operation op;
344   long old_written = CPP_WRITTEN (pfile);
345
346   op.unsignedp = 0;
347   op.op = INT;
348
349   pfile->no_macro_expand++;
350   token = _cpp_get_directive_token (pfile);
351   if (token == CPP_OPEN_PAREN)
352     {
353       paren++;
354       CPP_SET_WRITTEN (pfile, old_written);
355       token = _cpp_get_directive_token (pfile);
356     }
357
358   if (token != CPP_NAME)
359     goto oops;
360
361   tok = pfile->token_buffer + old_written;
362   len = CPP_PWRITTEN (pfile) - tok;
363   op.value = cpp_defined (pfile, tok, len);
364
365   if (paren)
366     {
367       if (_cpp_get_directive_token (pfile) != CPP_CLOSE_PAREN)
368         goto oops;
369     }
370   CPP_SET_WRITTEN (pfile, old_written);
371   pfile->no_macro_expand--;
372   return op;
373
374  oops:
375   CPP_SET_WRITTEN (pfile, old_written);
376   pfile->no_macro_expand--;
377   cpp_error (pfile, "'defined' without an identifier");
378
379   op.op = ERROR;
380   return op;
381 }
382
383 struct token
384 {
385   const char *operator;
386   op_t token;
387 };
388
389 static const struct token tokentab2[] =
390 {
391   {"&&", ANDAND},
392   {"||", OROR},
393   {"<<", LSH},
394   {">>", RSH},
395   {"==", EQUAL},
396   {"!=", NOTEQUAL},
397   {"<=", LEQ},
398   {">=", GEQ},
399   {"++", ERROR},
400   {"--", ERROR},
401   {NULL, ERROR}
402 };
403
404 /* Read one token.  */
405
406 static struct operation
407 lex (pfile, skip_evaluation)
408      cpp_reader *pfile;
409      int skip_evaluation;
410 {
411   const struct token *toktab;
412   enum cpp_ttype token;
413   struct operation op;
414   U_CHAR *tok_start, *tok_end;
415   long old_written;
416
417   old_written = CPP_WRITTEN (pfile);
418   token = _cpp_get_directive_token (pfile);
419
420   tok_start = pfile->token_buffer + old_written;
421   tok_end = CPP_PWRITTEN (pfile);
422   CPP_SET_WRITTEN (pfile, old_written);
423   switch (token)
424     {
425     case CPP_EOF: /* Should not happen ...  */
426     case CPP_VSPACE:
427       op.op = 0;
428       return op;
429     case CPP_NUMBER:
430       return parse_number (pfile, tok_start, tok_end);
431     case CPP_STRING:
432     case CPP_WSTRING:
433       cpp_error (pfile,
434                  "string constants are not allowed in #if expressions");
435       op.op = ERROR;
436       return op;
437
438     case CPP_CHAR:
439     case CPP_WCHAR:
440       return parse_charconst (pfile, tok_start, tok_end);
441
442     case CPP_NAME:
443       if (!strncmp (tok_start, "defined", 7))
444         return parse_defined (pfile);
445
446       op.op = INT;
447       op.unsignedp = 0;
448       op.value = 0;
449
450       if (CPP_OPTION (pfile, warn_undef) && !skip_evaluation)
451         cpp_warning (pfile, "'%.*s' is not defined",
452                      (int) (tok_end - tok_start), tok_start);
453       return op;
454
455     case CPP_ASSERTION:
456       op.op = INT;
457       op.unsignedp = 0;
458       op.value = cpp_defined (pfile, tok_start, tok_end - tok_start);
459       return op;
460
461     case CPP_OTHER:
462       /* See if it is a special token of length 2.  */
463       if (tok_start + 2 == tok_end)
464         {
465           for (toktab = tokentab2; toktab->operator != NULL; toktab++)
466             if (tok_start[0] == toktab->operator[0]
467                 && tok_start[1] == toktab->operator[1])
468                 break;
469           if (toktab->token == ERROR)
470             cpp_error (pfile, "'%s' not allowed in operand of #if",
471                        tok_start);
472           op.op = toktab->token; 
473           return op;
474         }
475       /* fall through */
476     default:
477       op.op = *tok_start;
478       return op;
479   }
480 }
481
482 /* Convert an operator ID to a string.  BUFF is a buffer at least 5
483    characters long which might be used to store the string.  */
484 /* XXX FIXME: Remove BUFF when new lexer is implemented.  */
485 static const char *
486 op_to_str (op, buff)
487      op_t op;
488      char *buff;
489 {
490   const struct token *toktab;
491
492   /* See if it is a special token of length 2.  */
493   for (toktab = tokentab2; toktab->operator != NULL; toktab++)
494     if (op == toktab->token)
495       return toktab->operator;
496
497   if (ISGRAPH (op))
498     sprintf (buff, "%c", (int) op);
499   else
500     sprintf (buff, "\\%03o", (int) op);
501   return buff;
502 }
503
504 /* Parse a C escape sequence.  STRING_PTR points to a variable
505    containing a pointer to the string to parse.  That pointer
506    is updated past the characters we use.  The value of the
507    escape sequence is returned.
508
509    A negative value means the sequence \ newline was seen,
510    which is supposed to be equivalent to nothing at all.
511
512    If \ is followed by a null character, we return a negative
513    value and leave the string pointer pointing at the null character.
514
515    If \ is followed by 000, we return 0 and leave the string pointer
516    after the zeros.  A value of 0 does not mean end of string.  */
517
518 static HOST_WIDEST_INT
519 parse_escape (pfile, string_ptr, result_mask)
520      cpp_reader *pfile;
521      U_CHAR **string_ptr;
522      HOST_WIDEST_INT result_mask;
523 {
524   register int c = *(*string_ptr)++;
525   switch (c)
526     {
527     case 'a':
528       return TARGET_BELL;
529     case 'b':
530       return TARGET_BS;
531     case 'e':
532     case 'E':
533       if (CPP_PEDANTIC (pfile))
534         cpp_pedwarn (pfile, "non-ANSI-standard escape sequence, '\\%c'", c);
535       return TARGET_ESC;
536     case 'f':
537       return TARGET_FF;
538     case 'n':
539       return TARGET_NEWLINE;
540     case 'r':
541       return TARGET_CR;
542     case 't':
543       return TARGET_TAB;
544     case 'v':
545       return TARGET_VT;
546     case '\n':
547       return -2;
548     case 0:
549       (*string_ptr)--;
550       return 0;
551       
552     case '0':
553     case '1':
554     case '2':
555     case '3':
556     case '4':
557     case '5':
558     case '6':
559     case '7':
560       {
561         register HOST_WIDEST_INT i = c - '0';
562         register int count = 0;
563         while (++count < 3)
564           {
565             c = *(*string_ptr)++;
566             if (c >= '0' && c <= '7')
567               i = (i << 3) + c - '0';
568             else
569               {
570                 (*string_ptr)--;
571                 break;
572               }
573           }
574         if (i != (i & result_mask))
575           {
576             i &= result_mask;
577             cpp_pedwarn (pfile, "octal escape sequence out of range");
578           }
579         return i;
580       }
581     case 'x':
582       {
583         register unsigned HOST_WIDEST_INT i = 0, overflow = 0;
584         register int digits_found = 0, digit;
585         for (;;)
586           {
587             c = *(*string_ptr)++;
588             if (c >= '0' && c <= '9')
589               digit = c - '0';
590             else if (c >= 'a' && c <= 'f')
591               digit = c - 'a' + 10;
592             else if (c >= 'A' && c <= 'F')
593               digit = c - 'A' + 10;
594             else
595               {
596                 (*string_ptr)--;
597                 break;
598               }
599             overflow |= i ^ (i << 4 >> 4);
600             i = (i << 4) + digit;
601             digits_found = 1;
602           }
603         if (!digits_found)
604           cpp_error (pfile, "\\x used with no following hex digits");
605         if (overflow | (i != (i & result_mask)))
606           {
607             i &= result_mask;
608             cpp_pedwarn (pfile, "hex escape sequence out of range");
609           }
610         return i;
611       }
612     default:
613       return c;
614     }
615 }
616
617 static void
618 integer_overflow (pfile)
619      cpp_reader *pfile;
620 {
621   if (CPP_PEDANTIC (pfile))
622     cpp_pedwarn (pfile, "integer overflow in preprocessor expression");
623 }
624
625 static HOST_WIDEST_INT
626 left_shift (pfile, a, unsignedp, b)
627      cpp_reader *pfile;
628      HOST_WIDEST_INT a;
629      unsigned int unsignedp;
630      unsigned HOST_WIDEST_INT b;
631 {
632   if (b >= HOST_BITS_PER_WIDEST_INT)
633     {
634       if (! unsignedp && a != 0)
635         integer_overflow (pfile);
636       return 0;
637     }
638   else if (unsignedp)
639     return (unsigned HOST_WIDEST_INT) a << b;
640   else
641     {
642       HOST_WIDEST_INT l = a << b;
643       if (l >> b != a)
644         integer_overflow (pfile);
645       return l;
646     }
647 }
648
649 static HOST_WIDEST_INT
650 right_shift (pfile, a, unsignedp, b)
651      cpp_reader *pfile ATTRIBUTE_UNUSED;
652      HOST_WIDEST_INT a;
653      unsigned int unsignedp;
654      unsigned HOST_WIDEST_INT b;
655 {
656   if (b >= HOST_BITS_PER_WIDEST_INT)
657     return unsignedp ? 0 : a >> (HOST_BITS_PER_WIDEST_INT - 1);
658   else if (unsignedp)
659     return (unsigned HOST_WIDEST_INT) a >> b;
660   else
661     return a >> b;
662 }
663 \f
664 /* Operator precedence and flags table.
665
666 After an operator is returned from the lexer, if it has priority less
667 than or equal to the operator on the top of the stack, we reduce the
668 stack by one operator and repeat the test.  Since equal priorities
669 reduce, this is naturally left-associative.
670
671 We handle right-associative operators by clearing the lower bit of all
672 left-associative operators, and setting it for right-associative ones.
673 After the reduction phase of a new operator, just before it is pushed
674 onto the stack, its RIGHT_ASSOC bit is cleared.  The effect is that
675 during the reduction phase, the current right-associative operator has
676 a priority one greater than any other operator of otherwise equal
677 precedence that has been pushed on the top of the stack.  This avoids
678 a reduction pass, and effectively makes the logic right-associative.
679
680 The remaining cases are '(' and ')'.  We handle '(' by skipping the
681 reduction phase completely.  ')' is given lower priority than
682 everything else, including '(', effectively forcing a reduction of the
683 parenthesised expression.  If there is no matching '(', the stack will
684 be reduced all the way to the beginning, exiting the parser in the
685 same way as the ultra-low priority end-of-expression dummy operator.
686 The exit code checks to see if the operator that caused it is ')', and
687 if so outputs an appropriate error message.
688
689 The parser assumes all shifted operators require a right operand
690 unless the flag NO_R_OPERAND is set, and similarly for NO_L_OPERAND.
691 These semantics are automatically checked, any extra semantics need to
692 be handled with operator-specific code.  */
693
694 #define FLAG_BITS  8
695 #define FLAG_MASK ((1 << FLAG_BITS) - 1)
696 #define PRIO_SHIFT (FLAG_BITS + 1)
697 #define EXTRACT_PRIO(cnst) (cnst >> FLAG_BITS)
698 #define EXTRACT_FLAGS(cnst) (cnst & FLAG_MASK)
699
700 /* Flags.  */
701 #define HAVE_VALUE     (1 << 0)
702 #define NO_L_OPERAND   (1 << 1)
703 #define NO_R_OPERAND   (1 << 2)
704 #define SHORT_CIRCUIT  (1 << 3)
705
706 /* Priority and flag combinations.  */
707 #define RIGHT_ASSOC         (1 << FLAG_BITS)
708 #define FORCE_REDUCE_PRIO   (0 << PRIO_SHIFT)
709 #define CLOSE_PAREN_PRIO    (1 << PRIO_SHIFT)
710 #define OPEN_PAREN_PRIO    ((2 << PRIO_SHIFT) | NO_L_OPERAND)
711 #define COMMA_PRIO          (3 << PRIO_SHIFT)
712 #define COND_PRIO          ((4 << PRIO_SHIFT) | RIGHT_ASSOC | SHORT_CIRCUIT)
713 #define COLON_PRIO         ((5 << PRIO_SHIFT) | SHORT_CIRCUIT)
714 #define OROR_PRIO          ((6 << PRIO_SHIFT) | SHORT_CIRCUIT)
715 #define ANDAND_PRIO        ((7 << PRIO_SHIFT) | SHORT_CIRCUIT)
716 #define OR_PRIO             (8 << PRIO_SHIFT)
717 #define XOR_PRIO            (9 << PRIO_SHIFT)
718 #define AND_PRIO           (10 << PRIO_SHIFT)
719 #define EQUAL_PRIO         (11 << PRIO_SHIFT)
720 #define LESS_PRIO          (12 << PRIO_SHIFT)
721 #define SHIFT_PRIO         (13 << PRIO_SHIFT)
722 #define PLUS_PRIO          (14 << PRIO_SHIFT)
723 #define MUL_PRIO           (15 << PRIO_SHIFT)
724 #define UNARY_PRIO        ((16 << PRIO_SHIFT) | RIGHT_ASSOC | NO_L_OPERAND)
725
726 #define COMPARE(OP) \
727   top->unsignedp = 0; \
728   top->value = (unsigned1 | unsigned2) \
729   ? (unsigned HOST_WIDEST_INT) v1 OP (unsigned HOST_WIDEST_INT) v2 \
730   : (v1 OP v2)
731 #define EQUALITY(OP) \
732   top->value = v1 OP v2; \
733   top->unsignedp = 0;
734 #define LOGICAL(OP) \
735   top->value = v1 OP v2; \
736   top->unsignedp = unsigned1 | unsigned2;
737
738 /* With -O2, gcc appears to produce nice code, moving the error
739    message load and subsequent jump completely out of the main path.  */
740 #define CPP_ICE(msgid) \
741   do { cpp_ice (pfile, msgid); goto syntax_error; } while(0)
742 #define SYNTAX_ERROR(msgid) \
743   do { cpp_error (pfile, msgid); goto syntax_error; } while(0)
744 #define SYNTAX_ERROR2(msgid, arg) \
745   do { cpp_error (pfile, msgid, arg); goto syntax_error; } while(0)
746
747 /* Parse and evaluate a C expression, reading from PFILE.
748    Returns the truth value of the expression.  */
749
750 int
751 _cpp_parse_expr (pfile)
752      cpp_reader *pfile;
753 {
754   /* The implementation is an operator precedence parser, i.e. a
755      bottom-up parser, using a stack for not-yet-reduced tokens.
756
757      The stack base is 'stack', and the current stack pointer is 'top'.
758      There is a stack element for each operator (only),
759      and the most recently pushed operator is 'top->op'.
760      An operand (value) is stored in the 'value' field of the stack
761      element of the operator that precedes it.
762      In that case the 'flags' field has the HAVE_VALUE flag set.  */
763
764 #define INIT_STACK_SIZE 20
765   struct operation init_stack[INIT_STACK_SIZE];
766   struct operation *stack = init_stack;
767   struct operation *limit = stack + INIT_STACK_SIZE;
768   register struct operation *top = stack + 1;
769   long old_written = CPP_WRITTEN (pfile);
770   int skip_evaluation = 0;
771   int result;
772   char buff[5];
773
774   pfile->parsing_if_directive++;
775   /* We've finished when we try to reduce this.  */
776   top->op = FINISHED;
777   /* Nifty way to catch missing '('.  */
778   top->prio = EXTRACT_PRIO(CLOSE_PAREN_PRIO);
779   /* Avoid missing right operand checks.  */
780   top->flags = NO_R_OPERAND;
781
782   for (;;)
783     {
784       unsigned int prio;
785       unsigned int flags;
786       struct operation op;
787
788       /* Read a token */
789       op = lex (pfile, skip_evaluation);
790
791       /* If the token is an operand, push its value and get next
792          token.  If it is an operator, get its priority and flags, and
793          try to reduce the expression on the stack.  */
794       switch (op.op)
795         {
796         case NAME:
797           CPP_ICE ("lex returns a NAME");
798         case ERROR:
799           goto syntax_error;
800         case '#':
801           /* We get '#' when get_directive_token hits a syntactically
802              invalid assertion predicate.  _cpp_parse_assertion has
803              already issued an error.  */
804           goto syntax_error;
805         default:
806           SYNTAX_ERROR ("invalid character in #if");
807
808         push_immediate:
809         case INT:
810         case CHAR:
811           /* Push a value onto the stack.  */
812           if (top->flags & HAVE_VALUE)
813             SYNTAX_ERROR ("missing binary operator");
814           top->value = op.value;
815           top->unsignedp = op.unsignedp;
816           top->flags |= HAVE_VALUE;
817           continue;
818
819         case '+':
820         case '-':    prio = PLUS_PRIO;  if (top->flags & HAVE_VALUE) break;
821           /* else unary; fall through */
822         case '!':
823         case '~':    prio = UNARY_PRIO;  break;
824
825         case '*':
826         case '/':
827         case '%':    prio = MUL_PRIO;  break;
828         case '<':
829         case '>':
830         case LEQ:
831         case GEQ:    prio = LESS_PRIO;  break;
832         case NOTEQUAL:
833         case EQUAL:  prio = EQUAL_PRIO;  break;
834         case LSH:
835         case RSH:    prio = SHIFT_PRIO;  break;
836         case '&':    prio = AND_PRIO;  break;
837         case '^':    prio = XOR_PRIO;  break;
838         case '|':    prio = OR_PRIO;  break;
839         case ANDAND: prio = ANDAND_PRIO;  break;
840         case OROR:   prio = OROR_PRIO;  break;
841         case ',':    prio = COMMA_PRIO;  break;
842         case '(':    prio = OPEN_PAREN_PRIO; break;
843         case ')':    prio = CLOSE_PAREN_PRIO;  break;
844         case ':':    prio = COLON_PRIO;  break;
845         case '?':    prio = COND_PRIO;  break;
846         case 0:      prio = FORCE_REDUCE_PRIO;  break;
847         }
848
849       /* Separate the operator's code into priority and flags.  */
850       flags = EXTRACT_FLAGS(prio);
851       prio = EXTRACT_PRIO(prio);
852       if (op.op == '(')
853         goto skip_reduction;
854
855       /* Check for reductions.  Then push the operator.  */
856       while (prio <= top->prio)
857         {
858           HOST_WIDEST_INT v1, v2;
859           unsigned int unsigned1, unsigned2;
860           
861           /* Most operators that can appear on the stack require a
862              right operand.  Check this before trying to reduce.  */
863           if ((top->flags & (HAVE_VALUE | NO_R_OPERAND)) == 0)
864             {
865               if (top->op == '(')
866                 SYNTAX_ERROR ("void expression between '(' and ')'");
867               else
868                 SYNTAX_ERROR2 ("operator '%s' has no right operand",
869                                op_to_str (top->op, buff));
870             }
871
872           unsigned2 = top->unsignedp, v2 = top->value;
873           top--;
874           unsigned1 = top->unsignedp, v1 = top->value;
875
876           /* Now set top->value = (top[1].op)(v1, v2); */
877           switch (top[1].op)
878             {
879             case '+':
880               if (!(top->flags & HAVE_VALUE))
881                 { /* Unary '+' */
882                   top->value = v2;
883                   top->unsignedp = unsigned2;
884                   top->flags |= HAVE_VALUE;
885                 }
886               else
887                 {
888                   top->value = v1 + v2;
889                   top->unsignedp = unsigned1 | unsigned2;
890                   if (! top->unsignedp && ! skip_evaluation
891                       && ! possible_sum_sign (v1, v2, top->value))
892                     integer_overflow (pfile);
893                 }
894               break;
895             case '-':
896               if (!(top->flags & HAVE_VALUE))
897                 { /* Unary '-' */
898                   top->value = - v2;
899                   if (!skip_evaluation && (top->value & v2) < 0
900                       && !unsigned2)
901                     integer_overflow (pfile);
902                   top->unsignedp = unsigned2;
903                   top->flags |= HAVE_VALUE;
904                 }
905               else
906                 { /* Binary '-' */
907                   top->value = v1 - v2;
908                   top->unsignedp = unsigned1 | unsigned2;
909                   if (! top->unsignedp && ! skip_evaluation
910                       && ! possible_sum_sign (top->value, v2, v1))
911                     integer_overflow (pfile);
912                 }
913               break;
914             case '*':
915               top->unsignedp = unsigned1 | unsigned2;
916               if (top->unsignedp)
917                 top->value = (unsigned HOST_WIDEST_INT) v1 * v2;
918               else if (!skip_evaluation)
919                 {
920                   top->value = v1 * v2;
921                   if (v1 && (top->value / v1 != v2
922                              || (top->value & v1 & v2) < 0))
923                     integer_overflow (pfile);
924                 }
925               break;
926             case '/':
927             case '%':
928               if (skip_evaluation)
929                 break;
930               if (v2 == 0)
931                 SYNTAX_ERROR ("division by zero in #if");
932               top->unsignedp = unsigned1 | unsigned2;
933               if (top[1].op == '/')
934                 {
935                   if (top->unsignedp)
936                     top->value = (unsigned HOST_WIDEST_INT) v1 / v2;
937                   else
938                     {
939                       top->value = v1 / v2;
940                       if ((top->value & v1 & v2) < 0)
941                         integer_overflow (pfile);
942                     }
943                 }
944               else
945                 {
946                   if (top->unsignedp)
947                     top->value = (unsigned HOST_WIDEST_INT) v1 % v2;
948                   else
949                     top->value = v1 % v2;
950                 }
951               break;
952             case '!':
953               top->value = ! v2;
954               top->unsignedp = 0;
955               top->flags |= HAVE_VALUE;
956               break;
957             case '~':
958               top->value = ~ v2;
959               top->unsignedp = unsigned2;
960               top->flags |= HAVE_VALUE;
961               break;
962             case '<':  COMPARE(<);  break;
963             case '>':  COMPARE(>);  break;
964             case LEQ:  COMPARE(<=);  break;
965             case GEQ:  COMPARE(>=);  break;
966             case EQUAL:    EQUALITY(==);  break;
967             case NOTEQUAL: EQUALITY(!=);  break;
968             case LSH:
969               if (skip_evaluation)
970                 break;
971               top->unsignedp = unsigned1;
972               if (v2 < 0 && ! unsigned2)
973                 top->value = right_shift (pfile, v1, unsigned1, -v2);
974               else
975                 top->value = left_shift (pfile, v1, unsigned1, v2);
976               break;
977             case RSH:
978               if (skip_evaluation)
979                 break;
980               top->unsignedp = unsigned1;
981               if (v2 < 0 && ! unsigned2)
982                 top->value = left_shift (pfile, v1, unsigned1, -v2);
983               else
984                 top->value = right_shift (pfile, v1, unsigned1, v2);
985               break;
986             case '&':  LOGICAL(&); break;
987             case '^':  LOGICAL(^);  break;
988             case '|':  LOGICAL(|);  break;
989             case ANDAND:
990               top->value = v1 && v2;  top->unsignedp = 0;
991               if (!v1) skip_evaluation--;
992               break;
993             case OROR:
994               top->value = v1 || v2;  top->unsignedp = 0;
995               if (v1) skip_evaluation--;
996               break;
997             case ',':
998               if (CPP_PEDANTIC (pfile))
999                 cpp_pedwarn (pfile, "comma operator in operand of #if");
1000               top->value = v2;
1001               top->unsignedp = unsigned2;
1002               break;
1003             case '?':
1004               SYNTAX_ERROR ("syntax error '?' without following ':'");
1005             case ':':
1006               if (top[0].op != '?')
1007                 SYNTAX_ERROR ("syntax error ':' without preceding '?'");
1008               top--;
1009               if (top->value) skip_evaluation--;
1010               top->value = top->value ? v1 : v2;
1011               top->unsignedp = unsigned1 | unsigned2;
1012               break;
1013             case '(':
1014               if (op.op != ')')
1015                 SYNTAX_ERROR ("missing ')' in expression");
1016               op.value = v2;
1017               op.unsignedp = unsigned2;
1018               goto push_immediate;
1019             default:
1020               SYNTAX_ERROR2 ("unimplemented operator '%s'",
1021                              op_to_str (top[1].op, buff));
1022             case FINISHED:
1023               /* Reducing this dummy operator indicates we've finished.  */
1024               if (op.op == ')')
1025                 SYNTAX_ERROR ("missing '(' in expression");
1026               goto done;
1027             }
1028         }
1029
1030       /* Handle short-circuit evaluations.  */
1031       if (flags & SHORT_CIRCUIT)
1032         switch (op.op)
1033           {
1034           case OROR:    if (top->value) skip_evaluation++; break;
1035           case ANDAND:
1036           case '?':     if (!top->value) skip_evaluation++; break;
1037           case ':':
1038             if (top[-1].value) /* Was '?' condition true?  */
1039               skip_evaluation++;
1040             else
1041               skip_evaluation--;
1042           }
1043
1044     skip_reduction:
1045       /* Check we have a left operand iff we need one.  */
1046       if (flags & NO_L_OPERAND)
1047         {
1048           if (top->flags & HAVE_VALUE)
1049             SYNTAX_ERROR2 ("missing binary operator before '%s'",
1050                            op_to_str (op.op, buff));
1051         }
1052       else
1053         {
1054           if (!(top->flags & HAVE_VALUE))
1055             SYNTAX_ERROR2 ("operator '%s' has no left operand",
1056                            op_to_str (op.op, buff));
1057         }
1058
1059       /* Check for and handle stack overflow.  */
1060       top++;
1061       if (top == limit)
1062         {
1063           struct operation *new_stack;
1064           int old_size = (char *) limit - (char *) stack;
1065           int new_size = 2 * old_size;
1066           if (stack != init_stack)
1067             new_stack = (struct operation *) xrealloc (stack, new_size);
1068           else
1069             {
1070               new_stack = (struct operation *) xmalloc (new_size);
1071               memcpy (new_stack, stack, old_size);
1072             }
1073           stack = new_stack;
1074           top = (struct operation *) ((char *) new_stack + old_size);
1075           limit = (struct operation *) ((char *) new_stack + new_size);
1076         }
1077       
1078       top->flags = flags;
1079       top->prio = prio & ~EXTRACT_PRIO(RIGHT_ASSOC);
1080       top->op = op.op;
1081     }
1082
1083  done:
1084   result = (top[1].value != 0);
1085   if (top != stack)
1086     CPP_ICE ("unbalanced stack in #if expression");
1087   else if (!(top[1].flags & HAVE_VALUE))
1088     {
1089       SYNTAX_ERROR ("#if with no expression");
1090     syntax_error:
1091       _cpp_skip_rest_of_line (pfile);
1092       result = 0;  /* Return 0 on syntax error.  */
1093     }
1094
1095   /* Free dynamic stack if we allocated one.  */
1096   if (stack != init_stack)
1097     free (stack);
1098   pfile->parsing_if_directive--;
1099   CPP_SET_WRITTEN (pfile, old_written);
1100   return result;
1101 }