Advertisement
Guest User

scheme parser

a guest
Mar 3rd, 2015
207
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.44 KB | None | 0 0
  1. /* Convert the list of tokens to a cons cell */
  2. /* tokens have a "type" (one of NUMBER, NUMBER_FLT, STRING, SYMBOL, LPAREN, RPAREN) */
  3. struct cons *tok_to_cons(struct tokens *tok)
  4. {
  5.   struct tokens *node = tok;
  6.   struct cons *cell = malloc(sizeof(struct cons *));
  7.   struct cons *head = cell;
  8.   node = node->next;
  9.   int *integer = NULL;
  10.   float *fl = NULL;
  11.  
  12.   while (node != NULL) {
  13.     object_t *obj = (node->type != RPAREN) ? malloc(sizeof(object_t *)) : NULL;
  14.     /* Similarly, objects also have a type, except they cannot be (L|R)PAREN */
  15.     switch(node->type) {
  16.       case NUMBER:
  17.         integer = malloc(sizeof(int *));
  18.         *integer = atoi(node->str);
  19.         obj->val = (void *)integer;
  20.         break;
  21.       case NUMBER_FLT:
  22.         fl = malloc(sizeof(float *));
  23.         *fl = atof(node->str);
  24.         obj->val = (void *)fl;
  25.         break;
  26.       case SYMBOL:
  27.         obj->val = (char *)strdup(node->str);
  28.         break;
  29.       case LPAREN:
  30.         /* Entering a nested cell */
  31.         /* For reference, (a . (b . ((c . (d . nil)) . nil))) = (a b (c d)) */
  32.         obj->val = tok_to_cons(node);
  33.         break;
  34.       case RPAREN:
  35.         /* Reached end of cons cell */
  36.         head->cdr = NULL;
  37.         return cell;
  38.       case STRING:
  39.         obj->val = strdup(node->str);
  40.         break;
  41.     }
  42.     obj->type = node->type;
  43.     head->car = obj;
  44.     head->cdr = malloc(sizeof(struct cons *));
  45.     node = node->next;
  46.   }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement