OSDN Git Service

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