/[cvs]/stack/stack.c
ViewVC logotype

Diff of /stack/stack.c

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1.22 by masse, Sat Feb 2 18:11:54 2002 UTC revision 1.75 by masse, Wed Feb 13 00:16:00 2002 UTC
# Line 1  Line 1 
1  /* printf */  /* printf, sscanf, fgets, fprintf */
2  #include <stdio.h>  #include <stdio.h>
3  /* EXIT_SUCCESS */  /* exit, EXIT_SUCCESS, malloc, free */
4  #include <stdlib.h>  #include <stdlib.h>
5  /* NULL */  /* NULL */
6  #include <stddef.h>  #include <stddef.h>
7  /* dlopen, dlsym, dlerror */  /* dlopen, dlsym, dlerror */
8  #include <dlfcn.h>  #include <dlfcn.h>
9  /* assert */  /* strcmp, strcpy, strlen, strcat, strdup */
10  #include <assert.h>  #include <string.h>
11    
12  #define HASHTBLSIZE 65536  #define HASHTBLSIZE 2048
13    
14  typedef struct stack_item  /* First, define some types. */
15  {  
16    /* A value of some type */
17    typedef struct {
18    enum {    enum {
19      value,                      /* Integer */      integer,
20      string,      string,
     ref,                        /* Reference (to an element in the  
                                    hash table) */  
21      func,                       /* Function pointer */      func,                       /* Function pointer */
22      symbol,      symb,
23      list      list
24    } type;                       /* Type of stack element */    } type;                       /* Type of stack element */
25    
26    union {    union {
27      void* ptr;                  /* Pointer to the content */      void *ptr;                  /* Pointer to the content */
28      int val;                    /* ...or an integer */      int val;                    /* ...or an integer */
29    } content;                    /* Stores a pointer or an integer */    } content;                    /* Stores a pointer or an integer */
30    
31    char* id;                     /* Symbol name */    int refcount;                 /* Reference counter */
32    struct stack_item* next;      /* Next element */  
33    } value;
34    
35    /* A symbol with a name and possible value */
36    /* (These do not need reference counters, they are kept unique by
37       hashing.) */
38    typedef struct symbol_struct {
39      char *id;                     /* Symbol name */
40      value *val;                   /* The value (if any) bound to it */
41      struct symbol_struct *next;   /* In case of hashing conflicts, a */
42    } symbol;                       /* symbol is a kind of stack item. */
43    
44    /* A type for a hash table for symbols */
45    typedef symbol *hashtbl[HASHTBLSIZE]; /* Hash table declaration */
46    
47    /* An item (value) on a stack */
48    typedef struct stackitem_struct
49    {
50      value *item;                  /* The value on the stack */
51                                    /* (This is never NULL) */
52      struct stackitem_struct *next; /* Next item */
53  } stackitem;  } stackitem;
54    
55    /* An environment; gives access to the stack and a hash table of
56       defined symbols */
57    typedef struct {
58      stackitem *head;              /* Head of the stack */
59      hashtbl symbols;              /* Hash table of all variable bindings */
60      int err;                      /* Error flag */
61      int non_eval_flag;
62      char *in_string;              /* Input pending to be read */
63    } environment;
64    
65    /* A type for pointers to external functions */
66    typedef void (*funcp)(environment *); /* funcp is a pointer to a void
67                                             function (environment *) */
68    
69    /* Initialize a newly created environment */
70    void init_env(environment *env)
71    {
72      int i;
73    
74      env->in_string= NULL;
75      env->err= 0;
76      env->non_eval_flag= 0;
77      for(i= 0; i<HASHTBLSIZE; i++)
78        env->symbols[i]= NULL;
79    }
80    
81    void printerr(const char* in_string) {
82      fprintf(stderr, "Err: %s\n", in_string);
83    }
84    
85  typedef stackitem* hashtbl[HASHTBLSIZE]; /* Hash table declaration */  /* Throw away a value */
86  typedef void (*funcp)(stackitem**); /* funcp is a pointer to a  void free_val(value *val){
87                                         void function (stackitem **) */    stackitem *item, *temp;
88    
89      val->refcount--;              /* Decrease the reference count */
90      if(val->refcount == 0){
91        switch (val->type){         /* and free the contents if necessary */
92        case string:
93          free(val->content.ptr);
94          break;
95        case list:                  /* lists needs to be freed recursively */
96          item=val->content.ptr;
97          while(item != NULL) {     /* for all stack items */
98            free_val(item->item);   /* free the value */
99            temp=item->next;        /* save next ptr */
100            free(item);             /* free the stackitem */
101            item=temp;              /* go to next stackitem */
102          }
103          free(val);                /* Free the actual list value */
104          break;
105        case integer:
106        case func:
107        case symb:
108          break;
109        }
110      }
111    }
112    
113  /* Initialize a newly created hash table. */  /* Discard the top element of the stack. */
114  void init_hashtbl(hashtbl out_hash)  extern void toss(environment *env)
115  {  {
116    long i;    stackitem *temp= env->head;
117    
118    for(i= 0; i<HASHTBLSIZE; i++)    if((env->head)==NULL) {
119      out_hash[i]= NULL;      printerr("Too Few Arguments");
120        env->err=1;
121        return;
122      }
123      
124      free_val(env->head->item);    /* Free the value */
125      env->head= env->head->next;   /* Remove the top stack item */
126      free(temp);                   /* Free the old top stack item */
127  }  }
128    
129  /* Returns a pointer to an element in the hash table. */  /* Returns a pointer to a pointer to an element in the hash table. */
130  stackitem** hash(hashtbl in_hashtbl, const char* in_string)  symbol **hash(hashtbl in_hashtbl, const char *in_string)
131  {  {
132    long i= 0;    int i= 0;
133    unsigned long out_hash= 0;    unsigned int out_hash= 0;
134    char key= '\0';    char key= '\0';
135    stackitem** position;    symbol **position;
136        
137    while(1){                     /* Hash in_string */    while(1){                     /* Hash in_string */
138      key= in_string[i++];      key= in_string[i++];
# Line 64  stackitem** hash(hashtbl in_hashtbl, con Line 144  stackitem** hash(hashtbl in_hashtbl, con
144    out_hash= out_hash%HASHTBLSIZE;    out_hash= out_hash%HASHTBLSIZE;
145    position= &(in_hashtbl[out_hash]);    position= &(in_hashtbl[out_hash]);
146    
147    while(position != NULL){    while(1){
148      if(*position==NULL)         /* If empty */      if(*position==NULL)         /* If empty */
149        return position;        return position;
150            
# Line 73  stackitem** hash(hashtbl in_hashtbl, con Line 153  stackitem** hash(hashtbl in_hashtbl, con
153    
154      position= &((*position)->next); /* Try next */      position= &((*position)->next); /* Try next */
155    }    }
   return NULL;                  /* end of list reached without finding  
                                    an empty position */  
156  }  }
157    
158  /* Generic push function. */  /* Push a value onto the stack */
159  int push(stackitem** stack_head, stackitem* in_item)  void push_val(environment *env, value *val)
160  {  {
161    in_item->next= *stack_head;    stackitem *new_item= malloc(sizeof(stackitem));
162    *stack_head= in_item;    new_item->item= val;
163    return 1;    val->refcount++;
164      new_item->next= env->head;
165      env->head= new_item;
166  }  }
167    
168  /* Push a value on the stack. */  /* Push an integer onto the stack. */
169  int push_val(stackitem** stack_head, int in_val)  void push_int(environment *env, int in_val)
170  {  {
171    stackitem* new_item= malloc(sizeof(stackitem));    value *new_value= malloc(sizeof(value));
172    assert(new_item != NULL);    
173    new_item->content.val= in_val;    new_value->content.val= in_val;
174    new_item->type= value;    new_value->type= integer;
175      new_value->refcount=1;
176    
177    push(stack_head, new_item);    push_val(env, new_value);
   return 1;  
178  }  }
179    
180  /* Copy a string onto the stack. */  /* Copy a string onto the stack. */
181  int push_cstring(stackitem** stack_head, const char* in_string)  void push_cstring(environment *env, const char *in_string)
182  {  {
183    stackitem* new_item= malloc(sizeof(stackitem));    value *new_value= malloc(sizeof(value));
184    new_item->content.ptr= malloc(strlen(in_string)+1);  
185    strcpy(new_item->content.ptr, in_string);    new_value->content.ptr= malloc(strlen(in_string)+1);
186    new_item->type= string;    strcpy(new_value->content.ptr, in_string);
187      new_value->type= string;
188      new_value->refcount=1;
189    
190      push_val(env, new_value);
191    }
192    
193    /* Mangle a symbol name to a valid C identifier name */
194    char *mangle_str(const char *old_string){
195      char validchars[]
196        ="0123456789abcdef";
197      char *new_string, *current;
198    
199      new_string=malloc((strlen(old_string)*2)+4);
200      strcpy(new_string, "sx_");    /* Stack eXternal */
201      current=new_string+3;
202      while(old_string[0] != '\0'){
203        current[0]=validchars[(unsigned char)(old_string[0])/16];
204        current[1]=validchars[(unsigned char)(old_string[0])%16];
205        current+=2;
206        old_string++;
207      }
208      current[0]='\0';
209    
210    push(stack_head, new_item);    return new_string;            /* The caller must free() it */
   return 1;  
211  }  }
212    
213  /* Create a new hash entry. */  extern void mangle(environment *env){
214  int mk_hashentry(hashtbl in_hashtbl, stackitem* in_item, const char* id)    value *new_value;
215  {    char *new_string;
   in_item->id= malloc(strlen(id)+1);  
216    
217    strcpy(in_item->id, id);    if((env->head)==NULL) {
218    push(hash(in_hashtbl, id), in_item);      printerr("Too Few Arguments");
219        env->err=1;
220        return;
221      }
222    
223    return 1;    if(env->head->item->type!=string) {
224  }      printerr("Bad Argument Type");
225        env->err=2;
226        return;
227      }
228    
229  /* Define a new function in the hash table. */    new_string= mangle_str((const char *)(env->head->item->content.ptr));
 void def_func(hashtbl in_hashtbl, funcp in_func, const char* id)  
 {  
   stackitem* temp= malloc(sizeof(stackitem));  
230    
231    temp->type= func;    toss(env);
232    temp->content.ptr= in_func;    if(env->err) return;
233    
234    mk_hashentry(in_hashtbl, temp, id);    new_value= malloc(sizeof(value));
235  }    new_value->content.ptr= new_string;
236      new_value->type= string;
237      new_value->refcount=1;
238    
239  /* Define a new symbol in the hash table. */    push_val(env, new_value);
 void def_sym(hashtbl in_hashtbl, const char* id)  
 {  
   stackitem* temp= malloc(sizeof(stackitem));  
     
   temp->type= symbol;  
   mk_hashentry(in_hashtbl, temp, id);  
240  }  }
241    
242  /* Push a reference to an entry in the hash table onto the stack. */  /* Push a symbol onto the stack. */
243  int push_ref(stackitem** stack_head, hashtbl in_hash, const char* in_string)  void push_sym(environment *env, const char *in_string)
244  {  {
245    static void* handle= NULL;    value *new_value;             /* A new symbol value */
246    void* symbol;    /* ...which might point to... */
247      symbol **new_symbol;          /* (if needed) A new actual symbol */
248      /* ...which, if possible, will be bound to... */
249      value *new_fvalue;            /* (if needed) A new function value */
250      /* ...which will point to... */
251      void *funcptr;                /* A function pointer */
252    
253    stackitem* new_item= malloc(sizeof(stackitem));    static void *handle= NULL;    /* Dynamic linker handle */
254    new_item->content.ptr= *hash(in_hash, in_string);    const char *dlerr;            /* Dynamic linker error */
255    new_item->type= ref;    char *mangled;                /* Mangled function name */
256    
257    if(new_item->content.ptr==NULL) { /* If hash entry empty */    new_value= malloc(sizeof(value));
     if(handle==NULL)            /* If no handle */  
       handle= dlopen(NULL, RTLD_LAZY);      
258    
259      symbol= dlsym(handle, in_string); /* Get function pointer */    /* The new value is a symbol */
260      if(dlerror()==NULL)         /* If existing function pointer */    new_value->type= symb;
261        def_func(in_hash, symbol, in_string); /* Store function pointer */    new_value->refcount= 1;
     else  
       def_sym(in_hash, in_string); /* Make symbol */  
         
     new_item->content.ptr= *hash(in_hash, in_string); /* XXX */  
     new_item->type= ref;  
   }  
262    
263    push(stack_head, new_item);    /* Look up the symbol name in the hash table */
264    return 1;    new_symbol= hash(env->symbols, in_string);
265  }    new_value->content.ptr= *new_symbol;
266    
267  void printerr(const char* in_string) {    if(*new_symbol==NULL) { /* If symbol was undefined */
   fprintf(stderr, "Err: %s\n", in_string);  
 }  
268    
269  /* Discard the top element of the stack. */      /* Create a new symbol */
270  extern void toss(stackitem** stack_head)      (*new_symbol)= malloc(sizeof(symbol));
271  {      (*new_symbol)->val= NULL;   /* undefined value */
272    stackitem* temp= *stack_head;      (*new_symbol)->next= NULL;
273        (*new_symbol)->id= malloc(strlen(in_string)+1);
274        strcpy((*new_symbol)->id, in_string);
275    
276    if((*stack_head)==NULL) {      /* Intern the new symbol in the hash table */
277      printerr("Stack empty");      new_value->content.ptr= *new_symbol;
     return;  
   }  
     
   if((*stack_head)->type==string)  
     free((*stack_head)->content.ptr);  
278    
279    *stack_head= (*stack_head)->next;      /* Try to load the symbol name as an external function, to see if
280    free(temp);         we should bind the symbol to a new function pointer value */
281        if(handle==NULL)            /* If no handle */
282          handle= dlopen(NULL, RTLD_LAZY);
283    
284        funcptr= dlsym(handle, in_string); /* Get function pointer */
285        dlerr=dlerror();
286        if(dlerr != NULL) {         /* If no function was found */
287          mangled=mangle_str(in_string);
288          funcptr= dlsym(handle, mangled); /* try mangling it */
289          free(mangled);
290          dlerr=dlerror();
291        }
292        if(dlerr==NULL) {           /* If a function was found */
293          new_fvalue= malloc(sizeof(value)); /* Create a new value */
294          new_fvalue->type=func;    /* The new value is a function pointer */
295          new_fvalue->content.ptr=funcptr; /* Store function pointer */
296          (*new_symbol)->val= new_fvalue; /* Bind the symbol to the new
297                                             function value */
298          new_fvalue->refcount= 1;
299        }
300      }
301      push_val(env, new_value);
302  }  }
303    
304  /* Print newline. */  /* Print newline. */
# Line 195  extern void nl() Line 307  extern void nl()
307    printf("\n");    printf("\n");
308  }  }
309    
310  /* Prints the top element of the stack. */  /* Gets the type of a value */
311  void print_(stackitem** stack_head)  extern void type(environment *env){
312  {    int typenum;
313    if((*stack_head)==NULL) {  
314      printerr("Stack empty");    if((env->head)==NULL) {
315        printerr("Too Few Arguments");
316        env->err=1;
317      return;      return;
318    }    }
319      typenum=env->head->item->type;
320      toss(env);
321      switch(typenum){
322      case integer:
323        push_sym(env, "integer");
324        break;
325      case string:
326        push_sym(env, "string");
327        break;
328      case symb:
329        push_sym(env, "symbol");
330        break;
331      case func:
332        push_sym(env, "function");
333        break;
334      case list:
335        push_sym(env, "list");
336        break;
337      }
338    }    
339    
340    switch((*stack_head)->type) {  /* Prints the top element of the stack. */
341    case value:  void print_h(stackitem *stack_head)
342      printf("%d", (*stack_head)->content.val);  {
343      switch(stack_head->item->type) {
344      case integer:
345        printf("%d", stack_head->item->content.val);
346      break;      break;
347    case string:    case string:
348      printf("\"%s\"", (char*)(*stack_head)->content.ptr);      printf("%s", (char*)stack_head->item->content.ptr);
349      break;      break;
350    case ref:    case symb:
351      printf("%s", ((stackitem*)(*stack_head)->content.ptr)->id);      printf("%s", ((symbol *)(stack_head->item->content.ptr))->id);
352      break;      break;
353    case symbol:    case func:
354    default:      printf("#<function %p>", (funcp)(stack_head->item->content.ptr));
355      printf("%p", (*stack_head)->content.ptr);      break;
356      case list:
357        /* A list is just a stack, so make stack_head point to it */
358        stack_head=(stackitem *)(stack_head->item->content.ptr);
359        printf("[ ");
360        while(stack_head != NULL) {
361          print_h(stack_head);
362          printf(" ");
363          stack_head=stack_head->next;
364        }
365        printf("]");
366      break;      break;
367    }    }
368  }  }
369    
370    extern void print_(environment *env) {
371      if(env->head==NULL) {
372        printerr("Too Few Arguments");
373        env->err=1;
374        return;
375      }
376      print_h(env->head);
377    }
378    
379  /* Prints the top element of the stack and then discards it. */  /* Prints the top element of the stack and then discards it. */
380  extern void print(stackitem** stack_head)  extern void print(environment *env)
381  {  {
382    print_(stack_head);    print_(env);
383    toss(stack_head);    if(env->err) return;
384      toss(env);
385  }  }
386    
387  /* Only to be called by function printstack. */  /* Only to be called by function printstack. */
388  void print_st(stackitem* stack_head, long counter)  void print_st(stackitem *stack_head, long counter)
389  {  {
390    if(stack_head->next != NULL)    if(stack_head->next != NULL)
391      print_st(stack_head->next, counter+1);      print_st(stack_head->next, counter+1);
   
392    printf("%ld: ", counter);    printf("%ld: ", counter);
393    print_(&stack_head);    print_h(stack_head);
394    nl();    nl();
395  }  }
396    
397  /* Prints the stack. */  /* Prints the stack. */
398  extern void printstack(stackitem** stack_head)  extern void printstack(environment *env)
399  {  {
400    if(*stack_head != NULL) {    if(env->head == NULL) {
401      print_st(*stack_head, 1);      return;
     nl();  
   } else {  
     printerr("Stack empty");  
402    }    }
403      print_st(env->head, 1);
404      nl();
405  }  }
406    
407  /* If the top element is a reference, determine if it's a reference to a  /* Swap the two top elements on the stack. */
408     function, and if it is, toss the reference and execute the function. */  extern void swap(environment *env)
 extern void eval(stackitem** stack_head)  
409  {  {
410    funcp in_func;    stackitem *temp= env->head;
411    stackitem* temp= *stack_head;    
412      if(env->head==NULL || env->head->next==NULL) {
413    if(temp==NULL) {      printerr("Too Few Arguments");
414      printerr("Stack empty");      env->err=1;
415      return;      return;
416    }    }
417    
418    while(temp->type==ref)    env->head= env->head->next;
419      temp= temp->content.ptr;    temp->next= env->head->next;
420      env->head->next= temp;
421    }
422    
423    if(temp->type==func) {  /* Rotate the first three elements on the stack. */
424      in_func= (funcp)(temp->content.ptr);  extern void rot(environment *env)
425      toss(stack_head);  {
426      (*in_func)(stack_head);    stackitem *temp= env->head;
427      
428      if(env->head==NULL || env->head->next==NULL
429          || env->head->next->next==NULL) {
430        printerr("Too Few Arguments");
431        env->err=1;
432      return;      return;
433    }    }
434        
435    printerr("Couldn't evaluate");    env->head= env->head->next->next;
436      temp->next->next= env->head->next;
437      env->head->next= temp;
438  }  }
439    
440  /* Make a list. */  /* Recall a value from a symbol, if bound */
441  extern void pack(stackitem** stack_head)  extern void rcl(environment *env)
442  {  {
443    void* delimiter;    value *val;
   stackitem *iterator, *temp, *pack;  
444    
445    if((*stack_head)==NULL) {    if(env->head == NULL) {
446      printerr("Stack empty");      printerr("Too Few Arguments");
447        env->err=1;
448      return;      return;
449    }    }
450    
451    delimiter= (*stack_head)->content.ptr; /* Get delimiter */    if(env->head->item->type!=symb) {
452    toss(stack_head);      printerr("Bad Argument Type");
453        env->err=2;
454    iterator= *stack_head;      return;
455      }
   /* Search for first delimiter */  
   while(iterator->next!=NULL && iterator->next->content.ptr!=delimiter)  
     iterator= iterator->next;  
   
   /* Extract list */  
   temp= *stack_head;  
   *stack_head= iterator->next;  
   iterator->next= NULL;  
     
   if(*stack_head!=NULL && (*stack_head)->content.ptr==delimiter)  
     toss(stack_head);  
   
   /* Push list */  
   pack= malloc(sizeof(stackitem));  
   pack->type= list;  
   pack->content.ptr= temp;  
456    
457    push(stack_head, pack);    val=((symbol *)(env->head->item->content.ptr))->val;
458      if(val == NULL){
459        printerr("Unbound Variable");
460        env->err=3;
461        return;
462      }
463      toss(env);            /* toss the symbol */
464      if(env->err) return;
465      push_val(env, val); /* Return its bound value */
466  }  }
467    
468  /* Parse input. */  /* If the top element is a symbol, determine if it's bound to a
469  int stack_read(stackitem** stack_head, hashtbl in_hash, char* in_line)     function value, and if it is, toss the symbol and execute the
470       function. */
471    extern void eval(environment *env)
472  {  {
473    char *temp, *rest;    funcp in_func;
474    int itemp;    value* temp_val;
475    size_t inlength= strlen(in_line)+1;    stackitem* iterator;
   int convert= 0;  
   static int non_eval_flag= 0;  
476    
477    temp= malloc(inlength);    if(env->head==NULL) {
478    rest= malloc(inlength);      printerr("Too Few Arguments");
479        env->err=1;
480        return;
481      }
482    
483    do {   eval_start:
484      /* If string */  
485      if((convert= sscanf(in_line, "\"%[^\"\n\r]\" %[^\n\r]", temp, rest))) {    switch(env->head->item->type) {
486        push_cstring(stack_head, temp);      /* if it's a symbol */
487        break;    case symb:
488      }      rcl(env);                   /* get its contents */
489      /* If value */      if(env->err) return;
490      if((convert= sscanf(in_line, "%d %[^\n\r]", &itemp, rest))) {      if(env->head->item->type!=symb){ /* don't recurse symbols */
491        push_val(stack_head, itemp);        goto eval_start;
       break;  
     }  
     /* Escape ';' with '\' */  
     if((convert= sscanf(in_line, "\\%c%[^\n\r]", temp, rest))) {  
       temp[1]= '\0';  
       push_ref(stack_head, in_hash, temp);  
       break;  
     }  
     /* If symbol */  
     if((convert= sscanf(in_line, "%[^][ ;\n\r]%[^\n\r]", temp, rest))) {  
         push_ref(stack_head, in_hash, temp);  
         break;  
492      }      }
493      /* If single char */      return;
494      if((convert= sscanf(in_line, "%c%[^\n\r]", temp, rest))) {  
495        if(*temp==';') {      /* If it's a lone function value, run it */
496          if(!non_eval_flag) {    case func:
497            eval(stack_head);             /* Evaluate top element */      in_func= (funcp)(env->head->item->content.ptr);
498            break;      toss(env);
499        if(env->err) return;
500        return (*in_func)(env);
501    
502        /* If it's a list */
503      case list:
504        temp_val= env->head->item;
505        env->head->item->refcount++;
506        toss(env);
507        if(env->err) return;
508        iterator= (stackitem*)temp_val->content.ptr;
509        while(iterator!=NULL) {
510          push_val(env, iterator->item);
511          if(env->head->item->type==symb
512            && strcmp(";", ((symbol*)(env->head->item->content.ptr))->id)==0) {
513            toss(env);
514            if(env->err) return;
515            if(iterator->next == NULL){
516              free_val(temp_val);
517              goto eval_start;
518          }          }
519                    eval(env);
520          push_ref(stack_head, in_hash, ";");          if(env->err) return;
         break;  
521        }        }
522          iterator= iterator->next;
523        }
524        free_val(temp_val);
525        return;
526    
527        if(*temp==']') {    default:
528          push_ref(stack_head, in_hash, "[");      return;
529          pack(stack_head);    }
530          if(non_eval_flag!=0)  }
           non_eval_flag--;  
         break;  
       }  
531    
532        if(*temp=='[') {  /* Reverse (flip) a list */
533          push_ref(stack_head, in_hash, "[");  extern void rev(environment *env){
534          non_eval_flag++;    stackitem *old_head, *new_head, *item;
535          break;  
536        }    if((env->head)==NULL) {
537      }      printerr("Too Few Arguments");
538    } while(0);      env->err=1;
539        return;
540      }
541    
542      if(env->head->item->type!=list) {
543        printerr("Bad Argument Type");
544        env->err=2;
545        return;
546      }
547    
548    free(temp);    old_head=(stackitem *)(env->head->item->content.ptr);
549      new_head=NULL;
550      while(old_head != NULL){
551        item=old_head;
552        old_head=old_head->next;
553        item->next=new_head;
554        new_head=item;
555      }
556      env->head->item->content.ptr=new_head;
557    }
558    
559    if(convert<2) {  /* Make a list. */
560      free(rest);  extern void pack(environment *env)
561      return 0;  {
562      stackitem *iterator, *temp;
563      value *pack;
564    
565      iterator= env->head;
566    
567      if(iterator==NULL
568         || (iterator->item->type==symb
569         && ((symbol*)(iterator->item->content.ptr))->id[0]=='[')) {
570        temp= NULL;
571        toss(env);
572      } else {
573        /* Search for first delimiter */
574        while(iterator->next!=NULL
575              && (iterator->next->item->type!=symb
576              || ((symbol*)(iterator->next->item->content.ptr))->id[0]!='['))
577          iterator= iterator->next;
578        
579        /* Extract list */
580        temp= env->head;
581        env->head= iterator->next;
582        iterator->next= NULL;
583        
584        if(env->head!=NULL)
585          toss(env);
586    }    }
587      
588    stack_read(stack_head, in_hash, rest);    /* Push list */
589        pack= malloc(sizeof(value));
590    free(rest);    pack->type= list;
591    return 1;    pack->content.ptr= temp;
592      pack->refcount= 1;
593    
594      push_val(env, pack);
595      rev(env);
596  }  }
597    
598  /* Relocate elements of the list on the stack. */  /* Relocate elements of the list on the stack. */
599  extern void expand(stackitem** stack_head)  extern void expand(environment *env)
600  {  {
601    stackitem *temp, *new_head;    stackitem *temp, *new_head;
602    
603    /* Is top element a list? */    /* Is top element a list? */
604    if((*stack_head)==NULL || (*stack_head)->type!=list) {    if(env->head==NULL) {
605      printerr("Stack empty or not a list");      printerr("Too Few Arguments");
606        env->err=1;
607        return;
608      }
609      if(env->head->item->type!=list) {
610        printerr("Bad Argument Type");
611        env->err=2;
612      return;      return;
613    }    }
614    
615      rev(env);
616    
617      if(env->err)
618        return;
619    
620    /* The first list element is the new stack head */    /* The first list element is the new stack head */
621    new_head= temp= (*stack_head)->content.ptr;    new_head= temp= env->head->item->content.ptr;
622    toss(stack_head);  
623      env->head->item->refcount++;
624      toss(env);
625    
626    /* Search the end of the list */    /* Find the end of the list */
627    while(temp->next!=NULL)    while(temp->next!=NULL)
628      temp= temp->next;      temp= temp->next;
629    
630    /* Connect the the tail of the list with the old stack head */    /* Connect the tail of the list with the old stack head */
631    temp->next= *stack_head;    temp->next= env->head;
632    *stack_head= new_head;        /* ...and voila! */    env->head= new_head;          /* ...and voila! */
 }  
   
 /* Swap the two top elements on the stack. */  
 extern void swap(stackitem** stack_head)  
 {  
   stackitem* temp= (*stack_head);  
     
   if((*stack_head)==NULL) {  
     printerr("Stack empty");  
     return;  
   }  
   
   if((*stack_head)->next==NULL)  
     return;  
633    
634    *stack_head= (*stack_head)->next;  }
   temp->next= (*stack_head)->next;  
   (*stack_head)->next= temp;  
 }  
635    
636  /* Compares two elements by reference. */  /* Compares two elements by reference. */
637  extern void eq(stackitem** stack_head)  extern void eq(environment *env)
638  {  {
639    void *left, *right;    void *left, *right;
640    int result;    int result;
641    
642    if((*stack_head)==NULL || (*stack_head)->next==NULL) {    if((env->head)==NULL || env->head->next==NULL) {
643      printerr("Not enough elements to compare");      printerr("Too Few Arguments");
644        env->err=1;
645      return;      return;
646    }    }
647    
648    left= (*stack_head)->content.ptr;    left= env->head->item->content.ptr;
649    swap(stack_head);    swap(env);
650    right= (*stack_head)->content.ptr;    right= env->head->item->content.ptr;
651    result= (left==right);    result= (left==right);
652        
653    toss(stack_head); toss(stack_head);    toss(env); toss(env);
654    push_val(stack_head, (left==right));    push_int(env, result);
655  }  }
656    
657  /* Negates the top element on the stack. */  /* Negates the top element on the stack. */
658  extern void not(stackitem** stack_head)  extern void not(environment *env)
659  {  {
660    int value;    int val;
661    
662      if((env->head)==NULL) {
663        printerr("Too Few Arguments");
664        env->err=1;
665        return;
666      }
667    
668    if((*stack_head)==NULL || (*stack_head)->type!=value) {    if(env->head->item->type!=integer) {
669      printerr("Stack empty or element is not a value");      printerr("Bad Argument Type");
670        env->err=2;
671      return;      return;
672    }    }
673    
674    value= (*stack_head)->content.val;    val= env->head->item->content.val;
675    toss(stack_head);    toss(env);
676    push_val(stack_head, !value);    push_int(env, !val);
677  }  }
678    
679  /* Compares the two top elements on the stack and return 0 if they're the  /* Compares the two top elements on the stack and return 0 if they're the
680     same. */     same. */
681  extern void neq(stackitem** stack_head)  extern void neq(environment *env)
682  {  {
683    eq(stack_head);    eq(env);
684    not(stack_head);    not(env);
685  }  }
686    
687  /* Give a symbol some content. */  /* Give a symbol some content. */
688  extern void def(stackitem** stack_head)  extern void def(environment *env)
689  {  {
690    stackitem *temp, *value;    symbol *sym;
691    
692    if(*stack_head==NULL || (*stack_head)->next==NULL    /* Needs two values on the stack, the top one must be a symbol */
693       || (*stack_head)->type!=ref) {    if(env->head==NULL || env->head->next==NULL) {
694      printerr("Define what?");      printerr("Too Few Arguments");
695        env->err=1;
696      return;      return;
697    }    }
698    
699    temp= (*stack_head)->content.ptr;    if(env->head->item->type!=symb) {
700    value= (*stack_head)->next;      printerr("Bad Argument Type");
701    temp->content= value->content;      env->err=2;
702    value->content.ptr=NULL;      return;
703    temp->type= value->type;    }
704    
705      /* long names are a pain */
706      sym=env->head->item->content.ptr;
707    
708    toss(stack_head); toss(stack_head);    /* if the symbol was bound to something else, throw it away */
709      if(sym->val != NULL)
710        free_val(sym->val);
711    
712      /* Bind the symbol to the value */
713      sym->val= env->head->next->item;
714      sym->val->refcount++;         /* Increase the reference counter */
715    
716      toss(env); toss(env);
717  }  }
718    
719  /* Quit stack. */  /* Quit stack. */
720  extern void quit()  extern void quit(environment *env)
721  {  {
722    exit(EXIT_SUCCESS);    exit(EXIT_SUCCESS);
723  }  }
724    
725    /* Clear stack */
726    extern void clear(environment *env)
727    {
728      while(env->head!=NULL)
729        toss(env);
730    }
731    
732    /* List all defined words */
733    extern void words(environment *env)
734    {
735      symbol *temp;
736      int i;
737      
738      for(i= 0; i<HASHTBLSIZE; i++) {
739        temp= env->symbols[i];
740        while(temp!=NULL) {
741          printf("%s\n", temp->id);
742          temp= temp->next;
743        }
744      }
745    }
746    
747    /* Forgets a symbol (remove it from the hash table) */
748    extern void forget(environment *env)
749    {
750      char* sym_id;
751      stackitem *stack_head= env->head;
752      symbol **hash_entry, *temp;
753    
754      if(stack_head==NULL) {
755        printerr("Too Few Arguments");
756        env->err=1;
757        return;
758      }
759      
760      if(stack_head->item->type!=symb) {
761        printerr("Bad Argument Type");
762        env->err=2;
763        return;
764      }
765    
766      sym_id= ((symbol*)(stack_head->item->content.ptr))->id;
767      toss(env);
768    
769      hash_entry= hash(env->symbols, sym_id);
770      temp= *hash_entry;
771      *hash_entry= (*hash_entry)->next;
772      
773      if(temp->val!=NULL) {
774        free_val(temp->val);
775      }
776      free(temp->id);
777      free(temp);
778    }
779    
780    /* Returns the current error number to the stack */
781    extern void errn(environment *env){
782      push_int(env, env->err);
783    }
784    
785    extern void read(environment*);
786    
787  int main()  int main()
788  {  {
789    stackitem* s= NULL;    environment myenv;
   hashtbl myhash;  
   char in_string[100];  
790    
791    init_hashtbl(myhash);    init_env(&myenv);
792    
793    printf("okidok\n ");    while(1) {
794        if(myenv.in_string==NULL)
795          printstack(&myenv);
796        read(&myenv);
797        if(myenv.err) {
798          printf("(error %d) ", myenv.err);
799          myenv.err=0;
800        } else if(myenv.head!=NULL
801                  && myenv.head->item->type==symb
802                  && ((symbol*)(myenv.head->item->content.ptr))->id[0]==';') {
803          toss(&myenv);             /* No error check in main */
804          eval(&myenv);
805        }
806      }
807      quit(&myenv);
808      return EXIT_FAILURE;
809    }
810    
811    while(fgets(in_string, 100, stdin) != NULL) {  /* + */
812      stack_read(&s, myhash, in_string);  extern void sx_2b(environment *env) {
813      printf("okidok\n ");    int a, b;
814      size_t len;
815      char* new_string;
816      value *a_val, *b_val;
817    
818      if((env->head)==NULL || env->head->next==NULL) {
819        printerr("Too Few Arguments");
820        env->err=1;
821        return;
822    }    }
823    
824    exit(EXIT_SUCCESS);    if(env->head->item->type==string
825         && env->head->next->item->type==string) {
826        a_val= env->head->item;
827        b_val= env->head->next->item;
828        a_val->refcount++;
829        b_val->refcount++;
830        toss(env); if(env->err) return;
831        toss(env); if(env->err) return;
832        len= strlen(a_val->content.ptr)+strlen(b_val->content.ptr)+1;
833        new_string= malloc(len);
834        strcpy(new_string, b_val->content.ptr);
835        strcat(new_string, a_val->content.ptr);
836        free_val(a_val); free_val(b_val);
837        push_cstring(env, new_string);
838        free(new_string);
839        return;
840      }
841      
842      if(env->head->item->type!=integer
843         || env->head->next->item->type!=integer) {
844        printerr("Bad Argument Type");
845        env->err=2;
846        return;
847      }
848      a=env->head->item->content.val;
849      toss(env);
850      if(env->err) return;
851      if(env->head->item->refcount == 1)
852        env->head->item->content.val += a;
853      else {
854        b=env->head->item->content.val;
855        toss(env);
856        if(env->err) return;
857        push_int(env, a+b);
858      }
859    }
860    
861    /* - */
862    extern void sx_2d(environment *env) {
863      int a, b;
864    
865      if((env->head)==NULL || env->head->next==NULL) {
866        printerr("Too Few Arguments");
867        env->err=1;
868        return;
869      }
870      
871      if(env->head->item->type!=integer
872         || env->head->next->item->type!=integer) {
873        printerr("Bad Argument Type");
874        env->err=2;
875        return;
876      }
877      a=env->head->item->content.val;
878      toss(env);
879      if(env->err) return;
880      if(env->head->item->refcount == 1)
881        env->head->item->content.val -= a;
882      else {
883        b=env->head->item->content.val;
884        toss(env);
885        if(env->err) return;
886        push_int(env, b-a);
887      }
888  }  }
889    
890  /* Local Variables: */  /* > */
891  /* compile-command:"make CFLAGS=\"-Wall -g -rdynamic -ldl\" stack" */  extern void sx_3e(environment *env) {
892  /* End: */    int a, b;
893    
894      if((env->head)==NULL || env->head->next==NULL) {
895        printerr("Too Few Arguments");
896        env->err=1;
897        return;
898      }
899      
900      if(env->head->item->type!=integer
901         || env->head->next->item->type!=integer) {
902        printerr("Bad Argument Type");
903        env->err=2;
904        return;
905      }
906      a=env->head->item->content.val;
907      toss(env);
908      if(env->err) return;
909      if(env->head->item->refcount == 1)
910        env->head->item->content.val = (env->head->item->content.val > a);
911      else {
912        b=env->head->item->content.val;
913        toss(env);
914        if(env->err) return;
915        push_int(env, b>a);
916      }
917    }
918    
919    /* Return copy of a value */
920    value *copy_val(value *old_value){
921      stackitem *old_item, *new_item, *prev_item;
922    
923      value *new_value=malloc(sizeof(value));
924    
925      new_value->type=old_value->type;
926      new_value->refcount=0;        /* This is increased if/when this
927                                       value is referenced somewhere, like
928                                       in a stack item or a variable */
929      switch(old_value->type){
930      case integer:
931        new_value->content.val=old_value->content.val;
932        break;
933      case string:
934        (char *)(new_value->content.ptr)
935          = strdup((char *)(old_value->content.ptr));
936        break;
937      case func:
938      case symb:
939        new_value->content.ptr=old_value->content.ptr;
940        break;
941      case list:
942        new_value->content.ptr=NULL;
943    
944        prev_item=NULL;
945        old_item=(stackitem *)(old_value->content.ptr);
946    
947        while(old_item != NULL) {   /* While list is not empty */
948          new_item= malloc(sizeof(stackitem));
949          new_item->item=copy_val(old_item->item); /* recurse */
950          new_item->next=NULL;
951          if(prev_item != NULL)     /* If this wasn't the first item */
952            prev_item->next=new_item; /* point the previous item to the
953                                         new item */
954          else
955            new_value->content.ptr=new_item;
956          old_item=old_item->next;
957          prev_item=new_item;
958        }    
959        break;
960      }
961      return new_value;
962    }
963    
964    /* duplicates an item on the stack */
965    extern void dup(environment *env) {
966      if((env->head)==NULL) {
967        printerr("Too Few Arguments");
968        env->err=1;
969        return;
970      }
971      push_val(env, copy_val(env->head->item));
972    }
973    
974    /* "if", If-Then */
975    extern void sx_6966(environment *env) {
976    
977      int truth;
978    
979      if((env->head)==NULL || env->head->next==NULL) {
980        printerr("Too Few Arguments");
981        env->err=1;
982        return;
983      }
984    
985      if(env->head->next->item->type != integer) {
986        printerr("Bad Argument Type");
987        env->err=2;
988        return;
989      }
990      
991      swap(env);
992      if(env->err) return;
993      
994      truth=env->head->item->content.val;
995    
996      toss(env);
997      if(env->err) return;
998    
999      if(truth)
1000        eval(env);
1001      else
1002        toss(env);
1003    }
1004    
1005    /* If-Then-Else */
1006    extern void ifelse(environment *env) {
1007    
1008      int truth;
1009    
1010      if((env->head)==NULL || env->head->next==NULL
1011         || env->head->next->next==NULL) {
1012        printerr("Too Few Arguments");
1013        env->err=1;
1014        return;
1015      }
1016    
1017      if(env->head->next->next->item->type != integer) {
1018        printerr("Bad Argument Type");
1019        env->err=2;
1020        return;
1021      }
1022      
1023      rot(env);
1024      if(env->err) return;
1025      
1026      truth=env->head->item->content.val;
1027    
1028      toss(env);
1029      if(env->err) return;
1030    
1031      if(!truth)
1032        swap(env);
1033      if(env->err) return;
1034    
1035      toss(env);
1036      if(env->err) return;
1037    
1038      eval(env);
1039    }
1040    
1041    /* while */
1042    extern void sx_7768696c65(environment *env) {
1043    
1044      int truth;
1045      value *loop, *test;
1046    
1047      if((env->head)==NULL || env->head->next==NULL) {
1048        printerr("Too Few Arguments");
1049        env->err=1;
1050        return;
1051      }
1052    
1053      loop= env->head->item;
1054      loop->refcount++;
1055      toss(env); if(env->err) return;
1056    
1057      test= env->head->item;
1058      test->refcount++;
1059      toss(env); if(env->err) return;
1060    
1061      do {
1062        push_val(env, test);
1063        eval(env);
1064        
1065        if(env->head->item->type != integer) {
1066          printerr("Bad Argument Type");
1067          env->err=2;
1068          return;
1069        }
1070        
1071        truth= env->head->item->content.val;
1072        toss(env); if(env->err) return;
1073        
1074        if(truth) {
1075          push_val(env, loop);
1076          eval(env);
1077        } else {
1078          toss(env);
1079        }
1080      
1081      } while(truth);
1082    
1083      free_val(test);
1084      free_val(loop);
1085    }
1086    
1087    /* For-loop */
1088    extern void sx_666f72(environment *env) {
1089      
1090      value *loop, *foo;
1091      stackitem *iterator;
1092      
1093      if((env->head)==NULL || env->head->next==NULL) {
1094        printerr("Too Few Arguments");
1095        env->err=1;
1096        return;
1097      }
1098    
1099      if(env->head->next->item->type != list) {
1100        printerr("Bad Argument Type");
1101        env->err=2;
1102        return;
1103      }
1104    
1105      loop= env->head->item;
1106      loop->refcount++;
1107      toss(env); if(env->err) return;
1108    
1109      foo= env->head->item;
1110      foo->refcount++;
1111      toss(env); if(env->err) return;
1112    
1113      iterator= foo->content.ptr;
1114    
1115      while(iterator!=NULL) {
1116        push_val(env, iterator->item);
1117        push_val(env, loop);
1118        eval(env); if(env->err) return;
1119        iterator= iterator->next;
1120      }
1121    
1122      free_val(loop);
1123      free_val(foo);
1124    }
1125    
1126    /* 'to' */
1127    extern void to(environment *env) {
1128      int i, start, ending;
1129      stackitem *temp_head;
1130      value *temp_val;
1131      
1132      if((env->head)==NULL || env->head->next==NULL) {
1133        printerr("Too Few Arguments");
1134        env->err=1;
1135        return;
1136      }
1137    
1138      if(env->head->item->type!=integer
1139         || env->head->next->item->type!=integer) {
1140        printerr("Bad Argument Type");
1141        env->err=2;
1142        return;
1143      }
1144    
1145      ending= env->head->item->content.val;
1146      toss(env); if(env->err) return;
1147      start= env->head->item->content.val;
1148      toss(env); if(env->err) return;
1149    
1150      temp_head= env->head;
1151      env->head= NULL;
1152    
1153      if(ending>=start) {
1154        for(i= ending; i>=start; i--)
1155          push_int(env, i);
1156      } else {
1157        for(i= ending; i<=start; i++)
1158          push_int(env, i);
1159      }
1160    
1161      temp_val= malloc(sizeof(value));
1162      temp_val->content.ptr= env->head;
1163      temp_val->refcount= 1;
1164      temp_val->type= list;
1165      env->head= temp_head;
1166      push_val(env, temp_val);
1167    }
1168    
1169    /* Read a string */
1170    extern void readline(environment *env) {
1171      char in_string[101];
1172    
1173      fgets(in_string, 100, stdin);
1174      push_cstring(env, in_string);
1175    }
1176    
1177    /* Read a value and place on stack */
1178    extern void read(environment *env) {
1179      const char symbform[]= "%[a-zA-Z0-9!$%*+./:<=>?@^_~-]%[\001-\377]";
1180      const char strform[]= "\"%[^\"]\"%[\001-\377]";
1181      const char intform[]= "%i%[\001-\377]";
1182      const char blankform[]= "%*[ \t]%[\001-\377]";
1183      const char ebrackform[]= "%*1[]]%[\001-\377]";
1184      const char semicform[]= "%*1[;]%[\001-\377]";
1185      const char bbrackform[]= "%*1[[]%[\001-\377]";
1186    
1187      int itemp;
1188      static int depth= 0;
1189      char *rest, *match;
1190      size_t inlength;
1191    
1192      if(env->in_string==NULL) {
1193        readline(env); if(env->err) return;
1194        
1195        env->in_string= malloc(strlen(env->head->item->content.ptr)+1);
1196        strcpy(env->in_string, env->head->item->content.ptr);
1197        toss(env); if(env->err) return;
1198      }
1199      
1200      inlength= strlen(env->in_string)+1;
1201      match= malloc(inlength);
1202      rest= malloc(inlength);
1203    
1204      if(sscanf(env->in_string, blankform, rest)) {
1205        ;
1206      } else if(sscanf(env->in_string, intform, &itemp, rest) > 0) {
1207        push_int(env, itemp);
1208      } else if(sscanf(env->in_string, strform, match, rest) > 0) {
1209        push_cstring(env, match);
1210      } else if(sscanf(env->in_string, symbform, match, rest) > 0) {
1211        push_sym(env, match);
1212      } else if(sscanf(env->in_string, ebrackform, rest) > 0) {
1213        pack(env); if(env->err) return;
1214        if(depth!=0) depth--;
1215      } else if(sscanf(env->in_string, semicform, rest) > 0) {
1216        push_sym(env, ";");
1217      } else if(sscanf(env->in_string, bbrackform, rest) > 0) {
1218        push_sym(env, "[");
1219        depth++;
1220      } else {
1221        free(rest);
1222        rest= NULL;
1223      }
1224          
1225      free(env->in_string);
1226      free(match);
1227    
1228      env->in_string= rest;
1229    
1230      if(depth)
1231        return read(env);
1232    }

Legend:
Removed from v.1.22  
changed lines
  Added in v.1.75

root@recompile.se
ViewVC Help
Powered by ViewVC 1.1.26