cexp.y 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  1. /* Parse C expressions for CCCP.
  2. Copyright (C) 1987 Free Software Foundation.
  3. NO WARRANTY
  4. BECAUSE THIS PROGRAM IS LICENSED FREE OF CHARGE, WE PROVIDE ABSOLUTELY
  5. NO WARRANTY, TO THE EXTENT PERMITTED BY APPLICABLE STATE LAW. EXCEPT
  6. WHEN OTHERWISE STATED IN WRITING, FREE SOFTWARE FOUNDATION, INC,
  7. RICHARD M. STALLMAN AND/OR OTHER PARTIES PROVIDE THIS PROGRAM "AS IS"
  8. WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
  9. BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  10. FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY
  11. AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE
  12. DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR
  13. CORRECTION.
  14. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW WILL RICHARD M.
  15. STALLMAN, THE FREE SOFTWARE FOUNDATION, INC., AND/OR ANY OTHER PARTY
  16. WHO MAY MODIFY AND REDISTRIBUTE THIS PROGRAM AS PERMITTED BELOW, BE
  17. LIABLE TO YOU FOR DAMAGES, INCLUDING ANY LOST PROFITS, LOST MONIES, OR
  18. OTHER SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
  19. USE OR INABILITY TO USE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR
  20. DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY THIRD PARTIES OR
  21. A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS) THIS
  22. PROGRAM, EVEN IF YOU HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH
  23. DAMAGES, OR FOR ANY CLAIM BY ANY OTHER PARTY.
  24. GENERAL PUBLIC LICENSE TO COPY
  25. 1. You may copy and distribute verbatim copies of this source file
  26. as you receive it, in any medium, provided that you conspicuously and
  27. appropriately publish on each copy a valid copyright notice "Copyright
  28. (C) 1987 Free Software Foundation"; and include following the
  29. copyright notice a verbatim copy of the above disclaimer of warranty
  30. and of this License. You may charge a distribution fee for the
  31. physical act of transferring a copy.
  32. 2. You may modify your copy or copies of this source file or
  33. any portion of it, and copy and distribute such modifications under
  34. the terms of Paragraph 1 above, provided that you also do the following:
  35. a) cause the modified files to carry prominent notices stating
  36. that you changed the files and the date of any change; and
  37. b) cause the whole of any work that you distribute or publish,
  38. that in whole or in part contains or is a derivative of this
  39. program or any part thereof, to be licensed at no charge to all
  40. third parties on terms identical to those contained in this
  41. License Agreement (except that you may choose to grant more extensive
  42. warranty protection to some or all third parties, at your option).
  43. c) You may charge a distribution fee for the physical act of
  44. transferring a copy, and you may at your option offer warranty
  45. protection in exchange for a fee.
  46. Mere aggregation of another unrelated program with this program (or its
  47. derivative) on a volume of a storage or distribution medium does not bring
  48. the other program under the scope of these terms.
  49. 3. You may copy and distribute this program (or a portion or derivative
  50. of it, under Paragraph 2) in object code or executable form under the terms
  51. of Paragraphs 1 and 2 above provided that you also do one of the following:
  52. a) accompany it with the complete corresponding machine-readable
  53. source code, which must be distributed under the terms of
  54. Paragraphs 1 and 2 above; or,
  55. b) accompany it with a written offer, valid for at least three
  56. years, to give any third party free (except for a nominal
  57. shipping charge) a complete machine-readable copy of the
  58. corresponding source code, to be distributed under the terms of
  59. Paragraphs 1 and 2 above; or,
  60. c) accompany it with the information you received as to where the
  61. corresponding source code may be obtained. (This alternative is
  62. allowed only for noncommercial distribution and only if you
  63. received the program in object code or executable form alone.)
  64. For an executable file, complete source code means all the source code for
  65. all modules it contains; but, as a special exception, it need not include
  66. source code for modules which are standard libraries that accompany the
  67. operating system on which the executable file runs.
  68. 4. You may not copy, sublicense, distribute or transfer this program
  69. except as expressly provided under this License Agreement. Any attempt
  70. otherwise to copy, sublicense, distribute or transfer this program is void and
  71. your rights to use the program under this License agreement shall be
  72. automatically terminated. However, parties who have received computer
  73. software programs from you with this License Agreement will not have
  74. their licenses terminated so long as such parties remain in full compliance.
  75. 5. If you wish to incorporate parts of this program into other free
  76. programs whose distribution conditions are different, write to the Free
  77. Software Foundation at 675 Mass Ave, Cambridge, MA 02139. We have not yet
  78. worked out a simple rule that can be stated here, but we will often permit
  79. this. We will be guided by the two goals of preserving the free status of
  80. all derivatives of our free software and of promoting the sharing and reuse of
  81. software.
  82. In other words, you are welcome to use, share and improve this program.
  83. You are forbidden to forbid anyone else to use, share and improve
  84. what you give them. Help stamp out software-hoarding!
  85. Adapted from expread.y of GDB by Paul Rubin, July 1986.
  86. /* Parse a C expression from text in a string */
  87. %{
  88. #include <setjmp.h>
  89. /* #define YYDEBUG 1 */
  90. static int yylex ();
  91. static yyerror ();
  92. int expression_value;
  93. static jmp_buf parse_return_error;
  94. /* some external tables of character types */
  95. extern unsigned char is_idstart[], is_idchar[];
  96. %}
  97. %union {
  98. long lval;
  99. int voidval;
  100. char *sval;
  101. }
  102. %type <lval> exp exp1 start
  103. %token <lval> INT CHAR
  104. %token <sval> NAME
  105. %token <lval> ERROR
  106. %right '?' ':'
  107. %left ','
  108. %left OR
  109. %left AND
  110. %left '|'
  111. %left '^'
  112. %left '&'
  113. %left EQUAL NOTEQUAL
  114. %left '<' '>' LEQ GEQ
  115. %left LSH RSH
  116. %left '+' '-'
  117. %left '*' '/' '%'
  118. %right UNARY
  119. /* %expect 40 */
  120. %%
  121. start : exp1
  122. { expression_value = $1; }
  123. ;
  124. /* Expressions, including the comma operator. */
  125. exp1 : exp
  126. | exp1 ',' exp
  127. { $$ = $3; }
  128. ;
  129. /* Expressions, not including the comma operator. */
  130. exp : '-' exp %prec UNARY
  131. { $$ = - $2; }
  132. | '!' exp %prec UNARY
  133. { $$ = ! $2; }
  134. | '~' exp %prec UNARY
  135. { $$ = ~ $2; }
  136. | '(' exp1 ')'
  137. { $$ = $2; }
  138. ;
  139. /* Binary operators in order of decreasing precedence. */
  140. exp : exp '*' exp
  141. { $$ = $1 * $3; }
  142. | exp '/' exp
  143. { $$ = $1 / $3; }
  144. | exp '%' exp
  145. { $$ = $1 % $3; }
  146. | exp '+' exp
  147. { $$ = $1 + $3; }
  148. | exp '-' exp
  149. { $$ = $1 - $3; }
  150. | exp LSH exp
  151. { $$ = $1 << $3; }
  152. | exp RSH exp
  153. { $$ = $1 >> $3; }
  154. | exp EQUAL exp
  155. { $$ = ($1 == $3); }
  156. | exp NOTEQUAL exp
  157. { $$ = ($1 != $3); }
  158. | exp LEQ exp
  159. { $$ = ($1 <= $3); }
  160. | exp GEQ exp
  161. { $$ = ($1 >= $3); }
  162. | exp '<' exp
  163. { $$ = ($1 < $3); }
  164. | exp '>' exp
  165. { $$ = ($1 > $3); }
  166. | exp '&' exp
  167. { $$ = ($1 & $3); }
  168. | exp '^' exp
  169. { $$ = ($1 ^ $3); }
  170. | exp '|' exp
  171. { $$ = ($1 | $3); }
  172. | exp AND exp
  173. { $$ = ($1 && $3); }
  174. | exp OR exp
  175. { $$ = ($1 || $3); }
  176. | exp '?' exp ':' exp
  177. { $$ = $1 ? $3 : $5; }
  178. | INT
  179. { $$ = yylval.lval; }
  180. | CHAR
  181. { $$ = yylval.lval; }
  182. | NAME
  183. { $$ = 0; }
  184. ;
  185. %%
  186. /* During parsing of a C expression, the pointer to the next character
  187. is in this variable. */
  188. static char *lexptr;
  189. /* Take care of parsing a number (anything that starts with a digit).
  190. Set yylval and return the token type; update lexptr.
  191. LEN is the number of characters in it. */
  192. /* maybe needs to actually deal with floating point numbers */
  193. static int
  194. parse_number (olen)
  195. int olen;
  196. {
  197. register char *p = lexptr;
  198. register long n = 0;
  199. register int c;
  200. register int base = 10;
  201. register len = olen;
  202. char *err_copy;
  203. extern double atof ();
  204. for (c = 0; c < len; c++)
  205. if (p[c] == '.') {
  206. /* It's a float since it contains a point. */
  207. yyerror ("floating point numbers not allowed in #if expressions");
  208. return ERROR;
  209. /* ****************
  210. yylval.dval = atof (p);
  211. lexptr += len;
  212. return FLOAT;
  213. **************** */
  214. }
  215. if (len >= 3 && (!strncmp (p, "0x", 2) || !strncmp (p, "0X", 2))) {
  216. p += 2;
  217. base = 16;
  218. len -= 2;
  219. }
  220. else if (*p == '0')
  221. base = 8;
  222. while (len-- > 0) {
  223. c = *p++;
  224. n *= base;
  225. if (c >= '0' && c <= '9')
  226. n += c - '0';
  227. else {
  228. if (c >= 'A' && c <= 'Z') c += 'a' - 'A';
  229. if (base == 16 && c >= 'a' && c <= 'f')
  230. n += c - 'a' + 10;
  231. else if (len == 0 && c == 'l')
  232. ;
  233. else {
  234. yyerror ("Invalid number in #if expression");
  235. return ERROR;
  236. }
  237. }
  238. }
  239. lexptr = p;
  240. yylval.lval = n;
  241. return INT;
  242. }
  243. struct token {
  244. char *operator;
  245. int token;
  246. };
  247. #define NULL 0
  248. static struct token tokentab2[] = {
  249. {"&&", AND},
  250. {"||", OR},
  251. {"<<", LSH},
  252. {">>", RSH},
  253. {"==", EQUAL},
  254. {"!=", NOTEQUAL},
  255. {"<=", LEQ},
  256. {">=", GEQ},
  257. {NULL, ERROR}
  258. };
  259. /* Read one token, getting characters through lexptr. */
  260. static int
  261. yylex ()
  262. {
  263. register int c;
  264. register int namelen;
  265. register char *tokstart;
  266. register struct token *toktab;
  267. retry:
  268. tokstart = lexptr;
  269. c = *tokstart;
  270. /* See if it is a special token of length 2. */
  271. for (toktab = tokentab2; toktab->operator != NULL; toktab++)
  272. if (c == *toktab->operator && tokstart[1] == toktab->operator[1]) {
  273. lexptr += 2;
  274. return toktab->token;
  275. }
  276. switch (c) {
  277. case 0:
  278. return 0;
  279. case ' ':
  280. case '\t':
  281. case '\n':
  282. lexptr++;
  283. goto retry;
  284. case '\'':
  285. lexptr++;
  286. c = *lexptr++;
  287. if (c == '\\')
  288. c = parse_escape (&lexptr);
  289. yylval.lval = c;
  290. c = *lexptr++;
  291. if (c != '\'') {
  292. yyerror ("Invalid character constant in #if");
  293. return ERROR;
  294. }
  295. return CHAR;
  296. /* some of these chars are invalid in constant expressions;
  297. maybe do something about them later */
  298. case '/':
  299. case '+':
  300. case '-':
  301. case '*':
  302. case '%':
  303. case '|':
  304. case '&':
  305. case '^':
  306. case '~':
  307. case '!':
  308. case '@':
  309. case '<':
  310. case '>':
  311. case '(':
  312. case ')':
  313. case '[':
  314. case ']':
  315. case '.':
  316. case '?':
  317. case ':':
  318. case '=':
  319. case '{':
  320. case '}':
  321. case ',':
  322. lexptr++;
  323. return c;
  324. case '"':
  325. yyerror ("double quoted strings not allowed in #if expressions");
  326. return ERROR;
  327. }
  328. if (c >= '0' && c <= '9') {
  329. /* It's a number */
  330. for (namelen = 0;
  331. c = tokstart[namelen], is_idchar[c] || c == '.';
  332. namelen++)
  333. ;
  334. return parse_number (namelen);
  335. }
  336. if (!is_idstart[c]) {
  337. yyerror ("Invalid token in expression");
  338. return ERROR;
  339. }
  340. /* It is a name. See how long it is. */
  341. for (namelen = 0; is_idchar[tokstart[namelen]]; namelen++)
  342. ;
  343. lexptr += namelen;
  344. return NAME;
  345. }
  346. /* Parse a C escape sequence. STRING_PTR points to a variable
  347. containing a pointer to the string to parse. That pointer
  348. is updated past the characters we use. The value of the
  349. escape sequence is returned.
  350. A negative value means the sequence \ newline was seen,
  351. which is supposed to be equivalent to nothing at all.
  352. If \ is followed by a null character, we return a negative
  353. value and leave the string pointer pointing at the null character.
  354. If \ is followed by 000, we return 0 and leave the string pointer
  355. after the zeros. A value of 0 does not mean end of string. */
  356. static int
  357. parse_escape (string_ptr)
  358. char **string_ptr;
  359. {
  360. register int c = *(*string_ptr)++;
  361. switch (c)
  362. {
  363. case 'a':
  364. return '\a';
  365. case 'b':
  366. return '\b';
  367. case 'e':
  368. return 033;
  369. case 'f':
  370. return '\f';
  371. case 'n':
  372. return '\n';
  373. case 'r':
  374. return '\r';
  375. case 't':
  376. return '\t';
  377. case 'v':
  378. return '\v';
  379. case '\n':
  380. return -2;
  381. case 0:
  382. (*string_ptr)--;
  383. return 0;
  384. case '^':
  385. c = *(*string_ptr)++;
  386. if (c == '\\')
  387. c = parse_escape (string_ptr);
  388. if (c == '?')
  389. return 0177;
  390. return (c & 0200) | (c & 037);
  391. case '0':
  392. case '1':
  393. case '2':
  394. case '3':
  395. case '4':
  396. case '5':
  397. case '6':
  398. case '7':
  399. {
  400. register int i = c - '0';
  401. register int count = 0;
  402. while (++count < 3)
  403. {
  404. if ((c = *(*string_ptr)++) >= '0' && c <= '7')
  405. {
  406. i *= 8;
  407. i += c - '0';
  408. }
  409. else
  410. {
  411. (*string_ptr)--;
  412. break;
  413. }
  414. }
  415. return i;
  416. }
  417. default:
  418. return c;
  419. }
  420. }
  421. static
  422. yyerror (s)
  423. char *s;
  424. {
  425. error (s);
  426. longjmp (parse_return_error, 1);
  427. }
  428. /* This page contains the entry point to this file. */
  429. /* Parse STRING as an expression, and complain if this fails
  430. to use up all of the contents of STRING. */
  431. /* We do not support C comments. They should be removed before
  432. this function is called. */
  433. int
  434. parse_c_expression (string)
  435. char *string;
  436. {
  437. lexptr = string;
  438. if (lexptr == 0 || *lexptr == 0) {
  439. error ("empty #if expression");
  440. return 0; /* don't include the #if group */
  441. }
  442. /* if there is some sort of scanning error, just return 0 and assume
  443. the parsing routine has printed an error message somewhere.
  444. there is surely a better thing to do than this. */
  445. if (setjmp(parse_return_error))
  446. return 0;
  447. if (yyparse ())
  448. return 0; /* actually this is never reached
  449. the way things stand. */
  450. if (*lexptr)
  451. error ("Junk after end of expression.");
  452. return expression_value; /* set by yyparse() */
  453. }
  454. #ifdef TEST_EXP_READER
  455. /* main program, for testing purposes. */
  456. main()
  457. {
  458. int n;
  459. char buf[1024];
  460. extern int yydebug;
  461. /*
  462. yydebug = 1;
  463. */
  464. initialize_random_junk ();
  465. for (;;) {
  466. printf("enter expression: ");
  467. n = 0;
  468. while ((buf[n] = getchar()) != '\n')
  469. n++;
  470. buf[n] = '\0';
  471. printf("parser returned %d\n", parse_c_expression(buf));
  472. }
  473. }
  474. /* table to tell if char can be part of a C identifier. */
  475. char is_idchar[256];
  476. /* table to tell if char can be first char of a c identifier. */
  477. char is_idstart[256];
  478. /* table to tell if c is horizontal space. isspace() thinks that
  479. newline is space; this is not a good idea for this program. */
  480. char is_hor_space[256];
  481. /*
  482. * initialize random junk in the hash table and maybe other places
  483. */
  484. initialize_random_junk()
  485. {
  486. register int i;
  487. /*
  488. * Set up is_idchar and is_idstart tables. These should be
  489. * faster than saying (is_alpha(c) || c == '_'), etc.
  490. * Must do set up these things before calling any routines tthat
  491. * refer to them.
  492. */
  493. for (i = 'a'; i <= 'z'; i++) {
  494. ++is_idchar[i - 'a' + 'A'];
  495. ++is_idchar[i];
  496. ++is_idstart[i - 'a' + 'A'];
  497. ++is_idstart[i];
  498. }
  499. for (i = '0'; i <= '9'; i++)
  500. ++is_idchar[i];
  501. ++is_idchar['_'];
  502. ++is_idstart['_'];
  503. #ifdef DOLLARS_IN_IDENTIFIERS
  504. ++is_idchar['$'];
  505. ++is_idstart['$'];
  506. #endif
  507. /* horizontal space table */
  508. ++is_hor_space[' '];
  509. ++is_hor_space['\t'];
  510. }
  511. error (msg)
  512. {
  513. printf("error: %s\n", msg);
  514. }
  515. #endif