for.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include "grap.h"
  4. #include "y.tab.h"
  5. typedef struct {
  6. Obj *var; /* index variable */
  7. double to; /* limit */
  8. double by;
  9. int op; /* operator */
  10. char *str; /* string to push back */
  11. } For;
  12. #define MAXFOR 10
  13. For forstk[MAXFOR]; /* stack of for loops */
  14. For *forp = forstk; /* pointer to current top */
  15. void forloop(Obj *var, double from, double to, int op, double by, char *str) /* set up a for loop */
  16. {
  17. fprintf(tfd, "# for %s from %g to %g by %c %g \n",
  18. var->name, from, to, op, by);
  19. if (++forp >= forstk+MAXFOR)
  20. ERROR "for loop nested too deep" FATAL;
  21. forp->var = var;
  22. forp->to = to;
  23. forp->op = op;
  24. forp->by = by;
  25. forp->str = str;
  26. setvar(var, from);
  27. nextfor();
  28. unput('\n');
  29. }
  30. void nextfor(void) /* do one iteration of a for loop */
  31. {
  32. /* BUG: this should depend on op and direction */
  33. if (forp->var->fval > SLOP * forp->to) { /* loop is done */
  34. free(forp->str);
  35. if (--forp < forstk)
  36. ERROR "forstk popped too far" FATAL;
  37. } else { /* another iteration */
  38. pushsrc(String, "\nEndfor\n");
  39. pushsrc(String, forp->str);
  40. }
  41. }
  42. void endfor(void) /* end one iteration of for loop */
  43. {
  44. switch (forp->op) {
  45. case '+':
  46. case ' ':
  47. forp->var->fval += forp->by;
  48. break;
  49. case '-':
  50. forp->var->fval -= forp->by;
  51. break;
  52. case '*':
  53. forp->var->fval *= forp->by;
  54. break;
  55. case '/':
  56. forp->var->fval /= forp->by;
  57. break;
  58. }
  59. nextfor();
  60. }
  61. char *ifstat(double expr, char *thenpart, char *elsepart)
  62. {
  63. dprintf("if %g then <%s> else <%s>\n", expr, thenpart, elsepart? elsepart : "");
  64. if (expr) {
  65. unput('\n');
  66. pushsrc(Free, thenpart);
  67. pushsrc(String, thenpart);
  68. unput('\n');
  69. if (elsepart)
  70. free(elsepart);
  71. return thenpart; /* to be freed later */
  72. } else {
  73. free(thenpart);
  74. if (elsepart) {
  75. unput('\n');
  76. pushsrc(Free, elsepart);
  77. pushsrc(String, elsepart);
  78. unput('\n');
  79. }
  80. return elsepart;
  81. }
  82. }