OSDN Git Service

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