OSDN Git Service

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