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