calc.c 33.8 KB
Newer Older
1
/* calc.c	01/13/1996
2
 * a simple calculator.
3 4 5
 */

/* Copyright (c) 1995,1996 Sascha Demetrio
6
 * Copyright (c) 2009, 2010, 2015 Peter Pentchev
7 8 9 10 11 12 13
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
14
 *    If you modify any part of HEXER and redistribute it, you must add
15 16 17 18 19 20
 *    a notice to the `README' file and the modified source files containing
 *    information about the  changes you made.  I do not want to take
 *    credit or be blamed for your modifications.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
21
 *    If you modify any part of HEXER and redistribute it in binary form,
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
 *    you must supply a `README' file containing information about the
 *    changes you made.
 * 3. The name of the developer may not be used to endorse or promote
 *    products derived from this software without specific prior written
 *    permission.
 *
 * HEXER WAS DEVELOPED BY SASCHA DEMETRIO.
 * THIS SOFTWARE SHOULD NOT BE CONSIDERED TO BE A COMMERCIAL PRODUCT.
 * THE DEVELOPER URGES THAT USERS WHO REQUIRE A COMMERCIAL PRODUCT
 * NOT MAKE USE OF THIS WORK.
 *
 * DISCLAIMER:
 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPER ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE DEVELOPER BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#include "config.h"
#include "defs.h"

#define NDEBUG

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <assert.h>
#include <math.h>
#if HAVE_FLOAT_H
#include <float.h>
#endif
#include <limits.h>

63 64
#include "buffer.h"
#include "hexer.h"
65
#include "calc.h"
66
#include "readline.h"
67
#include "tio.h"
68
#include "util.h"
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99

#define CALC_STACKSIZE 1024

#ifndef DBL_EPSILON
#define DBL_EPSILON (1e-9)
#endif

#ifndef LONG_BITS
#define LONG_BITS 32
#endif

#ifndef DEBUG
#define DEBUG 0
#endif

static int calc_stack_initialized_f = 0;
static int calc_command_counter = 0;

enum calc_object_e {
  CO_NONE,                           /* uninitialized */
  CO_INTEGER, CO_FLOAT, CO_BOOLEAN,  /* numeric values */
  CO_UNARY_OPERATOR,                 /* unary operator sign */
  CO_BINARY_OPERATOR,                /* binary operator sign */
  CO_VARIABLE,                       /* variable name */
  CO_ERROR                           /* error message */
};

#define CO_VALUE(x) (x.type == CO_INTEGER                                     \
                     || x.type == CO_FLOAT                                    \
                     || x.type == CO_BOOLEAN)

100
static const char *calc_object_names[] = {
101 102 103 104 105 106 107 108 109 110 111
  "none", "integer", "float", "boolean", "unary operator", "binary operator",
  "variable", "error", 0
};

enum calc_unary_operator_e {
  OP_NEG, OP_NOT, OP_COMP,
  OP_PAROPEN, OP_PARCLOSE,
  OP_EXEC,
  OP_max_unary_operator
};

112
static const char *calc_unary_operator_names[OP_max_unary_operator] = {
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
  "-  neg", "!  not", "~  comp", "(  paropen", ")  parclose", ":  exec"
};

enum calc_binary_operator_e {
  OP_POW,
  OP_MUL, OP_DIV, OP_MOD,
  OP_ADD, OP_SUB,
  OP_SHL, OP_SHR,
  OP_LES, OP_LEQ, OP_GRT, OP_GEQ,
  OP_EQU, OP_NEQ,
  OP_AND, OP_XOR, OP_OR,
  OP_LAND, OP_LOR,
  OP_ASSIGN,
  OP_max_binary_operator
};

static int prec[OP_max_binary_operator] = {
  0, 1, 1, 1, 2, 2, 3, 3, 4, 4, 4, 4, 5, 5, 6, 6, 6, 7, 7, 8
};

133
static const char *calc_binary_operator_names[OP_max_binary_operator] = {
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
  "** pow",
  "*  mul", "/  div", "%  mod", "+  add", "-  sub", "<< shl", ">> shr",
  "<  les", "<= leq", ">  grt", ">= geq", "== equ", "!= neq",
  "&  and", "^  xor", "|  or", "&& land", "|| lor", "=  assign"
};

struct calc_object_s {
  enum calc_object_e type;
  union {
    long i;                            /* `CO_INTEGER', `CO_BOOLEAN' */
    double f;                          /* `CO_FLOAT' */
    char *s;                           /* `CO_VARIABLE', `CO_ERROR' */
    enum calc_unary_operator_e uo;     /* `CO_UNARY_OPERATOR' */
    enum calc_binary_operator_e bo;    /* `CO_BINARY_OPERATOR' */
  } u;
};

/* a simple list of variables.
 */
struct calc_variable_s {
  char *name;
  struct calc_object_s object;
  struct calc_variable_s *next;
} *calc_variable_list = 0;

#ifdef CALC_COMPILE
enum calc_code_e {
  CC_VALUE,          /* immediate value */
  CC_INSTRUCTION     /* instruction */
};

static char *calc_code_names[] = {
  "VALUE", "INSTRUCTION", 0
};

#if 0
enum calc_instruction_e {
  CI_ADD,      /* add the top two elements on the stack */
  CI_ADDI,     /* add an immediate value to the top element */
  CI_SUB,      /* substact the top two elements */
  CI_SUBI,     /* substact immediate value from the top element */
  CI_MUL,      /* multiply the top two elements */
  CI_MULI,     /* multiply an immediate value with the top element */
  CI_POW,      /* compute s[-2] ** s[-1] */
  CI_POWI,     /* compute s[-1] ** i (immediate value) */
  CI_IDIV,     /* integer divide the top two elements */
  CI_IDIVI,    /* integer divide the top element by an immediate value */
  CI_DIV,      /* divide the top two elements */
  CI_DIVI,     /* divide the top element by an immediate value */
  CI_SHL,      /* shift left s[-2] by s[-1] bits */
  CI_SHLI,     /* shift left the top element by an immediate value */
  CI_SHR,      /* shift right s[-2] by s[-1] bits */
  CI_SHRI,     /* shift right the top element by an immediate value */
  CI_LES,      /* check if the top element is less than zero */
  CI_LEQ,      /* check if the top element is less or equal than zero */
  CI_GRT,      /* check if the top element is greater than zero */
  CI_GEQ,      /* check if the top element is greater or equal than zero */
  CI_EQU,      /* check if the top element is equal to zero */
  CI_NEQ,      /* check if the top element is not equal to zero */
  CI_PUSH,     /* push an immediate value onto the execution stack */
  CI_POP,      /* remove an element from the execution stack */
  CI_VALUE,    /* push the value of a variable onto the execution stack */
  CI_ASSIGN,   /* assign the top element to a variable */
#if 0
  CI_BEQ,      /* branch on equal */
  CI_BNE,      /* branch on not equal */
#endif
  CI_MAX       /* number of instructions */
};

static char *calc_instruction_names[] = {
  "ADD", "ADDI", "SUB", "SUBI", "MUL", "MULI", "POW", "POWI", "IDIV", "IDIVI",
  "DIV", "DIVI", "SHL", "SHLI", "SHR", "SHRI", "LES", "LEQ", "EQU", "NEQ",
  "PUSH", "POP", "VALUE", "ASSIGN",
  "BEQ", "BNE", 0
};
#endif

struct calc_code_s {
  enum calc_code_e type;
  union {
    enum calc_instruction_e instruction;
    struct calc_object_s object;
  } u;
};
#endif

static struct calc_object_s stack[CALC_STACKSIZE];
static int sp;

  static int
225
calc_initialize_stack(void)
226 227 228 229 230 231 232 233 234 235 236
{
  int i;

  if (calc_stack_initialized_f) return 0;
  ++calc_stack_initialized_f;
  for (i = 0; i < CALC_STACKSIZE; ++i) stack[i].type = CO_NONE;
  return 0;
}
/* calc_initialize_stack */

  static int
237
calc_clear_stack(int count)
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
  /* remove the trailing `count' stack elements from the stack.
   */
{
  for (--sp; count; --count, --sp) {
    switch (stack[sp].type) {
    case CO_VARIABLE:
    case CO_ERROR:
      free(stack[sp].u.s);
      stack[sp].u.s = 0;
      break;
    default:
      break;
    }
    stack[sp].type = CO_NONE;
  }
  ++sp;
  return 0;
}
/* calc_clear_stack */

  static int
259
calc_set_stack(int position, struct calc_object_s object)
260 261 262 263 264 265 266 267 268
{
  if (stack[position].type == CO_ERROR || stack[position].type == CO_VARIABLE)
    free(stack[position].u.s);
  stack[position] = object;
  return 0;
}
/* calc_set_stack */

  static char *
269
calc_sprint(char *s, struct calc_object_s object)
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
{
  switch(object.type) {
  case CO_BINARY_OPERATOR:
    sprintf(s, "%s", calc_binary_operator_names[(int)object.u.bo] + 3);
    break;
  case CO_UNARY_OPERATOR:
    sprintf(s, "%s", calc_unary_operator_names[(int)object.u.uo] + 3);
    break;
  case CO_INTEGER:
    sprintf(s, "%li 0%lo 0x%lx", object.u.i, object.u.i, object.u.i);
    break;
  case CO_FLOAT:
    sprintf(s, "%g", object.u.f);
    break;
  case CO_BOOLEAN:
    sprintf(s, "%s", object.u.i ? "true" : "false");
    break;
  case CO_ERROR:
  case CO_VARIABLE:
    sprintf(s, "%s", object.u.s);
    break;
  default:
    sprintf(s, "INVALID OBJECT");
  }
  return s;
}
/* calc_print */

  static int
calc_error(struct calc_object_s *x, const char *fmt, ...)
{
  va_list ap;
  char buf[256];

  va_start(ap, fmt);
  vsprintf(buf, fmt, ap);
  if (x->type != CO_ERROR) {
    x->type = CO_ERROR;
308
    x->u.s = strdup_fatal(buf);
309 310 311 312 313 314 315
  }
  va_end(ap);
  return 0;
}
/* calc_error */

  static int
316
calc_evaluate(struct calc_object_s *object)
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
{
  struct calc_variable_s *i;

  assert(object->type == CO_VARIABLE);
  for (i = calc_variable_list; i; i = i->next)
    if (!strcmp(object->u.s, i->name)) {
      *object = i->object;
      return 0;
    }
  calc_error(object, "undefined variable `%s'", object->u.s);
  return -1;
}
/* calc_evaluate */

  static int
332
calc_assign(struct calc_object_s x, struct calc_object_s y)
333 334 335 336 337 338 339 340 341 342 343
{
  struct calc_variable_s *i;

  assert(x.type == CO_VARIABLE);
  assert(y.type != CO_VARIABLE);
  assert(y.type != CO_ERROR);
  for (i = calc_variable_list; i; i = i->next)
    if (!strcmp(x.u.s, i->name)) {
      i->object = y;
      return 0;
    }
344
  i = (struct calc_variable_s *)malloc_fatal(sizeof *i);
345
  i->object = y;
346
  i->name = strdup_fatal(x.u.s);
347 348 349 350 351 352 353
  i->next = calc_variable_list;
  calc_variable_list = i;
  return 0;
}
/* calc_assign */

  static int
354
calc_operation(int position, int binary)
355 356 357 358 359 360 361 362 363
  /* evaluate the simple expression on stack position `position' and
   * update the stack.  if `binary == 0', a unary expression is expected,
   * else a binary expression is expected.  the function returns 0 on
   * success and -1 on error.
   */
{
  struct calc_object_s x, y, op;
  int int_f;
  int error_f = 0;
364
  int nremove;  /* number of elements to remove from the stack */
365 366 367
  int i;

  if (binary) {  /* binary operator */
368
    nremove = 2;
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781
    assert(position + 2 < sp);
    x = stack[position];
    op = stack[position + 1];
    y = stack[position + 2];
    if (x.type == CO_VARIABLE && op.u.bo != OP_ASSIGN) calc_evaluate(&x);
    if (y.type == CO_VARIABLE) calc_evaluate(&y);
    if (op.type != CO_BINARY_OPERATOR || !CO_VALUE(y)) {
      if (y.type == CO_ERROR) x = y; else calc_error(&x, "syntax error");
      ++error_f;
      goto exit;
    }
    switch (op.u.bo) {
    case OP_POW:
      int_f = 0;
      switch (x.type) {
      case CO_BOOLEAN:
      case CO_INTEGER:
        int_f = 1;
        x.type = CO_FLOAT;
        x.u.f = (double)x.u.i;
      case CO_FLOAT:
        if (y.type != CO_FLOAT) {
          y.type = CO_FLOAT;
          y.u.f = (double)y.u.i;
        } else
          int_f = 0;
        x.u.f = pow(x.u.f, y.u.f);
        if (int_f && x.u.f < (unsigned)(1 << (LONG_BITS - 1)) - 1) {
          x.type = CO_INTEGER;
          x.u.i = (int)x.u.f;
        }
        break;
      default:
        calc_error(&x, "syntax error");
        ++error_f;
        break;
      }
      break;
    case OP_MUL:
      switch (x.type) {
      case CO_BOOLEAN:
        if (y.type == CO_INTEGER) x.type = CO_INTEGER;
      case CO_INTEGER:
        if (y.type != CO_FLOAT) {
          x.u.i *= y.u.i;
          break;
        } else {
          x.u.f = (double)x.u.i;
          x.type = CO_FLOAT;
        }
      case CO_FLOAT:
        x.u.f *= y.type == CO_FLOAT ? y.u.f : (double)y.u.i;
        break;
      default:
        calc_error(&x, "syntax error");
        ++error_f;
        break;
      }
      break;
    case OP_DIV:
      if (y.type == CO_FLOAT ? fabs(y.u.f) < DBL_EPSILON : !y.u.i) {
        calc_error(&x, "division by zero");
        ++error_f;
        break;
      }
      switch (x.type) {
      case CO_BOOLEAN:
        if (y.type == CO_INTEGER) x.type = CO_INTEGER;
      case CO_INTEGER:
        if (y.type != CO_FLOAT) {
          x.u.i /= y.u.i;
          break;
        } else {
          x.u.f = (double)x.u.i;
          x.type = CO_FLOAT;
        }
      case CO_FLOAT:
        x.u.f /= y.type == CO_FLOAT ? y.u.f : (double)y.u.i;
        break;
      default:
        calc_error(&x, "syntax error");
        ++error_f;
        break;
      }
      break;
    case OP_MOD:
      if (x.type == CO_FLOAT || y.type == CO_FLOAT) {
        calc_error(&x, "invalid type in binary operator MOD (%%)");
        ++error_f;
        break;
      }
      switch (x.type) {
      case CO_BOOLEAN:
        if (y.type == CO_INTEGER) x.type = CO_INTEGER;
      case CO_INTEGER:
        x.u.i %= y.u.i;
        break;
      case CO_FLOAT:
      default:
        calc_error(&x, "syntax error");
        ++error_f;
        break;
      }
      break;
    case OP_ADD:
      switch (x.type) {
      case CO_BOOLEAN:
        if (y.type == CO_INTEGER) x.type = CO_INTEGER;
      case CO_INTEGER:
        if (y.type != CO_FLOAT) {
          x.u.i += y.u.i;
          break;
        } else {
          x.u.f = (double)x.u.i;
          x.type = CO_FLOAT;
        }
      case CO_FLOAT:
        x.u.f += y.type == CO_FLOAT ? y.u.f : (double)y.u.i;
        break;
      default:
        calc_error(&x, "syntax error");
        ++error_f;
        break;
      }
      break;
    case OP_SUB:
      switch (x.type) {
      case CO_BOOLEAN:
        if (y.type == CO_INTEGER) x.type = CO_INTEGER;
      case CO_INTEGER:
        if (y.type != CO_FLOAT) {
          x.u.i -= y.u.i;
          break;
        } else {
          x.u.f = (double)x.u.i;
          x.type = CO_FLOAT;
        }
      case CO_FLOAT:
        x.u.f -= y.type == CO_FLOAT ? y.u.f : (double)y.u.i;
        break;
      default:
        calc_error(&x, "syntax error");
        ++error_f;
        break;
      }
      break;
    case OP_SHL:
      if (x.type == CO_FLOAT || y.type == CO_FLOAT) {
        calc_error(&x, "invalid type in binary operator SHL (<<)");
        ++error_f;
        break;
      }
      switch (x.type) {
      case CO_BOOLEAN:
        if (y.type == CO_INTEGER) x.type = CO_INTEGER;
      case CO_INTEGER:
        if (y.u.i >= LONG_BITS) y.u.i = LONG_BITS - 1;
        x.u.i <<= y.u.i;
        break;
      case CO_FLOAT:
      default:
        calc_error(&x, "syntax error");
        ++error_f;
        break;
      }
      break;
    case OP_SHR:
      if (x.type == CO_FLOAT || y.type == CO_FLOAT) {
        calc_error(&x, "invalid type in binary operator SHR (>>)");
        ++error_f;
        break;
      }
      switch (x.type) {
      case CO_BOOLEAN:
        if (y.type == CO_INTEGER) x.type = CO_INTEGER;
      case CO_INTEGER:
        if (y.u.i >= LONG_BITS) y.u.i = LONG_BITS - 1;
        x.u.i >>= y.u.i;
        break;
      case CO_FLOAT:
      default:
        calc_error(&x, "syntax error");
        ++error_f;
        break;
      }
      break;
    case OP_LES:
      switch (x.type) {
      case CO_BOOLEAN:
      case CO_INTEGER:
        if (y.type != CO_FLOAT) {
          x.u.i = x.u.i < y.u.i;
          break;
        } else
          x.u.f = (double)x.u.i;
      case CO_FLOAT:
        x.u.i = x.u.f < (y.type == CO_FLOAT ? y.u.f : (double)y.u.i);
        break;
      default:
        calc_error(&x, "syntax error");
        ++error_f;
        break;
      }
      x.type = CO_BOOLEAN;
      break;
    case OP_LEQ:
      switch (x.type) {
      case CO_BOOLEAN:
      case CO_INTEGER:
        if (y.type != CO_FLOAT) {
          x.u.i = x.u.i <= y.u.i;
          break;
        } else
          x.u.f = (double)x.u.i;
      case CO_FLOAT:
        x.u.i = x.u.f <= (y.type == CO_FLOAT ? y.u.f : (double)y.u.i);
        break;
      default:
        calc_error(&x, "syntax error");
        ++error_f;
        break;
      }
      x.type = CO_BOOLEAN;
      break;
    case OP_GRT:
      switch (x.type) {
      case CO_BOOLEAN:
      case CO_INTEGER:
        if (y.type != CO_FLOAT) {
          x.u.i = x.u.i > y.u.i;
          break;
        } else
          x.u.f = (double)x.u.i;
      case CO_FLOAT:
        x.u.i = x.u.f > (y.type == CO_FLOAT ? y.u.f : (double)y.u.i);
        break;
      default:
        calc_error(&x, "syntax error");
        ++error_f;
        break;
      }
      x.type = CO_BOOLEAN;
      break;
    case OP_GEQ:
      switch (x.type) {
      case CO_BOOLEAN:
      case CO_INTEGER:
        if (y.type != CO_FLOAT) {
          x.u.i = x.u.i >= y.u.i;
          break;
        } else
          x.u.f = (double)x.u.i;
      case CO_FLOAT:
        x.u.i = x.u.f >= (y.type == CO_FLOAT ? y.u.f : (double)y.u.i);
        break;
      default:
        calc_error(&x, "syntax error");
        ++error_f;
        break;
      }
      x.type = CO_BOOLEAN;
      break;
    case OP_EQU:
      switch (x.type) {
      case CO_BOOLEAN:
      case CO_INTEGER:
        if (y.type != CO_FLOAT) {
          x.u.i = x.u.i == y.u.i;
          break;
        } else
          x.u.f = (double)x.u.i;
      case CO_FLOAT:
        if (y.type == CO_INTEGER) y.u.f = (double)y.u.i;
        x.u.i = fabs(x.u.f - y.u.f) < DBL_EPSILON;
        break;
      default:
        calc_error(&x, "syntax error");
        ++error_f;
        break;
      }
      x.type = CO_BOOLEAN;
      break;
    case OP_NEQ:
      switch (x.type) {
      case CO_BOOLEAN:
      case CO_INTEGER:
        if (y.type != CO_FLOAT) {
          x.u.i = x.u.i != y.u.i;
          break;
        } else
          x.u.f = (double)x.u.i;
      case CO_FLOAT:
        if (y.type == CO_INTEGER) y.u.f = (double)y.u.i;
        x.u.i = fabs(x.u.f - y.u.f) >= DBL_EPSILON;
        break;
      default:
        calc_error(&x, "syntax error");
        ++error_f;
        break;
      }
      x.type = CO_BOOLEAN;
      break;
    case OP_AND:
      if (x.type == CO_FLOAT || y.type == CO_FLOAT) {
        calc_error(&x, "invalid type in binary operator AND (&)");
        ++error_f;
        break;
      }
      switch (x.type) {
      case CO_BOOLEAN:
        if (y.type == CO_INTEGER) x.type = CO_INTEGER;
      case CO_INTEGER:
        if (y.u.i >= LONG_BITS) y.u.i = LONG_BITS - 1;
        x.u.i &= y.u.i;
        break;
      case CO_FLOAT:
      default:
        calc_error(&x, "syntax error");
        ++error_f;
        break;
      }
      break;
    case OP_XOR:
      if (x.type == CO_FLOAT || y.type == CO_FLOAT) {
        calc_error(&x, "invalid type in binary operator XOR (^)");
        ++error_f;
        break;
      }
      switch (x.type) {
      case CO_BOOLEAN:
        if (y.type == CO_INTEGER) x.type = CO_INTEGER;
      case CO_INTEGER:
        if (y.u.i >= LONG_BITS) y.u.i = LONG_BITS - 1;
        x.u.i ^= y.u.i;
        break;
      case CO_FLOAT:
      default:
        calc_error(&x, "syntax error");
        ++error_f;
        break;
      }
      break;
    case OP_OR:
      if (x.type == CO_FLOAT || y.type == CO_FLOAT) {
        calc_error(&x, "invalid type in binary operator OR (|)");
        ++error_f;
        break;
      }
      switch (x.type) {
      case CO_BOOLEAN:
        if (y.type == CO_INTEGER) x.type = CO_INTEGER;
      case CO_INTEGER:
        if (y.u.i >= LONG_BITS) y.u.i = LONG_BITS - 1;
        x.u.i |= y.u.i;
        break;
      case CO_FLOAT:
      default:
        calc_error(&x, "syntax error");
        ++error_f;
        break;
      }
      break;
    case OP_LAND:  /* logical AND */
      switch (x.type) {
      case CO_BOOLEAN:
      case CO_INTEGER:
        x.u.i = x.u.i
          && (y.type == CO_FLOAT ? fabs(y.u.f) >= DBL_EPSILON : y.u.i);
        break;
      case CO_FLOAT:
        x.u.i = fabs(x.u.f) >= DBL_EPSILON
          && (y.type == CO_FLOAT ? fabs(y.u.f) >= DBL_EPSILON : y.u.i);
        break;
      default:
        calc_error(&x, "syntax error");
        ++error_f;
        break;
      }
      x.type = CO_BOOLEAN;
      break;
    case OP_LOR:  /* logical OR */
      switch (x.type) {
      case CO_BOOLEAN:
      case CO_INTEGER:
        x.u.i = x.u.i
          || (y.type == CO_FLOAT ? fabs(y.u.f) >= DBL_EPSILON : y.u.i);
        break;
      case CO_FLOAT:
        x.u.i = fabs(x.u.f) >= DBL_EPSILON
          || (y.type == CO_FLOAT ? fabs(y.u.f) >= DBL_EPSILON : y.u.i);
        break;
      default:
        calc_error(&x, "syntax error");
        ++error_f;
        break;
      }
      x.type = CO_BOOLEAN;
      break;
    case OP_ASSIGN:
      if (x.type != CO_VARIABLE) {
        calc_error(&x, "invalid l-value in assignment");
        ++error_f;
        break;
      }
      calc_assign(x, y);
      x = y;
      break;
    default:
      calc_error(&x, "syntax error");
      ++error_f;
      break;
    }
  } else {  /* unary operator */
782
    nremove = 1;
783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851
    assert(position + 1 < sp);
    op = stack[position];
    x = stack[position + 1];
    assert(op.type == CO_UNARY_OPERATOR);
    if (x.type == CO_VARIABLE) calc_evaluate(&x);
    switch (op.u.uo) {
    case OP_NEG:
      switch (x.type) {
      case CO_BOOLEAN:
      case CO_INTEGER:
        x.u.i = -x.u.i;
        break;
      case CO_FLOAT:
        x.u.f = -x.u.f;
        break;
      default:
        calc_error(&x, "syntax error");
        ++error_f;
        break;
      }
      break;
    case OP_NOT:  /* logical NOT */
      switch (x.type) {
      case CO_INTEGER:
        x.type = CO_BOOLEAN;
      case CO_BOOLEAN:
        x.u.i = !x.u.i;
        break;
      case CO_FLOAT:
        x.u.i = !x.u.f;
        x.type = CO_BOOLEAN;
        break;
      default:
        calc_error(&x, "syntax error");
        ++error_f;
        break;
      }
      break;
    case OP_COMP:  /* bit complement */
      if (x.type == CO_FLOAT) {
        calc_error(&x, "invalid type in unary operator COMP (~)");
        ++error_f;
        break;
      }
      switch (x.type) {
      case CO_BOOLEAN:
        x.type = CO_INTEGER;
      case CO_INTEGER:
        x.u.i = ~x.u.i;
        break;
      default:
        calc_error(&x, "syntax error");
        ++error_f;
        break;
      }
      break;
    case OP_PAROPEN:
      break;
    case OP_PARCLOSE:
    case OP_EXEC:
      /* `calc_operation()' should never be called for `OP_EXEC' or
       * `OP_PARCLOSE'. */
    default:
      calc_error(&x, "syntax error");
      ++error_f;
      break;
    }
  }
exit:
852 853
  for (i = position + 1; i < sp; ++i) calc_set_stack(i, stack[i + nremove]);
  calc_clear_stack(nremove);
854 855 856 857 858 859
  calc_set_stack(position, x);
  return error_f;
}
/* calc_operation */

  static int
860
calc_reduce(void)
861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931
  /* try to reduce to top of the stack.  return values:
   * -1:  reduction failed due to an error.  an error element has been put
   *      onto the stack.
   * 0:   no reduction.
   * 1:   reduction succeeded.
   */
{
  struct calc_object_s x, y, z;
  int error_f = 0;
  int reduce_f = 0;

  if (sp < 2) goto exit_calc_reduce;
  x = stack[sp - 1];
  y = stack[sp - 2];
  switch (x.type) {
  case CO_INTEGER: case CO_FLOAT: case CO_BOOLEAN: case CO_VARIABLE:
    switch (y.type) {
    case CO_UNARY_OPERATOR:
      if (y.u.uo != OP_PAROPEN) {
unary:  error_f = calc_operation(sp - 2, 0);
        ++reduce_f;
      }
      break;
    case CO_BINARY_OPERATOR:
      /* check if `y' is an unary minus */
      if (y.u.bo == OP_SUB && (sp == 2 ? 1 : !CO_VALUE(stack[sp - 3]))) {
        stack[sp - 2].type = CO_UNARY_OPERATOR;
        stack[sp - 2].u.uo = OP_NEG;
        goto unary;
      }
      break;
    default:
      calc_error(stack + sp++, "syntax error");
      ++error_f;
      break;
    }
    break;
  case CO_UNARY_OPERATOR:
    if (x.u.uo == OP_PARCLOSE)
      goto eval;
    else if (x.u.uo == OP_EXEC && sp > 3)
      goto exec;
    break;
  case CO_BINARY_OPERATOR:
    if (sp > 3) {
exec: z = stack[sp - 3];
      if (z.type == CO_BINARY_OPERATOR) {
        if (!CO_VALUE(y) && y.type != CO_VARIABLE) {
          calc_error(stack + sp++, "syntax error");
          ++error_f;
          break;
        } else if (prec[(int)z.u.bo] <= prec[(int)x.u.bo]
                   || x.type == CO_UNARY_OPERATOR) {
          error_f = calc_operation(sp - 4, 1);
          ++reduce_f;
          break;
        }
      } else {
        if (z.type != CO_UNARY_OPERATOR || z.u.uo != OP_PAROPEN) {
          calc_error(stack + sp++, "syntax error");
          ++error_f;
          break;
        }
      }
    }
    break;
  default: abort();
  }
exit_calc_reduce:
  return error_f ? -1 : reduce_f;

Peter Pentchev's avatar
Peter Pentchev committed
932
eval: /* evaluate a parenthesized expression */
933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961
  if (sp > 1 && y.type == CO_UNARY_OPERATOR ? y.u.uo == OP_PAROPEN : 0) {
    calc_clear_stack(2);
    calc_error(stack + sp++, "empty parentheses");
    ++error_f;
  } else if (sp > 2) {
    z = stack[sp - 3];
    if (z.type == CO_BINARY_OPERATOR && sp > 3)
      goto exec;
    else if (z.type == CO_UNARY_OPERATOR) {
      assert(z.u.uo == OP_PAROPEN);
      if (!CO_VALUE(y)) {
        calc_error(&y, "invalid object (%s) in parentheses",
                   calc_object_names[(int)y.type]);
        ++error_f;
      }
      stack[sp - 3] = y;
      calc_clear_stack(2);
      ++reduce_f;
    }
  } else {
    calc_clear_stack(1);
    calc_error(stack + sp++, "unmatched ')'");
    ++error_f;
  }
  return error_f ? -1 : reduce_f;
}
/* calc_reduce */

  static int
962
istrue(char *s, char **endptr)
963
{
964
  static const char *true_strings[] = { "true", "t", "TRUE", "True", "T",
965 966 967
    "yes", "y", "YES", "Yes", "on", "ON", "On", 0 };
  int i, l;

968
  for (i = 0; (l = (true_strings[i] ? strlen(true_strings[i]) : 0)); ++i)
969 970 971 972 973 974 975 976 977 978
    if (!strncmp(true_strings[i], s, l)) {
      *endptr = s + l;
      return 1;
    }
  *endptr = s;
  return 0;
}
/* istrue */

  static int
979
isfalse(char *s, char **endptr)
980
{
981
  static const char *false_strings[] = { "false", "f", "FALSE", "False", "F",
982 983 984
    "no", "n", "NO", "No", "off", "OFF", "Off", 0 };
  int i, l;

985
  for (i = 0; (l = (false_strings[i] ? strlen(false_strings[i]) : 0)); ++i)
986 987 988 989 990 991 992 993 994 995 996 997 998 999
    if (!strncmp(false_strings[i], s, l)) {
      *endptr = s + l;
      return 1;
    }
  *endptr = s;
  return 0;
}
/* isfalse */

#ifndef XDIGIT
#define XDIGIT(x) (isdigit(x) ? x - '0' : tolower(x) - 'a' + 0xa)
#endif

  static int
1000
calc_scan(char *expr)
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
{
  char *p, *q, *r;
  long val;
  double fval;
  struct calc_object_s x;
  int float_f = 0;
  int base;
  int i;

  calc_clear_stack(sp);
1011
  for (p = expr; p;) {
1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
    while (isspace(*p)) ++p;
    if (!*p) break;
    if (isdigit(*p) || *p == '.') {
      if (*p == '0') {
        if (tolower(p[1]) == 'x') /* hex */
          base = 0x10, r = p + 2;
        else if (isdigit(p[1])) /* oct */
          base = 010, r = p + 1;
        else
          goto dec;
      } else { /* dec */
dec:    base = 10, r = p;
        for (q = p, val = 0; isdigit(*q); ++q);
        if (*q == '.' || *q == 'e' || *q == 'E') ++float_f;
      }
      if (float_f) {
        fval = strtod(r, &p);
        x.type = CO_FLOAT;
        x.u.f = fval;
      } else {
        val = strtol(r, &p, base);
        x.type = CO_INTEGER;
        x.u.i = val;
      }
    } else if (istrue(p, &p)) {
      x.type = CO_BOOLEAN;
      x.u.i = 1;
    } else if (isfalse(p, &p)) {
      x.type = CO_BOOLEAN;
      x.u.i = 0;
    } else if (isalpha(*p) || *p == '_' || *p == '$') {
      for (q = p + 1; isalnum(*q) || *q == '_' || *q == '$'; ++q);
      x.type = CO_VARIABLE;
1045
      x.u.s = strdup_fatal(p);
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
      x.u.s[q - p] = 0;
      p = q;
    } else {
      switch (*p) {
      case '*':
        ++p;
        x.type = CO_BINARY_OPERATOR;
        if (*p == '*') {
          ++p;
          x.u.bo = OP_POW;
        } else
          x.u.bo = OP_MUL;
        break;
      case '/':
        ++p;
        x.type = CO_BINARY_OPERATOR;
        x.u.bo = OP_DIV;
        break;
      case '%':
        ++p;
        x.type = CO_BINARY_OPERATOR;
        x.u.bo = OP_MOD;
        break;
      case '+':
        ++p;
        x.type = CO_BINARY_OPERATOR;
        x.u.bo = OP_ADD;
        break;
      case '-':
        ++p;
        x.type = CO_BINARY_OPERATOR;
        x.u.bo = OP_SUB;
        break;
      case '<':
        ++p;
        switch (*p) {
        case '<':
          ++p;
          x.type = CO_BINARY_OPERATOR;
          x.u.bo = OP_SHL;
          break;
        case '=':
          ++p;
          x.type = CO_BINARY_OPERATOR;
          x.u.bo = OP_LEQ;
          break;
        default:
          x.type = CO_BINARY_OPERATOR;
          x.u.bo = OP_LES;
        }
        break;
      case '>':
        ++p;
        switch (*p) {
        case '>':
          ++p;
          x.type = CO_BINARY_OPERATOR;
          x.u.bo = OP_SHR;
          break;
        case '=':
          ++p;
          x.type = CO_BINARY_OPERATOR;
          x.u.bo = OP_GEQ;
          break;
        default:
          x.type = CO_BINARY_OPERATOR;
          x.u.bo = OP_GRT;
        }
        break;
      case '=':
        ++p;
        switch (*p) {
        case '=':
          ++p;
          x.type = CO_BINARY_OPERATOR;
          x.u.bo = OP_EQU;
          break;
        default:
          x.type = CO_BINARY_OPERATOR;
          x.u.bo = OP_ASSIGN;
        }
        break;
      case '!':
        ++p;
        switch (*p) {
        case '=':
          ++p;
          x.type = CO_BINARY_OPERATOR;
          x.u.bo = OP_NEQ;
          break;
        default:
          x.type = CO_UNARY_OPERATOR;
          x.u.uo = OP_NOT;
        }
        break;
      case '&':
        ++p;
        switch (*p) {
        case '&':
          ++p;
          x.type = CO_BINARY_OPERATOR;
          x.u.bo = OP_LAND;
          break;
        default:
          x.type = CO_BINARY_OPERATOR;
          x.u.bo = OP_AND;
        }
        break;
      case '|':
        ++p;
        switch (*p) {
        case '|':
          ++p;
          x.type = CO_BINARY_OPERATOR;
          x.u.bo = OP_LOR;
          break;
        default:
          x.type = CO_BINARY_OPERATOR;
          x.u.bo = OP_OR;
        }
        break;
      case '^':
        ++p;
        x.type = CO_BINARY_OPERATOR;
        x.u.bo = OP_XOR;
        break;
      case '~':
        ++p;
        x.type = CO_UNARY_OPERATOR;
        x.u.uo = OP_COMP;
        break;
      case '(':
        ++p;
        x.type = CO_UNARY_OPERATOR;
        x.u.uo = OP_PAROPEN;
        break;
      case ')':
        ++p;
        x.type = CO_UNARY_OPERATOR;
        x.u.uo = OP_PARCLOSE;
        break;
      default:
Peter Pentchev's avatar
Peter Pentchev committed
1188
        calc_error(stack + sp++, "unexpected character %c (0x%x)",
1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221
                   isprint(*p) ? *p : ' ', (int)(unsigned char)*p);
        return -1;
      }
    }
    stack[sp++] = x;
#   if DEBUG
    calc_stack();
    while ((i = calc_reduce()) > 0) calc_stack();
    if (i < 0) {
      calc_stack();
      return -1;
    }
#   else
    while ((i = calc_reduce()) > 0);
    if (i < 0) return -1;
#   endif
  }
  x.type = CO_UNARY_OPERATOR;
  x.u.uo = OP_EXEC;
  stack[sp++] = x;
# if DEBUG
  calc_stack();
  while ((i = calc_reduce()) > 0) calc_stack();
  if (i < 0) calc_stack();
# else
  while ((i = calc_reduce()) > 0);
# endif
  return i;
}
/* calc_scan */

#ifdef MYCALC
  int
1222
main(int argc, char **argv)
1223 1224 1225 1226 1227 1228 1229 1230 1231 1232
{
  char buf[256];
  int error_f = 0;
  int i;
  struct calc_object_s x;

  calc_initialize_stack();
  for (;;) {
    *buf = 0;
    if (argc > 1)
1233 1234
      for (i = 1; i < argc; ++i)
	snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%s", argv[i]);
1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280
    else
      fgets(buf, 256, stdin);
    if (!*buf) break;
    if (buf[strlen(buf) - 1] == '\n') buf[strlen(buf) - 1] = 0;
    if (calc_scan(buf)) {
      /* search for error objects on the stack */
      for (i = sp - 1; i >= 0; --i)
        if (stack[i].type == CO_ERROR) {
          calc_print(stack[i], 0);
          ++error_f;
          putchar('\n');
        }
      if (!error_f) {
        printf("unknown error\nstack:\n");
        calc_stack();
      }
    } else {
      if (stack[1].type != CO_UNARY_OPERATOR || stack[1].u.uo != OP_EXEC)
        printf("syntax error");
      else {
        if (stack[0].type == CO_VARIABLE) calc_evaluate(stack);
        if (stack[0].type == CO_ERROR)
          calc_print(stack[0], 0);
        else if (!CO_VALUE(stack[0]))
          printf("syntax error");
        else {
          if (argc == 1) printf("$%i = ", ++calc_command_counter);
          calc_print(stack[0], 0);
          x.type = CO_VARIABLE;
          x.u.s = (char *)alloca(256);
          sprintf(x.u.s, "$%i", calc_command_counter);
          calc_assign(x, stack[0]);
          sprintf(x.u.s, "$$");
          calc_assign(x, stack[0]);
        }
        putchar('\n');
      }
    }
    calc_clear_stack(sp);
    if (argc > 1) break;
  }
  return 0;
}
/* main */
#else
  char *
1281
calculator(char *expr)
1282 1283 1284 1285 1286 1287 1288
{
  int i;
  int error_f = 0;
  static char result[256];
  struct calc_object_s x;

  calc_initialize_stack();
1289
  if (calc_scan(expr)) {
1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329
    /* search for error objects on the stack */
    for (i = sp - 1; i >= 0; --i)
      if (stack[i].type == CO_ERROR) {
        calc_sprint(result, stack[i]);
        ++error_f;
        break;
      }
    if (!error_f)
      sprintf(result, "unknown error");
  } else {
    if (stack[1].type != CO_UNARY_OPERATOR || stack[1].u.uo != OP_EXEC)
      sprintf(result, "syntax error");
    else {
      if (stack[0].type == CO_VARIABLE) calc_evaluate(stack);
      if (stack[0].type == CO_ERROR)
        calc_sprint(result, stack[0]);
      else if (!CO_VALUE(stack[0]))
        sprintf(result, "syntax error");
      else {
        sprintf(result, "$%i = ", ++calc_command_counter);
        calc_sprint(result + strlen(result), stack[0]);
        x.type = CO_VARIABLE;
        x.u.s = (char *)alloca(256);
        sprintf(x.u.s, "$%i", calc_command_counter);
        calc_assign(x, stack[0]);
        sprintf(x.u.s, "$$");
        calc_assign(x, stack[0]);
      }
    }
  }
  calc_clear_stack(sp);
  return result;
}
/* calculator */
#endif

/* end of calc.c */

/* VIM configuration: (do not delete this line)
 *
1330 1331
 * vim:bk:nodg:efm=%f\:%l\:%m:hid:icon:
 * vim:sw=2:sm:textwidth=79:ul=1024:wrap:
1332 1333
 */