OSDN Git Service

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