OSDN Git Service

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