cexp.y 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  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
  42. extensive warranty protection to 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. 3. You may copy and distribute this program or any portion of it in
  47. compiled, executable or object code form under the terms of Paragraphs
  48. 1 and 2 above provided that you do the following:
  49. a) cause each such copy to be accompanied by the
  50. corresponding machine-readable source code, which must
  51. be distributed under the terms of Paragraphs 1 and 2 above; or,
  52. b) cause each such copy to be accompanied by a
  53. written offer, with no time limit, to give any third party
  54. free (except for a nominal shipping charge) a machine readable
  55. copy of the corresponding source code, to be distributed
  56. under the terms of Paragraphs 1 and 2 above; or,
  57. c) in the case of a recipient of this program in compiled, executable
  58. or object code form (without the corresponding source code) you
  59. shall cause copies you distribute to be accompanied by a copy
  60. of the written offer of source code which you received along
  61. with the copy you received.
  62. 4. You may not copy, sublicense, distribute or transfer this program
  63. except as expressly provided under this License Agreement. Any attempt
  64. otherwise to copy, sublicense, distribute or transfer this program is void and
  65. your rights to use the program under this License agreement shall be
  66. automatically terminated. However, parties who have received computer
  67. software programs from you with this License Agreement will not have
  68. their licenses terminated so long as such parties remain in full compliance.
  69. 5. If you wish to incorporate parts of this program into other free
  70. programs whose distribution conditions are different, write to the Free
  71. Software Foundation at 1000 Mass Ave, Cambridge, MA 02138. We have not yet
  72. worked out a simple rule that can be stated here, but we will often permit
  73. this. We will be guided by the two goals of preserving the free status of
  74. all derivatives our free software and of promoting the sharing and reuse of
  75. software.
  76. In other words, you are welcome to use, share and improve this program.
  77. You are forbidden to forbid anyone else to use, share and improve
  78. what you give them. Help stamp out software-hoarding!
  79. Adapted from expread.y of GDB by Paul Rubin, July 1986.
  80. /* Parse a C expression from text in a string */
  81. %{
  82. #include <setjmp.h>
  83. /* #define YYDEBUG 1 */
  84. static int yylex ();
  85. static yyerror ();
  86. int expression_value;
  87. static jmp_buf parse_return_error;
  88. /* some external tables of character types */
  89. extern unsigned char is_idstart[], is_idchar[];
  90. %}
  91. %union {
  92. long lval;
  93. int voidval;
  94. char *sval;
  95. }
  96. %type <lval> exp exp1 start
  97. %token <lval> INT CHAR
  98. %token <sval> NAME
  99. %token <lval> ERROR
  100. %left ','
  101. %left OR
  102. %left AND
  103. %left '|'
  104. %left '^'
  105. %left '&'
  106. %left EQUAL NOTEQUAL
  107. %left '<' '>' LEQ GEQ
  108. %left LSH RSH
  109. %left '+' '-'
  110. %left '*' '/' '%'
  111. %right UNARY
  112. %%
  113. start : exp1
  114. { expression_value = $1; }
  115. ;
  116. /* Expressions, including the comma operator. */
  117. exp1 : exp
  118. | exp1 ',' exp
  119. { $$ = $3; }
  120. ;
  121. /* Expressions, not including the comma operator. */
  122. exp : '-' exp %prec UNARY
  123. { $$ = - $2; }
  124. | '!' exp %prec UNARY
  125. { $$ = ! $2; }
  126. | '~' exp %prec UNARY
  127. { $$ = ~ $2; }
  128. | '(' exp1 ')'
  129. { $$ = $2; }
  130. ;
  131. /* Binary operators in order of decreasing precedence. */
  132. exp : exp '*' exp
  133. { $$ = $1 * $3; }
  134. | exp '/' exp
  135. { $$ = $1 / $3; }
  136. | exp '%' exp
  137. { $$ = $1 % $3; }
  138. | exp '+' exp
  139. { $$ = $1 + $3; }
  140. | exp '-' exp
  141. { $$ = $1 - $3; }
  142. | exp LSH exp
  143. { $$ = $1 << $3; }
  144. | exp RSH exp
  145. { $$ = $1 >> $3; }
  146. | exp EQUAL exp
  147. { $$ = ($1 == $3); }
  148. | exp NOTEQUAL exp
  149. { $$ = ($1 != $3); }
  150. | exp LEQ exp
  151. { $$ = ($1 <= $3); }
  152. | exp GEQ exp
  153. { $$ = ($1 >= $3); }
  154. | exp '<' exp
  155. { $$ = ($1 < $3); }
  156. | exp '>' exp
  157. { $$ = ($1 > $3); }
  158. | exp '&' exp
  159. { $$ = ($1 & $3); }
  160. | exp '^' exp
  161. { $$ = ($1 ^ $3); }
  162. | exp '|' exp
  163. { $$ = ($1 | $3); }
  164. | exp AND exp
  165. { $$ = ($1 && $3); }
  166. | exp OR exp
  167. { $$ = ($1 || $3); }
  168. | exp '?' exp ':' exp
  169. { $$ = $1 ? $3 : $5; }
  170. | INT
  171. { $$ = yylval.lval; }
  172. | CHAR
  173. { $$ = yylval.lval; }
  174. | NAME
  175. { $$ = 0; }
  176. ;
  177. %%
  178. /* During parsing of a C expression, the pointer to the next character
  179. is in this variable. */
  180. static char *lexptr;
  181. /* Take care of parsing a number (anything that starts with a digit).
  182. Set yylval and return the token type; update lexptr.
  183. LEN is the number of characters in it. */
  184. /* maybe needs to actually deal with floating point numbers */
  185. static int
  186. parse_number (olen)
  187. int olen;
  188. {
  189. register char *p = lexptr;
  190. register long n = 0;
  191. register int c;
  192. register int base = 10;
  193. register len = olen;
  194. char *err_copy;
  195. extern double atof ();
  196. for (c = 0; c < len; c++)
  197. if (p[c] == '.') {
  198. /* It's a float since it contains a point. */
  199. yyerror ("floating point numbers not allowed in #if expressions");
  200. return ERROR;
  201. /* ****************
  202. yylval.dval = atof (p);
  203. lexptr += len;
  204. return FLOAT;
  205. **************** */
  206. }
  207. if (len >= 3 && (!strncmp (p, "0x", 2) || !strncmp (p, "0X", 2))) {
  208. p += 2;
  209. base = 16;
  210. len -= 2;
  211. }
  212. else if (*p == '0')
  213. base = 8;
  214. while (len-- > 0) {
  215. c = *p++;
  216. n *= base;
  217. if (c >= '0' && c <= '9')
  218. n += c - '0';
  219. else {
  220. if (c >= 'A' && c <= 'Z') c += 'a' - 'A';
  221. if (base == 16 && c >= 'a' && c <= 'f')
  222. n += c - 'a' + 10;
  223. else if (len == 0 && c == 'l')
  224. ;
  225. else {
  226. yyerror ("Invalid number in #if expression");
  227. return ERROR;
  228. }
  229. }
  230. }
  231. lexptr = p;
  232. yylval.lval = n;
  233. return INT;
  234. }
  235. struct token {
  236. char *operator;
  237. int token;
  238. };
  239. #define NULL 0
  240. static struct token tokentab2[] = {
  241. {"&&", AND},
  242. {"||", OR},
  243. {"<<", LSH},
  244. {">>", RSH},
  245. {"==", EQUAL},
  246. {"!=", NOTEQUAL},
  247. {"<=", LEQ},
  248. {">=", GEQ},
  249. {NULL, ERROR}
  250. };
  251. /* Read one token, getting characters through lexptr. */
  252. static int
  253. yylex ()
  254. {
  255. register int c;
  256. register int namelen;
  257. register char *tokstart;
  258. register struct token *toktab;
  259. retry:
  260. tokstart = lexptr;
  261. c = *tokstart;
  262. /* See if it is a special token of length 2. */
  263. for (toktab = tokentab2; toktab->operator != NULL; toktab++)
  264. if (c == *toktab->operator && tokstart[1] == toktab->operator[1]) {
  265. lexptr += 2;
  266. return toktab->token;
  267. }
  268. switch (c) {
  269. case 0:
  270. return 0;
  271. case ' ':
  272. case '\t':
  273. case '\n':
  274. lexptr++;
  275. goto retry;
  276. case '\'':
  277. lexptr++;
  278. c = *lexptr++;
  279. if (c == '\\')
  280. c = parse_escape (&lexptr);
  281. yylval.lval = c;
  282. c = *lexptr++;
  283. if (c != '\'') {
  284. yyerror ("Invalid character constant in #if");
  285. return ERROR;
  286. }
  287. return CHAR;
  288. case '/': /* possible comment */
  289. if (*lexptr != '*')
  290. return c;
  291. for (;;) {
  292. while (*lexptr != '\0') {
  293. if (*lexptr++ == '*' && *lexptr == '/') {
  294. lexptr++;
  295. goto retry;
  296. }
  297. }
  298. }
  299. /* some of these chars are invalid in constant expressions;
  300. maybe do something about them later */
  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. case '}':
  323. case ',':
  324. lexptr++;
  325. return c;
  326. case '"':
  327. yyerror ("double quoted strings not allowed in #if expressions");
  328. return ERROR;
  329. }
  330. if (c >= '0' && c <= '9') {
  331. /* It's a number */
  332. for (namelen = 0;
  333. c = tokstart[namelen], is_idchar[c] || c == '.';
  334. namelen++)
  335. ;
  336. return parse_number (namelen);
  337. }
  338. if (!is_idstart[c]) {
  339. yyerror ("Invalid token in expression");
  340. return ERROR;
  341. }
  342. /* It is a name. See how long it is. */
  343. for (namelen = 0; is_idchar[tokstart[namelen]]; namelen++)
  344. ;
  345. lexptr += namelen;
  346. return NAME;
  347. }
  348. /* Parse a C escape sequence. STRING_PTR points to a variable
  349. containing a pointer to the string to parse. That pointer
  350. is updated past the characters we use. The value of the
  351. escape sequence is returned.
  352. A negative value means the sequence \ newline was seen,
  353. which is supposed to be equivalent to nothing at all.
  354. If \ is followed by a null character, we return a negative
  355. value and leave the string pointer pointing at the null character.
  356. If \ is followed by 000, we return 0 and leave the string pointer
  357. after the zeros. A value of 0 does not mean end of string. */
  358. static int
  359. parse_escape (string_ptr)
  360. char **string_ptr;
  361. {
  362. register int c = *(*string_ptr)++;
  363. switch (c)
  364. {
  365. case 'a':
  366. return '\a';
  367. case 'b':
  368. return '\b';
  369. case 'e':
  370. return 033;
  371. case 'f':
  372. return '\f';
  373. case 'n':
  374. return '\n';
  375. case 'r':
  376. return '\r';
  377. case 't':
  378. return '\t';
  379. case 'v':
  380. return '\v';
  381. case '\n':
  382. return -2;
  383. case 0:
  384. (*string_ptr)--;
  385. return 0;
  386. case '^':
  387. c = *(*string_ptr)++;
  388. if (c == '\\')
  389. c = parse_escape (string_ptr);
  390. if (c == '?')
  391. return 0177;
  392. return (c & 0200) | (c & 037);
  393. case '0':
  394. case '1':
  395. case '2':
  396. case '3':
  397. case '4':
  398. case '5':
  399. case '6':
  400. case '7':
  401. {
  402. register int i = c - '0';
  403. register int count = 0;
  404. while (++count < 3)
  405. {
  406. if ((c = *(*string_ptr)++) >= '0' && c <= '7')
  407. {
  408. i *= 8;
  409. i += c - '0';
  410. }
  411. else
  412. {
  413. (*string_ptr)--;
  414. break;
  415. }
  416. }
  417. return i;
  418. }
  419. default:
  420. return c;
  421. }
  422. }
  423. static
  424. yyerror (s)
  425. char *s;
  426. {
  427. error (s);
  428. longjmp (parse_return_error, 1);
  429. }
  430. /* This page contains the entry point to this file. */
  431. /* Parse STRING as an expression, and complain if this fails
  432. to use up all of the contents of STRING. */
  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. /* horizontal space table */
  504. ++is_hor_space[' '];
  505. ++is_hor_space['\t'];
  506. }
  507. error (msg)
  508. {
  509. printf("error: %s\n", msg);
  510. }
  511. #endif