symtab.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <ctype.h>
  4. #include <string.h>
  5. #include "pic.h"
  6. #include "y.tab.h"
  7. YYSTYPE getvar(char *s) /* return value of variable s (usually pointer) */
  8. {
  9. struct symtab *p;
  10. static YYSTYPE bug;
  11. p = lookup(s);
  12. if (p == NULL) {
  13. if (islower(s[0]))
  14. ERROR "no such variable as %s", s WARNING;
  15. else
  16. ERROR "no such place as %s", s WARNING;
  17. return(bug);
  18. }
  19. return(p->s_val);
  20. }
  21. double getfval(char *s) /* return float value of variable s */
  22. {
  23. YYSTYPE y;
  24. y = getvar(s);
  25. return y.f;
  26. }
  27. void setfval(char *s, double f) /* set variable s to f */
  28. {
  29. struct symtab *p;
  30. if ((p = lookup(s)) != NULL)
  31. p->s_val.f = f;
  32. }
  33. struct symtab *makevar(char *s, int t, YYSTYPE v) /* make variable named s in table */
  34. /* assumes s is static or from tostring */
  35. {
  36. struct symtab *p;
  37. for (p = stack[nstack].p_symtab; p != NULL; p = p->s_next)
  38. if (strcmp(s, p->s_name) == 0)
  39. break;
  40. if (p == NULL) { /* it's a new one */
  41. p = (struct symtab *) malloc(sizeof(struct symtab));
  42. if (p == NULL)
  43. ERROR "out of symtab space with %s", s FATAL;
  44. p->s_next = stack[nstack].p_symtab;
  45. stack[nstack].p_symtab = p; /* stick it at front */
  46. }
  47. p->s_name = s;
  48. p->s_type = t;
  49. p->s_val = v;
  50. return(p);
  51. }
  52. struct symtab *lookup(char *s) /* find s in symtab */
  53. {
  54. int i;
  55. struct symtab *p;
  56. for (i = nstack; i >= 0; i--) /* look in each active symtab */
  57. for (p = stack[i].p_symtab; p != NULL; p = p->s_next)
  58. if (strcmp(s, p->s_name) == 0)
  59. return(p);
  60. return(NULL);
  61. }
  62. void freesymtab(struct symtab *p) /* free space used by symtab at p */
  63. {
  64. struct symtab *q;
  65. for ( ; p != NULL; p = q) {
  66. q = p->s_next;
  67. free(p->s_name); /* assumes done with tostring */
  68. free((char *)p);
  69. }
  70. }
  71. void freedef(char *s) /* free definition for string s */
  72. {
  73. struct symtab *p, *q, *op;
  74. for (p = op = q = stack[nstack].p_symtab; p != NULL; p = p->s_next) {
  75. if (strcmp(s, p->s_name) == 0) { /* got it */
  76. if (p->s_type != DEFNAME)
  77. break;
  78. if (p == op) /* 1st elem */
  79. stack[nstack].p_symtab = p->s_next;
  80. else
  81. q->s_next = p->s_next;
  82. free(p->s_name);
  83. free(p->s_val.p);
  84. free((char *)p);
  85. return;
  86. }
  87. q = p;
  88. }
  89. /* ERROR "%s is not defined at this point", s WARNING; */
  90. }