1 /* Parse C expressions for cpplib.
2 Copyright (C) 1987, 1992, 1994, 1995, 1997, 1998, 1999, 2000, 2001,
3 2002 Free Software Foundation.
4 Contributed by Per Bothner, 1994.
6 This program is free software; you can redistribute it and/or modify it
7 under the terms of the GNU General Public License as published by the
8 Free Software Foundation; either version 2, or (at your option) any
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program; if not, write to the Free Software
18 Foundation, 59 Temple Place - Suite 330,
19 Boston, MA 02111-1307, USA. */
26 /* Yield nonzero if adding two numbers with A's and B's signs can yield a
27 number with SUM's sign, where A, B, and SUM are all C integers. */
28 #define possible_sum_sign(a, b, sum) ((((a) ^ (b)) | ~ ((a) ^ (sum))) < 0)
30 static void integer_overflow PARAMS ((cpp_reader *));
31 static HOST_WIDEST_INT left_shift PARAMS ((cpp_reader *, HOST_WIDEST_INT,
33 unsigned HOST_WIDEST_INT));
34 static HOST_WIDEST_INT right_shift PARAMS ((cpp_reader *, HOST_WIDEST_INT,
36 unsigned HOST_WIDEST_INT));
37 static struct op parse_number PARAMS ((cpp_reader *, const cpp_token *));
38 static struct op parse_defined PARAMS ((cpp_reader *));
39 static struct op lex PARAMS ((cpp_reader *));
40 static const unsigned char *op_as_text PARAMS ((cpp_reader *, enum cpp_ttype));
41 static struct op *reduce PARAMS ((cpp_reader *, struct op *, enum cpp_ttype));
46 uchar unsignedp; /* True if value should be treated as unsigned. */
47 HOST_WIDEST_INT value; /* The value logically "right" of op. */
50 /* Token type abuse. There is no "error" token, but we can't get
51 comments in #if, so we can abuse that token type. Similarly,
52 create unary plus and minus operators. */
53 #define CPP_ERROR CPP_COMMENT
54 #define CPP_UPLUS (CPP_LAST_CPP_OP + 1)
55 #define CPP_UMINUS (CPP_LAST_CPP_OP + 2)
57 /* With -O2, gcc appears to produce nice code, moving the error
58 message load and subsequent jump completely out of the main path. */
59 #define SYNTAX_ERROR(msgid) \
60 do { cpp_error (pfile, DL_ERROR, msgid); goto syntax_error; } while(0)
61 #define SYNTAX_ERROR2(msgid, arg) \
62 do { cpp_error (pfile, DL_ERROR, msgid, arg); goto syntax_error; } while(0)
66 const unsigned char s[4];
67 const unsigned char u;
68 const unsigned char l;
71 static const struct suffix vsuf_1[] = {
72 { "u", 1, 0 }, { "U", 1, 0 },
73 { "l", 0, 1 }, { "L", 0, 1 }
76 static const struct suffix vsuf_2[] = {
77 { "ul", 1, 1 }, { "UL", 1, 1 }, { "uL", 1, 1 }, { "Ul", 1, 1 },
78 { "lu", 1, 1 }, { "LU", 1, 1 }, { "Lu", 1, 1 }, { "lU", 1, 1 },
79 { "ll", 0, 2 }, { "LL", 0, 2 }
82 static const struct suffix vsuf_3[] = {
83 { "ull", 1, 2 }, { "ULL", 1, 2 }, { "uLL", 1, 2 }, { "Ull", 1, 2 },
84 { "llu", 1, 2 }, { "LLU", 1, 2 }, { "LLu", 1, 2 }, { "llU", 1, 2 }
87 /* Parse and convert what is presumably an integer in TOK. Accepts
88 decimal, hex, or octal with or without size suffixes. Returned op
89 is CPP_ERROR on error, otherwise it is a CPP_NUMBER. */
91 parse_number (pfile, tok)
96 const uchar *start = tok->val.str.text;
97 const uchar *end = start + tok->val.str.len;
98 const uchar *p = start;
100 unsigned HOST_WIDEST_INT n = 0, nd, MAX_over_base;
103 int digit, largest_digit = 0;
104 const struct suffix *sufftab;
110 if (end - start >= 3 && (p[1] == 'x' || p[1] == 'X'))
122 /* Some buggy compilers (e.g. MPW C) seem to need both casts. */
123 MAX_over_base = (((unsigned HOST_WIDEST_INT) -1)
124 / ((unsigned HOST_WIDEST_INT) base));
131 || (base == 16 && ISXDIGIT (c)))
132 digit = hex_value (c);
136 if (largest_digit < digit)
137 largest_digit = digit;
138 nd = n * base + digit;
139 overflow |= MAX_over_base < n || nd < n;
145 /* Check for a floating point constant. Note that float constants
146 with an exponent or suffix but no decimal point are technically
147 invalid (C99 6.4.4.2) but accepted elsewhere. */
148 if ((c == '.' || c == 'F' || c == 'f')
149 || (base == 10 && (c == 'E' || c == 'e')
150 && p+1 < end && (p[1] == '+' || p[1] == '-'))
151 || (base == 16 && (c == 'P' || c == 'p')
152 && p+1 < end && (p[1] == '+' || p[1] == '-')))
153 SYNTAX_ERROR ("floating point numbers are not valid in #if");
155 /* Determine the suffix. l means long, and u means unsigned.
156 See the suffix tables, above. */
159 case 1: sufftab = vsuf_1; nsuff = ARRAY_SIZE (vsuf_1); break;
160 case 2: sufftab = vsuf_2; nsuff = ARRAY_SIZE (vsuf_2); break;
161 case 3: sufftab = vsuf_3; nsuff = ARRAY_SIZE (vsuf_3); break;
162 default: goto invalid_suffix;
165 for (i = 0; i < nsuff; i++)
166 if (memcmp (p, sufftab[i].s, end - p) == 0)
170 op.unsignedp = sufftab[i].u;
172 if (CPP_WTRADITIONAL (pfile)
174 && ! cpp_sys_macro_p (pfile))
175 cpp_error (pfile, DL_WARNING, "traditional C rejects the `U' suffix");
176 if (sufftab[i].l == 2 && CPP_OPTION (pfile, pedantic)
177 && ! CPP_OPTION (pfile, c99))
178 cpp_error (pfile, DL_PEDWARN,
179 "too many 'l' suffixes in integer constant");
182 if (base <= largest_digit)
183 cpp_error (pfile, DL_PEDWARN,
184 "integer constant contains digits beyond the radix");
187 cpp_error (pfile, DL_PEDWARN, "integer constant out of range");
189 /* If too big to be signed, consider it unsigned. */
190 else if ((HOST_WIDEST_INT) n < 0 && ! op.unsignedp)
193 cpp_error (pfile, DL_WARNING,
194 "integer constant is so large that it is unsigned");
203 cpp_error (pfile, DL_ERROR, "invalid suffix '%.*s' on integer constant",
210 /* Handle meeting "defined" in a preprocessor expression. */
212 parse_defined (pfile)
216 cpp_hashnode *node = 0;
217 const cpp_token *token;
219 cpp_context *initial_context = pfile->context;
221 /* Don't expand macros. */
222 pfile->state.prevent_expansion++;
224 token = cpp_get_token (pfile);
225 if (token->type == CPP_OPEN_PAREN)
228 token = cpp_get_token (pfile);
231 if (token->type == CPP_NAME)
233 node = token->val.node;
234 if (paren && cpp_get_token (pfile)->type != CPP_CLOSE_PAREN)
236 cpp_error (pfile, DL_ERROR, "missing ')' after \"defined\"");
242 cpp_error (pfile, DL_ERROR,
243 "operator \"defined\" requires an identifier");
244 if (token->flags & NAMED_OP)
249 op.type = token->type;
250 cpp_error (pfile, DL_ERROR,
251 "(\"%s\" is an alternative token for \"%s\" in C++)",
252 cpp_token_as_text (pfile, token),
253 cpp_token_as_text (pfile, &op));
261 if (pfile->context != initial_context)
262 cpp_error (pfile, DL_WARNING,
263 "this use of \"defined\" may not be portable");
265 op.value = node->type == NT_MACRO;
269 /* A possible controlling macro of the form #if !defined ().
270 _cpp_parse_expr checks there was no other junk on the line. */
271 pfile->mi_ind_cmacro = node;
274 pfile->state.prevent_expansion--;
278 /* Read a token. The returned type is CPP_NUMBER for a valid number
279 (an interpreted preprocessing number or character constant, or the
280 result of the "defined" or "#" operators), CPP_ERROR on error,
281 CPP_EOF, or the type of an operator token. */
287 const cpp_token *token = cpp_get_token (pfile);
292 return parse_number (pfile, token);
297 unsigned int chars_seen;
299 if (token->type == CPP_CHAR)
302 op.unsignedp = WCHAR_UNSIGNED;
304 op.value = cpp_interpret_charconst (pfile, token, 1, &chars_seen);
310 SYNTAX_ERROR ("string constants are not valid in #if");
313 if (ISGRAPH (token->val.c))
314 SYNTAX_ERROR2 ("invalid character '%c' in #if", token->val.c);
316 SYNTAX_ERROR2 ("invalid character '\\%03o' in #if", token->val.c);
319 if (token->val.node == pfile->spec_nodes.n_defined)
320 return parse_defined (pfile);
321 else if (CPP_OPTION (pfile, cplusplus)
322 && (token->val.node == pfile->spec_nodes.n_true
323 || token->val.node == pfile->spec_nodes.n_false))
327 op.value = (token->val.node == pfile->spec_nodes.n_true);
329 /* Warn about use of true or false in #if when pedantic
330 and stdbool.h has not been included. */
331 if (CPP_PEDANTIC (pfile)
332 && ! cpp_defined (pfile, DSC("__bool_true_false_are_defined")))
333 cpp_error (pfile, DL_PEDWARN,
334 "ISO C++ does not permit \"%s\" in #if",
335 NODE_NAME (token->val.node));
344 if (CPP_OPTION (pfile, warn_undef) && !pfile->state.skip_eval)
345 cpp_error (pfile, DL_WARNING, "\"%s\" is not defined",
346 NODE_NAME (token->val.node));
355 if (_cpp_test_assertion (pfile, &temp))
363 if (((int) token->type > (int) CPP_EQ
364 && (int) token->type < (int) CPP_PLUS_EQ))
370 SYNTAX_ERROR2 ("\"%s\" is not valid in #if expressions",
371 cpp_token_as_text (pfile, token));
379 /* Warn if appropriate on overflow. */
381 integer_overflow (pfile)
384 if (CPP_PEDANTIC (pfile))
385 cpp_error (pfile, DL_PEDWARN,
386 "integer overflow in preprocessor expression");
389 /* Handle shifting A left by B bits. UNSIGNEDP is non-zero if A is
391 static HOST_WIDEST_INT
392 left_shift (pfile, a, unsignedp, b)
395 unsigned int unsignedp;
396 unsigned HOST_WIDEST_INT b;
398 if (b >= HOST_BITS_PER_WIDEST_INT)
400 if (! unsignedp && a != 0)
401 integer_overflow (pfile);
405 return (unsigned HOST_WIDEST_INT) a << b;
408 HOST_WIDEST_INT l = a << b;
410 integer_overflow (pfile);
415 /* Handle shifting A right by B bits. UNSIGNEDP is non-zero if A is
417 static HOST_WIDEST_INT
418 right_shift (pfile, a, unsignedp, b)
419 cpp_reader *pfile ATTRIBUTE_UNUSED;
421 unsigned int unsignedp;
422 unsigned HOST_WIDEST_INT b;
424 if (b >= HOST_BITS_PER_WIDEST_INT)
425 return unsignedp ? 0 : a >> (HOST_BITS_PER_WIDEST_INT - 1);
427 return (unsigned HOST_WIDEST_INT) a >> b;
432 /* Operator precedence and flags table.
434 After an operator is returned from the lexer, if it has priority less
435 than the operator on the top of the stack, we reduce the stack by one
436 operator and repeat the test. Since equal priorities do not reduce,
437 this is naturally right-associative.
439 We handle left-associative operators by decrementing the priority of
440 just-lexed operators by one, but retaining the priority of operators
441 already on the stack.
443 The remaining cases are '(' and ')'. We handle '(' by skipping the
444 reduction phase completely. ')' is given lower priority than
445 everything else, including '(', effectively forcing a reduction of the
446 parenthesised expression. If there is a matching '(', the routine
447 reduce() exits immediately. If the normal exit route sees a ')', then
448 there cannot have been a matching '(' and an error message is output.
450 The parser assumes all shifted operators require a left operand unless
451 the flag NO_L_OPERAND is set. These semantics are automatic; any
452 extra semantics need to be handled with operator-specific code. */
455 #define NO_L_OPERAND (1 << 0)
456 #define LEFT_ASSOC (1 << 1)
458 /* Operator to priority map. Must be in the same order as the first
459 N entries of enum cpp_ttype. */
460 static const struct operator
462 uchar prio; /* Priorities are even. */
466 /* EQ */ {0, 0}, /* Shouldn't happen. */
467 /* NOT */ {16, NO_L_OPERAND},
468 /* GREATER */ {12, LEFT_ASSOC},
469 /* LESS */ {12, LEFT_ASSOC},
470 /* PLUS */ {14, LEFT_ASSOC},
471 /* MINUS */ {14, LEFT_ASSOC},
472 /* MULT */ {15, LEFT_ASSOC},
473 /* DIV */ {15, LEFT_ASSOC},
474 /* MOD */ {15, LEFT_ASSOC},
475 /* AND */ {9, LEFT_ASSOC},
476 /* OR */ {7, LEFT_ASSOC},
477 /* XOR */ {8, LEFT_ASSOC},
478 /* RSHIFT */ {13, LEFT_ASSOC},
479 /* LSHIFT */ {13, LEFT_ASSOC},
480 /* MIN */ {10, LEFT_ASSOC}, /* C++ specific */
481 /* MAX */ {10, LEFT_ASSOC}, /* extensions */
483 /* COMPL */ {16, NO_L_OPERAND},
484 /* AND_AND */ {6, LEFT_ASSOC},
485 /* OR_OR */ {5, LEFT_ASSOC},
487 /* COLON */ {4, LEFT_ASSOC},
488 /* COMMA */ {2, LEFT_ASSOC},
489 /* OPEN_PAREN */ {1, NO_L_OPERAND},
490 /* CLOSE_PAREN */ {0, 0},
492 /* EQ_EQ */ {11, LEFT_ASSOC},
493 /* NOT_EQ */ {11, LEFT_ASSOC},
494 /* GREATER_EQ */ {12, LEFT_ASSOC},
495 /* LESS_EQ */ {12, LEFT_ASSOC},
496 /* UPLUS */ {16, NO_L_OPERAND},
497 /* UMINUS */ {16, NO_L_OPERAND}
500 #define COMPARE(OP) \
501 top->unsignedp = 0; \
502 top->value = (unsigned1 | unsigned2) \
503 ? (unsigned HOST_WIDEST_INT) v1 OP (unsigned HOST_WIDEST_INT) v2 \
505 #define EQUALITY(OP) \
506 top->value = v1 OP v2; \
508 #define BITWISE(OP) \
509 top->value = v1 OP v2; \
510 top->unsignedp = unsigned1 | unsigned2;
512 top->value = (v1 OP v2) ? v1 : v2; \
513 top->unsignedp = unsigned1 | unsigned2;
515 top->value = OP v2; \
516 top->unsignedp = unsigned2;
517 #define SHIFT(PSH, MSH) \
518 if (pfile->state.skip_eval) \
520 top->unsignedp = unsigned1; \
521 if (v2 < 0 && ! unsigned2) \
522 top->value = MSH (pfile, v1, unsigned1, -v2); \
524 top->value = PSH (pfile, v1, unsigned1, v2);
526 /* Parse and evaluate a C expression, reading from PFILE.
527 Returns the truth value of the expression.
529 The implementation is an operator precedence parser, i.e. a
530 bottom-up parser, using a stack for not-yet-reduced tokens.
532 The stack base is op_stack, and the current stack pointer is 'top'.
533 There is a stack element for each operator (only), and the most
534 recently pushed operator is 'top->op'. An operand (value) is
535 stored in the 'value' field of the stack element of the operator
538 _cpp_parse_expr (pfile)
541 struct op *top = pfile->op_stack;
542 unsigned int lex_count;
543 bool saw_leading_not, want_value = true;
545 pfile->state.skip_eval = 0;
547 /* Set up detection of #if ! defined(). */
548 pfile->mi_ind_cmacro = 0;
549 saw_leading_not = false;
552 /* Lowest priority operator prevents further reductions. */
568 /* Push a value onto the stack. */
570 SYNTAX_ERROR ("missing binary operator");
572 top->value = op.value;
573 top->unsignedp = op.unsignedp;
577 saw_leading_not = lex_count == 1;
591 /* Check we have a value or operator as appropriate. */
592 if (optab[op.op].flags & NO_L_OPERAND)
595 SYNTAX_ERROR2 ("missing binary operator before '%s'",
596 op_as_text (pfile, op.op));
600 if (op.op == CPP_CLOSE_PAREN)
602 if (top->op == CPP_OPEN_PAREN)
603 SYNTAX_ERROR ("void expression between '(' and ')'");
605 else if (top->op == CPP_EOF)
606 SYNTAX_ERROR ("#if with no expression");
607 if (top->op != CPP_EOF && top->op != CPP_OPEN_PAREN)
608 SYNTAX_ERROR2 ("operator '%s' has no right operand",
609 op_as_text (pfile, top->op));
612 top = reduce (pfile, top, op.op);
618 case CPP_CLOSE_PAREN:
624 pfile->state.skip_eval++;
629 pfile->state.skip_eval++;
632 if (top[-1].value) /* Was '?' condition true? */
633 pfile->state.skip_eval++;
635 pfile->state.skip_eval--;
642 /* Check for and handle stack overflow. */
643 if (++top == pfile->op_limit)
644 top = _cpp_expand_op_stack (pfile);
650 /* The controlling macro expression is only valid if we called lex 3
651 times: <!> <defined expression> and <EOF>. push_conditional ()
652 checks that we are at top-of-file. */
653 if (pfile->mi_ind_cmacro && !(saw_leading_not && lex_count == 3))
654 pfile->mi_ind_cmacro = 0;
656 if (top != pfile->op_stack)
658 cpp_error (pfile, DL_ICE, "unbalanced stack in #if");
660 return false; /* Return false on syntax error. */
663 return top->value != 0;
666 /* Reduce the operator / value stack if possible, in preparation for
667 pushing operator OP. Returns NULL on error, otherwise the top of
670 reduce (pfile, top, op)
677 if (op == CPP_OPEN_PAREN)
680 /* Decrement the priority of left-associative operators to force a
681 reduction with operators of otherwise equal priority. */
682 prio = optab[op].prio - ((optab[op].flags & LEFT_ASSOC) != 0);
683 while (prio < optab[top->op].prio)
685 HOST_WIDEST_INT v1, v2;
686 unsigned int unsigned1, unsigned2;
688 unsigned2 = top->unsignedp, v2 = top->value;
690 unsigned1 = top->unsignedp, v1 = top->value;
692 /* Now set top->value = (top[1].op)(v1, v2); */
696 cpp_error (pfile, DL_ICE, "impossible operator '%s'",
697 op_as_text (pfile, top[1].op));
700 case CPP_NOT: UNARY(!); break;
701 case CPP_COMPL: UNARY(~); break;
702 case CPP_LESS: COMPARE(<); break;
703 case CPP_GREATER: COMPARE(>); break;
704 case CPP_LESS_EQ: COMPARE(<=); break;
705 case CPP_GREATER_EQ: COMPARE(>=); break;
706 case CPP_EQ_EQ: EQUALITY(==); break;
707 case CPP_NOT_EQ: EQUALITY(!=); break;
708 case CPP_AND: BITWISE(&); break;
709 case CPP_XOR: BITWISE(^); break;
710 case CPP_OR: BITWISE(|); break;
711 case CPP_LSHIFT: SHIFT(left_shift, right_shift); break;
712 case CPP_RSHIFT: SHIFT(right_shift, left_shift); break;
713 case CPP_MIN: MINMAX(<); break;
714 case CPP_MAX: MINMAX(>); break;
717 /* Can't use UNARY(+) because K+R C did not have unary
718 plus. Can't use UNARY() because some compilers object
719 to the empty argument. */
721 top->unsignedp = unsigned2;
722 if (CPP_WTRADITIONAL (pfile))
723 cpp_error (pfile, DL_WARNING,
724 "traditional C rejects the unary plus operator");
728 if (!pfile->state.skip_eval && (top->value & v2) < 0 && !unsigned2)
729 integer_overflow (pfile);
733 top->value = v1 + v2;
734 top->unsignedp = unsigned1 | unsigned2;
735 if (! top->unsignedp && ! pfile->state.skip_eval
736 && ! possible_sum_sign (v1, v2, top->value))
737 integer_overflow (pfile);
740 top->value = v1 - v2;
741 top->unsignedp = unsigned1 | unsigned2;
742 if (! top->unsignedp && ! pfile->state.skip_eval
743 && ! possible_sum_sign (top->value, v2, v1))
744 integer_overflow (pfile);
747 top->unsignedp = unsigned1 | unsigned2;
749 top->value = (unsigned HOST_WIDEST_INT) v1 * v2;
750 else if (!pfile->state.skip_eval)
752 top->value = v1 * v2;
753 if (v1 && (top->value / v1 != v2
754 || (top->value & v1 & v2) < 0))
755 integer_overflow (pfile);
760 if (pfile->state.skip_eval)
764 cpp_error (pfile, DL_ERROR, "division by zero in #if");
767 top->unsignedp = unsigned1 | unsigned2;
768 if (top[1].op == CPP_DIV)
771 top->value = (unsigned HOST_WIDEST_INT) v1 / v2;
774 top->value = v1 / v2;
775 if ((top->value & v1 & v2) < 0)
776 integer_overflow (pfile);
782 top->value = (unsigned HOST_WIDEST_INT) v1 % v2;
784 top->value = v1 % v2;
789 top->value = v1 || v2;
791 if (v1) pfile->state.skip_eval--;
794 top->value = v1 && v2;
796 if (!v1) pfile->state.skip_eval--;
799 if (CPP_PEDANTIC (pfile))
800 cpp_error (pfile, DL_PEDWARN,
801 "comma operator in operand of #if");
803 top->unsignedp = unsigned2;
806 cpp_error (pfile, DL_ERROR, "'?' without following ':'");
809 if (top->op != CPP_QUERY)
811 cpp_error (pfile, DL_ERROR, " ':' without preceding '?'");
815 if (top->value) pfile->state.skip_eval--;
816 top->value = top->value ? v1 : v2;
817 top->unsignedp = unsigned1 | unsigned2;
820 if (op != CPP_CLOSE_PAREN)
822 cpp_error (pfile, DL_ERROR, "missing ')' in expression");
826 top->unsignedp = unsigned2;
831 if (op == CPP_CLOSE_PAREN)
833 cpp_error (pfile, DL_ERROR, "missing '(' in expression");
840 /* Returns the position of the old top of stack after expansion. */
842 _cpp_expand_op_stack (pfile)
845 size_t n = (size_t) (pfile->op_limit - pfile->op_stack);
847 pfile->op_stack = (struct op *) xrealloc (pfile->op_stack,
848 (n * 2 + 20) * sizeof (struct op));
850 return pfile->op_stack + n;
853 /* Output OP as text for diagnostics. */
854 static const unsigned char *
855 op_as_text (pfile, op)
863 else if (op == CPP_UMINUS)
868 return cpp_token_as_text (pfile, &token);