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

Diff of /stack/stack.c

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

revision 1.19 by masse, Sat Feb 2 14:50:44 2002 UTC revision 1.132 by masse, Fri Aug 8 14:20:49 2003 UTC
# Line 1  Line 1 
1  /* printf */  /* -*- coding: utf-8; -*- */
2  #include <stdio.h>  /*
3  /* EXIT_SUCCESS */      stack - an interactive interpreter for a stack-based language
4  #include <stdlib.h>      Copyright (C) 2002  Mats Alritzson and Teddy Hogeborn
 /* NULL */  
 #include <stddef.h>  
 /* dlopen, dlsym, dlerror */  
 #include <dlfcn.h>  
 /* assert */  
 #include <assert.h>  
   
 #define HASHTBLSIZE 65536  
   
 typedef struct stack_item  
 {  
   enum {  
     value,                      /* Integer */  
     string,  
     ref,                        /* Reference (to an element in the  
                                    hash table) */  
     func,                       /* Function pointer */  
     symbol,  
     list  
   } type;                       /* Type of stack element */  
   
   union {  
     void* ptr;                  /* Pointer to the content */  
     int val;                    /* ...or an integer */  
   } content;                    /* Stores a pointer or an integer */  
   
   char* id;                     /* Symbol name */  
   struct stack_item* next;      /* Next element */  
 } stackitem;  
   
   
 typedef stackitem* hashtbl[HASHTBLSIZE]; /* Hash table declaration */  
 typedef void (*funcp)(stackitem**); /* funcp is a pointer to a  
                                        void function (stackitem **) */  
5    
6  /* Initialize a newly created hash table. */      This program is free software; you can redistribute it and/or modify
7  void init_hashtbl(hashtbl out_hash)      it under the terms of the GNU General Public License as published by
8        the Free Software Foundation; either version 2 of the License, or
9        (at your option) any later version.
10    
11        This program is distributed in the hope that it will be useful,
12        but WITHOUT ANY WARRANTY; without even the implied warranty of
13        MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14        GNU General Public License for more details.
15    
16        You should have received a copy of the GNU General Public License
17        along with this program; if not, write to the Free Software
18        Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19    
20        Authors: Mats Alritzson <masse@fukt.bth.se>
21                 Teddy Hogeborn <teddy@fukt.bth.se>
22    */
23    
24    #include "stack.h"
25    
26    const char* start_message= "Stack version $Revision$\n\
27    Copyright (C) 2002  Mats Alritzson and Teddy Hogeborn\n\
28    Stack comes with ABSOLUTELY NO WARRANTY; for details type 'warranty;'.\n\
29    This is free software, and you are welcome to redistribute it\n\
30    under certain conditions; type 'copying;' for details.\n";
31    
32    
33    /* Initialize a newly created environment */
34    void init_env(environment *env)
35  {  {
36    long i;    int i;
37    
38      env->gc_limit= 400000;
39      env->gc_count= 0;
40      env->gc_ref= NULL;
41    
42      env->head= new_val(env);
43    for(i= 0; i<HASHTBLSIZE; i++)    for(i= 0; i<HASHTBLSIZE; i++)
44      out_hash[i]= NULL;      env->symbols[i]= NULL;
45      env->err= 0;
46      env->in_string= NULL;
47      env->free_string= NULL;
48      env->inputstream= stdin;
49      env->interactive= 1;
50  }  }
51    
52  /* Returns a pointer to an element in the hash table. */  
53  stackitem** hash(hashtbl in_hashtbl, const char* in_string)  void printerr(const char* in_string)
54  {  {
55    long i= 0;    fprintf(stderr, "Err: %s\n", in_string);
56    unsigned long out_hash= 0;  }
57    
58    
59    /* Returns a pointer to a pointer to an element in the hash table. */
60    symbol **hash(hashtbl in_hashtbl, const char *in_string)
61    {
62      int i= 0;
63      unsigned int out_hash= 0;
64    char key= '\0';    char key= '\0';
65    stackitem** position;    symbol **position;
66        
67    while(1){                     /* Hash in_string */    while(1){                     /* Hash in_string */
68      key= in_string[i++];      key= in_string[i++];
# Line 64  stackitem** hash(hashtbl in_hashtbl, con Line 74  stackitem** hash(hashtbl in_hashtbl, con
74    out_hash= out_hash%HASHTBLSIZE;    out_hash= out_hash%HASHTBLSIZE;
75    position= &(in_hashtbl[out_hash]);    position= &(in_hashtbl[out_hash]);
76    
77    while(position != NULL){    while(1){
78      if(*position==NULL)         /* If empty */      if(*position==NULL)         /* If empty */
79        return position;        return position;
80            
# Line 73  stackitem** hash(hashtbl in_hashtbl, con Line 83  stackitem** hash(hashtbl in_hashtbl, con
83    
84      position= &((*position)->next); /* Try next */      position= &((*position)->next); /* Try next */
85    }    }
   return NULL;                  /* end of list reached without finding  
                                    an empty position */  
86  }  }
87    
 /* Generic push function. */  
 int push(stackitem** stack_head, stackitem* in_item)  
 {  
   in_item->next= *stack_head;  
   *stack_head= in_item;  
   return 1;  
 }  
88    
89  /* Push a value on the stack. */  /* Create new value */
90  int push_val(stackitem** stack_head, int in_val)  value* new_val(environment *env)
91  {  {
92    stackitem* new_item= malloc(sizeof(stackitem));    value *nval= malloc(sizeof(value));
93    assert(new_item != NULL);    stackitem *nitem= malloc(sizeof(stackitem));
   new_item->content.val= in_val;  
   new_item->type= value;  
94    
95    push(stack_head, new_item);    assert(nval != NULL);
96    return 1;    assert(nitem != NULL);
 }  
97    
98  /* Copy a string onto the stack. */    nval->content.ptr= NULL;
99  int push_cstring(stackitem** stack_head, const char* in_string)    nval->type= empty;
 {  
   stackitem* new_item= malloc(sizeof(stackitem));  
   new_item->content.ptr= malloc(strlen(in_string)+1);  
   strcpy(new_item->content.ptr, in_string);  
   new_item->type= string;  
100    
101    push(stack_head, new_item);    nitem->item= nval;
102    return 1;    nitem->next= env->gc_ref;
 }  
103    
104  /* Create a new hash entry. */    env->gc_ref= nitem;
 int mk_hashentry(hashtbl in_hashtbl, stackitem* in_item, const char* id)  
 {  
   in_item->id= malloc(strlen(id)+1);  
105    
106    strcpy(in_item->id, id);    env->gc_count += sizeof(value);
107    push(hash(in_hashtbl, id), in_item);    nval->gc.flag.mark= 0;
108      nval->gc.flag.protect= 0;
109    
110    return 1;    return nval;
111  }  }
112    
113  /* Define a new function in the hash table. */  
114  void def_func(hashtbl in_hashtbl, funcp in_func, const char* id)  /* Mark values recursively.
115       Marked values are not collected by the GC. */
116    inline void gc_mark(value *val)
117  {  {
118    stackitem* temp= malloc(sizeof(stackitem));    if(val==NULL || val->gc.flag.mark)
119        return;
120    
121    temp->type= func;    val->gc.flag.mark= 1;
   temp->content.ptr= in_func;  
122    
123    mk_hashentry(in_hashtbl, temp, id);    if(val->type==tcons) {
124        gc_mark(CAR(val));
125        gc_mark(CDR(val));
126      }
127  }  }
128    
 /* Define a new symbol in the hash table. */  
 void def_sym(hashtbl in_hashtbl, const char* id)  
 {  
   stackitem* temp= malloc(sizeof(stackitem));  
     
   temp->type= symbol;  
   mk_hashentry(in_hashtbl, temp, id);  
 }  
129    
130  /* Push a reference to an entry in the hash table onto the stack. */  /* Start GC */
131  int push_ref(stackitem** stack_head, hashtbl in_hash, const char* in_string)  extern void gc_init(environment *env)
132  {  {
133    static void* handle= NULL;    stackitem *new_head= NULL, *titem;
134    void* symbol;    symbol *tsymb;
135      int i;
136    
137    stackitem* new_item= malloc(sizeof(stackitem));    if(env->interactive)
138    new_item->content.ptr= *hash(in_hash, in_string);      printf("Garbage collecting.");
   new_item->type= ref;  
139    
140    if(new_item->content.ptr==NULL) { /* If hash entry empty */    /* Mark values on stack */
141      if(handle==NULL)            /* If no handle */    gc_mark(env->head);
       handle= dlopen(NULL, RTLD_LAZY);      
142    
143      symbol= dlsym(handle, in_string); /* Get function pointer */    if(env->interactive)
144      if(dlerror()==NULL)         /* If existing function pointer */      printf(".");
       def_func(in_hash, symbol, in_string); /* Store function pointer */  
     else  
       def_sym(in_hash, in_string); /* Make symbol */  
         
     new_item->content.ptr= *hash(in_hash, in_string); /* XXX */  
     new_item->type= ref;  
   }  
145    
146    push(stack_head, new_item);    /* Mark values in hashtable */
147    return 1;    for(i= 0; i<HASHTBLSIZE; i++)
148  }      for(tsymb= env->symbols[i]; tsymb!=NULL; tsymb= tsymb->next)
149          if (tsymb->val != NULL)
150            gc_mark(tsymb->val);
151    
152      if(env->interactive)
153        printf(".");
154    
155      env->gc_count= 0;
156    
157      while(env->gc_ref!=NULL) {    /* Sweep unused values */
158        if(!(env->gc_ref->item->gc.no_gc)){ /* neither mark nor protect */
159    
160          /* Remove content */
161          switch(env->gc_ref->item->type){
162          case string:
163            free(env->gc_ref->item->content.string);
164            break;
165          case tcons:
166            free(env->gc_ref->item->content.c);
167            break;
168          case port:
169          case empty:
170          case integer:
171          case tfloat:
172          case func:
173          case symb:
174            /* Symbol strings are freed when walking the hash table */
175            break;
176          }
177    
178  void printerr(const char* in_string) {        free(env->gc_ref->item);  /* Remove from gc_ref */
179    fprintf(stderr, "Err: %s\n", in_string);        titem= env->gc_ref->next;
180  }        free(env->gc_ref);        /* Remove value */
181          env->gc_ref= titem;
182          continue;
183        }
184    
185  /* Discard the top element of the stack. */  #ifdef DEBUG
186  extern void toss(stackitem** stack_head)      printf("Kept value (%p)", env->gc_ref->item);
187  {      if(env->gc_ref->item->gc.flag.mark)
188    stackitem* temp= *stack_head;        printf(" (marked)");
189        if(env->gc_ref->item->gc.flag.protect)
190          printf(" (protected)");
191        switch(env->gc_ref->item->type){
192        case integer:
193          printf(" integer: %d", env->gc_ref->item->content.i);
194          break;
195        case func:
196          printf(" func: %p", env->gc_ref->item->content.func);
197          break;
198        case symb:
199          printf(" symb: %s", env->gc_ref->item->content.sym->id);
200          break;
201        case tcons:
202          printf(" tcons: %p\t%p", CAR(env->gc_ref->item),
203                 CDR(env->gc_ref->item));
204          break;
205        default:
206          printf(" <unknown %d>", (env->gc_ref->item->type));
207        }
208        printf("\n");
209    #endif /* DEBUG */
210    
211    if((*stack_head)==NULL) {      /* Keep values */    
212      printerr("Stack empty");      env->gc_count += sizeof(value);
213      return;      if(env->gc_ref->item->type==string)
214          env->gc_count += strlen(env->gc_ref->item->content.string)+1;
215        
216        titem= env->gc_ref->next;
217        env->gc_ref->next= new_head;
218        new_head= env->gc_ref;
219        new_head->item->gc.flag.mark= 0;
220        env->gc_ref= titem;
221    }    }
     
   if((*stack_head)->type==string)  
     free((*stack_head)->content.ptr);  
222    
223    *stack_head= (*stack_head)->next;    if (env->gc_limit < env->gc_count*2)
224    free(temp);      env->gc_limit= env->gc_count*2;
225    
226      env->gc_ref= new_head;
227    
228      if(env->interactive)
229        printf("done (%d bytes still allocated)\n", env->gc_count);
230    
231  }  }
232    
233  /* Print newline. */  
234  extern void nl()  inline void gc_maybe(environment *env)
235  {  {
236    printf("\n");    if(env->gc_count < env->gc_limit)
237        return;
238      else
239        return gc_init(env);
240  }  }
241    
242  /* Prints the top element of the stack. */  
243  void print_(stackitem** stack_head)  /* Protect values from GC */
244    void protect(value *val)
245  {  {
246    if((*stack_head)==NULL) {    if(val==NULL || val->gc.flag.protect)
     printerr("Stack empty");  
247      return;      return;
248    
249      val->gc.flag.protect= 1;
250    
251      if(val->type==tcons) {
252        protect(CAR(val));
253        protect(CDR(val));
254    }    }
255    }
256    
257    switch((*stack_head)->type) {  
258    case value:  /* Unprotect values from GC */
259      printf("%d", (*stack_head)->content.val);  void unprotect(value *val)
260      break;  {
261    case string:    if(val==NULL || !(val->gc.flag.protect))
262      printf("%s", (char*)(*stack_head)->content.ptr);      return;
263      break;  
264    case ref:    val->gc.flag.protect= 0;
265      printf("%s", ((stackitem*)(*stack_head)->content.ptr)->id);  
266      break;    if(val->type==tcons) {
267    case symbol:      unprotect(CAR(val));
268    default:      unprotect(CDR(val));
     printf("%p", (*stack_head)->content.ptr);  
     break;  
269    }    }
270  }  }
271    
272  /* Prints the top element of the stack and then discards it. */  
273  extern void print(stackitem** stack_head)  /* Push a value onto the stack */
274    void push_val(environment *env, value *val)
275  {  {
276    print_(stack_head);    value *new_value= new_val(env);
277    toss(stack_head);  
278      new_value->content.c= malloc(sizeof(pair));
279      assert(new_value->content.c!=NULL);
280      env->gc_count += sizeof(pair);
281      new_value->type= tcons;
282      CAR(new_value)= val;
283      CDR(new_value)= env->head;
284      env->head= new_value;
285  }  }
286    
 /* Only to be called by function printstack. */  
 void print_st(stackitem* stack_head, long counter)  
 {  
   if(stack_head->next != NULL)  
     print_st(stack_head->next, counter+1);  
287    
288    printf("%ld: ", counter);  /* Push an integer onto the stack */
289    print_(&stack_head);  void push_int(environment *env, int in_val)
290    nl();  {
291      value *new_value= new_val(env);
292      
293      new_value->content.i= in_val;
294      new_value->type= integer;
295    
296      push_val(env, new_value);
297  }  }
298    
299  /* Prints the stack. */  
300  extern void printstack(stackitem** stack_head)  /* Push a floating point number onto the stack */
301    void push_float(environment *env, float in_val)
302  {  {
303    if(*stack_head != NULL) {    value *new_value= new_val(env);
304      print_st(*stack_head, 1);  
305      printf("\n");    new_value->content.f= in_val;
306    } else {    new_value->type= tfloat;
307      printerr("Stack empty");  
308    }    push_val(env, new_value);
309  }  }
310    
311  /* If the top element is a reference, determine if it's a reference to a  
312     function, and if it is, toss the reference and execute the function. */  /* Copy a string onto the stack. */
313  extern void eval(stackitem** stack_head)  void push_cstring(environment *env, const char *in_string)
314  {  {
315    funcp in_func;    value *new_value= new_val(env);
316      int length= strlen(in_string)+1;
317    
318    if((*stack_head)==NULL || (*stack_head)->type!=ref) {    new_value->content.string= malloc(length);
319      printerr("Stack empty or not a reference");    assert(new_value != NULL);
320      return;    env->gc_count += length;
321    }    strcpy(new_value->content.string, in_string);
322      new_value->type= string;
323    
324    if(((stackitem*)(*stack_head)->content.ptr)->type==func) {    push_val(env, new_value);
     in_func= (funcp)((stackitem*)(*stack_head)->content.ptr)->content.ptr;  
     toss(stack_head);  
     (*in_func)(stack_head);  
     return;  
   } else  
     printerr("Not a function");  
325  }  }
326    
327  /* Make a list. */  
328  extern void pack(stackitem** stack_head)  /* Mangle a symbol name to a valid C identifier name */
329    char *mangle_str(const char *old_string)
330  {  {
331    void* delimiter;    char validchars[]= "0123456789abcdef";
332    stackitem *iterator, *temp, *pack;    char *new_string, *current;
333    
334    if((*stack_head)==NULL) {    new_string= malloc((strlen(old_string)*2)+4);
335      printerr("Stack empty");    assert(new_string != NULL);
336      return;    strcpy(new_string, "sx_");    /* Stack eXternal */
337      current= new_string+3;
338    
339      while(old_string[0] != '\0'){
340        current[0]= validchars[(unsigned char)(old_string[0])/16];
341        current[1]= validchars[(unsigned char)(old_string[0])%16];
342        current+= 2;
343        old_string++;
344    }    }
345      current[0]= '\0';
346    
347    delimiter= (*stack_head)->content.ptr; /* Get delimiter */    return new_string;            /* The caller must free() it */
348    toss(stack_head);  }
349    
   iterator= *stack_head;  
350    
351    /* Search for first delimiter */  /* Push a symbol onto the stack. */
352    while(iterator->next!=NULL && iterator->next->content.ptr!=delimiter)  void push_sym(environment *env, const char *in_string)
353      iterator= iterator->next;  {
354      value *new_value;             /* A new symbol value */
355      /* ...which might point to... */
356      symbol **new_symbol;          /* (if needed) A new actual symbol */
357      /* ...which, if possible, will be bound to... */
358      value *new_fvalue;            /* (if needed) A new function value */
359      /* ...which will point to... */
360      void *funcptr;                /* A function pointer */
361    
362    /* Extract list */    static void *handle= NULL;    /* Dynamic linker handle */
363    temp= *stack_head;    const char *dlerr;            /* Dynamic linker error */
364    *stack_head= iterator->next;    char *mangled;                /* Mangled function name */
   iterator->next= NULL;  
     
   if(*stack_head!=NULL && (*stack_head)->content.ptr==delimiter)  
     toss(stack_head);  
365    
366    /* Push list */    new_value= new_val(env);
367    pack= malloc(sizeof(stackitem));    protect(new_value);
368    pack->type= list;    new_fvalue= new_val(env);
369    pack->content.ptr= temp;    protect(new_fvalue);
370    
371      /* The new value is a symbol */
372      new_value->type= symb;
373    
374      /* Look up the symbol name in the hash table */
375      new_symbol= hash(env->symbols, in_string);
376      new_value->content.sym= *new_symbol;
377    
378      if(*new_symbol==NULL) { /* If symbol was undefined */
379    
380        /* Create a new symbol */
381        (*new_symbol)= malloc(sizeof(symbol));
382        assert((*new_symbol) != NULL);
383        (*new_symbol)->val= NULL;   /* undefined value */
384        (*new_symbol)->next= NULL;
385        (*new_symbol)->id= malloc(strlen(in_string)+1);
386        assert((*new_symbol)->id != NULL);
387        strcpy((*new_symbol)->id, in_string);
388    
389        /* Intern the new symbol in the hash table */
390        new_value->content.sym= *new_symbol;
391    
392        /* Try to load the symbol name as an external function, to see if
393           we should bind the symbol to a new function pointer value */
394        if(handle==NULL)            /* If no handle */
395          handle= dlopen(NULL, RTLD_LAZY);
396    
397        mangled= mangle_str(in_string); /* mangle the name */
398        funcptr= dlsym(handle, mangled); /* and try to find it */
399    
400        dlerr= dlerror();
401        if(dlerr != NULL) {         /* If no function was found */
402          funcptr= dlsym(handle, in_string); /* Get function pointer */
403          dlerr= dlerror();
404        }
405    
406        if(dlerr==NULL) {           /* If a function was found */
407          new_fvalue->type= func;   /* The new value is a function pointer */
408          new_fvalue->content.func= funcptr; /* Store function pointer */
409          (*new_symbol)->val= new_fvalue; /* Bind the symbol to the new
410                                             function value */
411        }
412    
413        free(mangled);
414      }
415    
416    push(stack_head, pack);    push_val(env, new_value);
417      unprotect(new_value); unprotect(new_fvalue);
418  }  }
419    
 /* Parse input. */  
 int stack_read(stackitem** stack_head, hashtbl in_hash, char* in_line)  
 {  
   char *temp, *rest;  
   int itemp;  
   size_t inlength= strlen(in_line)+1;  
   int convert= 0;  
420    
421    temp= malloc(inlength);  /* Print a value */
422    rest= malloc(inlength);  void print_val(environment *env, value *val, int noquote, stackitem *stack,
423                   FILE *stream)
424    {
425      stackitem *titem, *tstack;
426      int depth;
427    
428    do {    switch(val->type) {
429      /* If string */    case empty:
430      if((convert= sscanf(in_line, "\"%[^\"\n\r]\" %[^\n\r]", temp, rest))) {      if(fprintf(stream, "[]") < 0){
431        push_cstring(stack_head, temp);        perror("print_val");
432        break;        env->err= 5;
433          return;
434      }      }
435      /* If value */      break;
436      if((convert= sscanf(in_line, "%d %[^\n\r]", &itemp, rest))) {    case integer:
437        push_val(stack_head, itemp);      if(fprintf(stream, "%d", val->content.i) < 0){
438        break;        perror("print_val");
439          env->err= 5;
440          return;
441      }      }
442      /* Escape ';' with '\' */      break;
443      if((convert= sscanf(in_line, "\\%c%[^\n\r]", temp, rest))) {    case tfloat:
444        temp[1]= '\0';      if(fprintf(stream, "%f", val->content.f) < 0){
445        push_ref(stack_head, in_hash, temp);        perror("print_val");
446        break;        env->err= 5;
447      }        return;
     /* If symbol */  
     if((convert= sscanf(in_line, "%[^] ;\n\r]%[^\n\r]", temp, rest))) {  
         push_ref(stack_head, in_hash, temp);  
         break;  
448      }      }
449      /* If single char */      break;
450      if((convert= sscanf(in_line, "%c%[^\n\r]", temp, rest))) {    case string:
451        if(*temp==';') {      if(noquote){
452          eval(stack_head);               /* Evaluate top element */        if(fprintf(stream, "%s", val->content.string) < 0){
453          break;          perror("print_val");
454            env->err= 5;
455            return;
456          }
457        } else {                    /* quote */
458          if(fprintf(stream, "\"%s\"", val->content.string) < 0){
459            perror("print_val");
460            env->err= 5;
461            return;
462          }
463        }
464        break;
465      case symb:
466        if(fprintf(stream, "%s", val->content.sym->id) < 0){
467          perror("print_val");
468          env->err= 5;
469          return;
470        }
471        break;
472      case func:
473        if(fprintf(stream, "#<function %p>", val->content.func) < 0){
474          perror("print_val");
475          env->err= 5;
476          return;
477        }
478        break;
479      case port:
480        if(fprintf(stream, "#<port %p>", val->content.p) < 0){
481          perror("print_val");
482          env->err= 5;
483          return;
484        }
485        break;
486      case tcons:
487        if(fprintf(stream, "[ ") < 0){
488          perror("print_val");
489          env->err= 5;
490          return;
491        }
492        tstack= stack;
493    
494        do {
495          titem=malloc(sizeof(stackitem));
496          assert(titem != NULL);
497          titem->item=val;
498          titem->next=tstack;
499          tstack=titem;             /* Put it on the stack */
500          /* Search a stack of values being printed to see if we are already
501             printing this value */
502          titem=tstack;
503          depth=0;
504    
505          while(titem != NULL && titem->item != CAR(val)){
506            titem=titem->next;
507            depth++;
508        }        }
509    
510        if(*temp==']') {        if(titem != NULL){        /* If we found it on the stack, */
511          push_ref(stack_head, in_hash, "[");          if(fprintf(stream, "#%d#", depth) < 0){ /* print a depth reference */
512          pack(stack_head);            perror("print_val");
513              env->err= 5;
514              free(titem);
515              return;
516            }
517          } else {
518            print_val(env, CAR(val), noquote, tstack, stream);
519          }
520    
521          val= CDR(val);
522          switch(val->type){
523          case empty:
524            break;
525          case tcons:
526            /* Search a stack of values being printed to see if we are already
527               printing this value */
528            titem=tstack;
529            depth=0;
530    
531            while(titem != NULL && titem->item != val){
532              titem=titem->next;
533              depth++;
534            }
535            if(titem != NULL){      /* If we found it on the stack, */
536              if(fprintf(stream, " . #%d#", depth) < 0){ /* print a depth reference */
537                perror("print_val");
538                env->err= 5;
539                goto printval_end;
540              }
541            } else {
542              if(fprintf(stream, " ") < 0){
543                perror("print_val");
544                env->err= 5;
545                goto printval_end;
546              }
547            }
548          break;          break;
549          default:
550            if(fprintf(stream, " . ") < 0){ /* Improper list */
551              perror("print_val");
552              env->err= 5;
553              goto printval_end;
554            }
555            print_val(env, val, noquote, tstack, stream);
556        }        }
557      }      } while(val->type == tcons && titem == NULL);
   } while(0);  
558    
559      printval_end:
560    
561    free(temp);      titem=tstack;
562        while(titem != stack){
563          tstack=titem->next;
564          free(titem);
565          titem=tstack;
566        }
567    
568    if(convert<2) {      if(! (env->err)){
569      free(rest);        if(fprintf(stream, " ]") < 0){
570      return 0;          perror("print_val");
571            env->err= 5;
572          }
573        }
574        break;
575    }    }
     
   stack_read(stack_head, in_hash, rest);  
     
   free(rest);  
   return 1;  
576  }  }
577    
 /* Relocate elements of the list on the stack. */  
 extern void expand(stackitem** stack_head)  
 {  
   stackitem *temp, *new_head;  
578    
579    /* Is top element a list? */  /* Swap the two top elements on the stack. */
580    if((*stack_head)==NULL || (*stack_head)->type!=list) {  extern void swap(environment *env)
581      printerr("Stack empty or not a list");  {
582      value *temp= env->head;
583      
584      if(env->head->type == empty || CDR(env->head)->type == empty) {
585        printerr("Too Few Arguments");
586        env->err=1;
587      return;      return;
588    }    }
589    
590    /* The first list element is the new stack head */    env->head= CDR(env->head);
591    new_head= temp= (*stack_head)->content.ptr;    CDR(temp)= CDR(env->head);
592    toss(stack_head);    CDR(env->head)= temp;
593    }
594    
595    
596    /* Recall a value from a symbol, if bound */
597    extern void rcl(environment *env)
598    {
599      value *val;
600    
601      if(env->head->type==empty) {
602        printerr("Too Few Arguments");
603        env->err= 1;
604        return;
605      }
606    
607    /* Search the end of the list */    if(CAR(env->head)->type!=symb) {
608    while(temp->next!=NULL)      printerr("Bad Argument Type");
609      temp= temp->next;      env->err= 2;
610        return;
611      }
612    
613    /* Connect the the tail of the list with the old stack head */    val= CAR(env->head)->content.sym->val;
614    temp->next= *stack_head;    if(val == NULL){
615    *stack_head= new_head;        /* ...and voila! */      printerr("Unbound Variable");
616        env->err= 3;
617        return;
618      }
619      push_val(env, val);           /* Return the symbol's bound value */
620      swap(env);
621      if(env->err) return;
622      env->head= CDR(env->head);
623  }  }
624    
625  /* Swap the two top elements on the stack. */  
626  extern void swap(stackitem** stack_head)  /* If the top element is a symbol, determine if it's bound to a
627       function value, and if it is, toss the symbol and execute the
628       function. */
629    extern void eval(environment *env)
630  {  {
631    stackitem* temp= (*stack_head);    funcp in_func;
632        value* temp_val;
633    if((*stack_head)==NULL) {    value* iterator;
634      printerr("Stack empty");  
635     eval_start:
636    
637      gc_maybe(env);
638    
639      if(env->head->type==empty) {
640        printerr("Too Few Arguments");
641        env->err= 1;
642      return;      return;
643    }    }
644    
645    if((*stack_head)->next==NULL)    switch(CAR(env->head)->type) {
646        /* if it's a symbol */
647      case symb:
648        rcl(env);                   /* get its contents */
649        if(env->err) return;
650        if(CAR(env->head)->type!=symb){ /* don't recurse symbols */
651          goto eval_start;
652        }
653      return;      return;
654    
655    *stack_head= (*stack_head)->next;      /* If it's a lone function value, run it */
656    temp->next= (*stack_head)->next;    case func:
657    (*stack_head)->next= temp;      in_func= CAR(env->head)->content.func;
658  }      env->head= CDR(env->head);
659        return in_func(env);
660    
661        /* If it's a list */
662      case tcons:
663        temp_val= CAR(env->head);
664        protect(temp_val);
665    
666  /* Compares two elements by reference. */      env->head= CDR(env->head);
667  extern void eq(stackitem** stack_head)      iterator= temp_val;
668  {      
669    void *left, *right;      while(iterator->type != empty) {
670    int result;        push_val(env, CAR(iterator));
671          
672         if(CAR(env->head)->type==symb
673             && CAR(env->head)->content.sym->id[0]==';') {
674            env->head= CDR(env->head);
675            
676            if(CDR(iterator)->type == empty){
677              goto eval_start;
678            }
679            eval(env);
680            if(env->err) return;
681          }
682          if (CDR(iterator)->type == empty || CDR(iterator)->type == tcons)
683            iterator= CDR(iterator);
684          else {
685            printerr("Bad Argument Type"); /* Improper list */
686            env->err= 2;
687            return;
688          }
689        }
690        unprotect(temp_val);
691        return;
692    
693    if((*stack_head)==NULL || (*stack_head)->next==NULL) {    case empty:
694      printerr("Not enough elements to compare");      env->head= CDR(env->head);
695      case integer:
696      case tfloat:
697      case string:
698      case port:
699      return;      return;
700    }    }
701    }
702    
703    
704    /* Internal forget function */
705    void forget_sym(symbol **hash_entry)
706    {
707      symbol *temp;
708    
709    left= (*stack_head)->content.ptr;    temp= *hash_entry;
710    swap(stack_head);    *hash_entry= (*hash_entry)->next;
   right= (*stack_head)->content.ptr;  
   result= (left==right);  
711        
712    toss(stack_head); toss(stack_head);    free(temp->id);
713    push_val(stack_head, (left==right));    free(temp);
714  }  }
715    
716  /* Negates the top element on the stack. */  
717  extern void not(stackitem** stack_head)  int main(int argc, char **argv)
718  {  {
719    int value;    environment myenv;
720      int c;                        /* getopt option character */
721    
722    if((*stack_head)==NULL || (*stack_head)->type!=value) {  #ifdef __linux__
723      printerr("Stack empty or element is not a value");    mtrace();
724      return;  #endif
725    
726      init_env(&myenv);
727    
728      myenv.interactive = isatty(STDIN_FILENO) && isatty(STDOUT_FILENO);
729    
730      while ((c = getopt (argc, argv, "i")) != -1)
731        switch (c)
732          {
733          case 'i':
734            myenv.interactive = 1;
735            break;
736          case '?':
737            fprintf (stderr,
738                     "Unknown option character '\\x%x'.\n",
739                     optopt);
740            return EX_USAGE;
741          default:
742            abort ();
743          }
744      
745      if (optind < argc) {
746        myenv.interactive = 0;
747        myenv.inputstream= fopen(argv[optind], "r");
748        if(myenv.inputstream== NULL) {
749          perror(argv[0]);
750          exit (EX_NOINPUT);
751        }
752    }    }
753    
754    value= (*stack_head)->content.val;    if(myenv.interactive)
755    toss(stack_head);      printf(start_message);
756    push_val(stack_head, !value);  
757      while(1) {
758        if(myenv.in_string==NULL) {
759          if (myenv.interactive) {
760            if(myenv.err) {
761              printf("(error %d)\n", myenv.err);
762              myenv.err= 0;
763            }
764            printf("\n");
765            printstack(&myenv);
766            printf("> ");
767          }
768          myenv.err=0;
769        }
770        readstream(&myenv, myenv.inputstream);
771        if (myenv.err) {            /* EOF or other error */
772          myenv.err=0;
773          quit(&myenv);
774        } else if(myenv.head->type!=empty
775                  && CAR(myenv.head)->type==symb
776                  && CAR(myenv.head)->content.sym->id[0] == ';') {
777          if(myenv.head->type != empty)
778            myenv.head= CDR(myenv.head);
779          eval(&myenv);
780        } else {
781          gc_maybe(&myenv);
782        }
783      }
784      quit(&myenv);
785      return EXIT_FAILURE;
786  }  }
787    
788  /* Compares the two top elements on the stack and return 0 if they're the  
789     same. */  /* Return copy of a value */
790  extern void neq(stackitem** stack_head)  value *copy_val(environment *env, value *old_value)
791  {  {
792    eq(stack_head);    value *new_value;
793    not(stack_head);  
794      if(old_value==NULL)
795        return NULL;
796    
797      new_value= new_val(env);
798      new_value->type= old_value->type;
799    
800      switch(old_value->type){
801      case tfloat:
802      case integer:
803      case func:
804      case symb:
805      case empty:
806      case port:
807        new_value->content= old_value->content;
808        break;
809      case string:
810        new_value->content.string= strdup(old_value->content.string);
811        break;
812      case tcons:
813    
814        new_value->content.c= malloc(sizeof(pair));
815        assert(new_value->content.c!=NULL);
816        env->gc_count += sizeof(pair);
817    
818        CAR(new_value)= copy_val(env, CAR(old_value)); /* recurse */
819        CDR(new_value)= copy_val(env, CDR(old_value)); /* recurse */
820        break;
821      }
822    
823      return new_value;
824  }  }
825    
826  /* Give a symbol some content. */  
827  extern void def(stackitem** stack_head)  /* read a line from a stream; used by readline */
828    void readlinestream(environment *env, FILE *stream)
829  {  {
830    stackitem *temp, *value;    char in_string[101];
831    
832      if(fgets(in_string, 100, stream)==NULL) {
833        push_cstring(env, "");
834        if (! feof(stream)){
835          perror("readline");
836          env->err= 5;
837        }
838      } else {
839        push_cstring(env, in_string);
840      }
841    }
842    
843    if(*stack_head==NULL || (*stack_head)->next==NULL  
844       || (*stack_head)->type!=ref) {  /* Reverse (flip) a list */
845      printerr("Define what?");  extern void rev(environment *env)
846    {
847      value *old_head, *new_head, *item;
848    
849      if(env->head->type==empty) {
850        printerr("Too Few Arguments");
851        env->err= 1;
852      return;      return;
853    }    }
854    
855    temp= (*stack_head)->content.ptr;    if(CAR(env->head)->type==empty)
856    value= (*stack_head)->next;      return;                     /* Don't reverse an empty list */
   temp->content= value->content;  
   value->content.ptr=NULL;  
   temp->type= value->type;  
857    
858    toss(stack_head); toss(stack_head);    if(CAR(env->head)->type!=tcons) {
859  }      printerr("Bad Argument Type");
860        env->err= 2;
861        return;
862      }
863    
864  /* Quit stack. */    old_head= CAR(env->head);
865  extern void quit()    new_head= new_val(env);
866  {    while(old_head->type != empty) {
867    exit(EXIT_SUCCESS);      item= old_head;
868        old_head= CDR(old_head);
869        CDR(item)= new_head;
870        new_head= item;
871      }
872      CAR(env->head)= new_head;
873  }  }
874    
875  int main()  
876    /* Make a list. */
877    extern void pack(environment *env)
878  {  {
879    stackitem* s= NULL;    value *iterator, *temp, *ending;
   hashtbl myhash;  
   char in_string[100];  
880    
881    init_hashtbl(myhash);    ending=new_val(env);
882    
883    printf("okidok\n ");    iterator= env->head;
884      if(iterator->type == empty
885         || (CAR(iterator)->type==symb
886         && CAR(iterator)->content.sym->id[0]=='[')) {
887        temp= ending;
888        if(env->head->type != empty)
889          env->head= CDR(env->head);
890      } else {
891        /* Search for first delimiter */
892        while(CDR(iterator)->type != empty
893              && (CAR(CDR(iterator))->type!=symb
894               || CAR(CDR(iterator))->content.sym->id[0]!='['))
895          iterator= CDR(iterator);
896        
897        /* Extract list */
898        temp= env->head;
899        env->head= CDR(iterator);
900        CDR(iterator)= ending;
901    
902    while(fgets(in_string, 100, stdin) != NULL) {      if(env->head->type != empty)
903      stack_read(&s, myhash, in_string);        env->head= CDR(env->head);
     printf("okidok\n ");  
904    }    }
905    
906    exit(EXIT_SUCCESS);    /* Push list */
907    
908      push_val(env, temp);
909      rev(env);
910  }  }
911    
912  /* Local Variables: */  
913  /* compile-command:"make CFLAGS=\"-Wall -g -rdynamic -ldl\" stack" */  /* read from a stream; used by "read" and "readport" */
914  /* End: */  void readstream(environment *env, FILE *stream)
915    {
916      const char symbform[]= "%[a-zA-Z0-9!$%*+./:<=>?@^_~-]%n";
917      const char strform[]= "\"%[^\"]\"%n";
918      const char intform[]= "%i%n";
919      const char fltform[]= "%f%n";
920      const char blankform[]= "%*[ \t]%n";
921      const char ebrackform[]= "]%n";
922      const char semicform[]= ";%n";
923      const char bbrackform[]= "[%n";
924    
925      int itemp, readlength= -1;
926      int count= -1;
927      float ftemp;
928      static int depth= 0;
929      char *match;
930      size_t inlength;
931    
932      if(env->in_string==NULL) {
933        if(depth > 0 && env->interactive) {
934          printf("]> ");
935        }
936        readlinestream(env, env->inputstream);
937        if(env->err) return;
938    
939        if((CAR(env->head)->content.string)[0]=='\0'){
940          env->err= 4;              /* "" means EOF */
941          return;
942        }
943        
944        env->in_string= malloc(strlen(CAR(env->head)->content.string)+1);
945        assert(env->in_string != NULL);
946        env->free_string= env->in_string; /* Save the original pointer */
947        strcpy(env->in_string, CAR(env->head)->content.string);
948        env->head= CDR(env->head);
949      }
950      
951      inlength= strlen(env->in_string)+1;
952      match= malloc(inlength);
953      assert(match != NULL);
954    
955      if(sscanf(env->in_string, blankform, &readlength) != EOF
956         && readlength != -1) {
957        ;
958      } else if(sscanf(env->in_string, fltform, &ftemp, &readlength) != EOF
959                && readlength != -1) {
960        if(sscanf(env->in_string, intform, &itemp, &count) != EOF
961           && count==readlength) {
962          push_int(env, itemp);
963        } else {
964          push_float(env, ftemp);
965        }
966      } else if(sscanf(env->in_string, "\"\"%n", &readlength) != EOF
967                && readlength != -1) {
968        push_cstring(env, "");
969      } else if(sscanf(env->in_string, strform, match, &readlength) != EOF
970                && readlength != -1) {
971        push_cstring(env, match);
972      } else if(sscanf(env->in_string, symbform, match, &readlength) != EOF
973                && readlength != -1) {
974        push_sym(env, match);
975      } else if(sscanf(env->in_string, ebrackform, &readlength) != EOF
976                && readlength != -1) {
977        pack(env); if(env->err) return;
978        if(depth != 0) depth--;
979      } else if(sscanf(env->in_string, semicform, &readlength) != EOF
980                && readlength != -1) {
981        push_sym(env, ";");
982      } else if(sscanf(env->in_string, bbrackform, &readlength) != EOF
983                && readlength != -1) {
984        push_sym(env, "[");
985        depth++;
986      } else {
987        free(env->free_string);
988        env->in_string = env->free_string = NULL;
989      }
990      if (env->in_string != NULL) {
991        env->in_string += readlength;
992      }
993    
994      free(match);
995    
996      if(depth)
997        return readstream(env, env->inputstream);
998    }

Legend:
Removed from v.1.19  
changed lines
  Added in v.1.132

root@recompile.se
ViewVC Help
Powered by ViewVC 1.1.26