Function Type

As we’ve added a new possible lval type with the enumeration LVAL_FUN. We should update all our relevant functions that work on lvals to deal correctly with this update. In most cases this just means inserting new cases into switch statements.

We can start by making a new constructor function for this type.

  1. lval* lval_fun(lbuiltin func) {
  2. lval* v = malloc(sizeof(lval));
  3. v->type = LVAL_FUN;
  4. v->fun = func;
  5. return v;
  6. }

On deletion we don’t need to do anything special for function pointers.

  1. case LVAL_FUN: break;

On printing we can just print out a nominal string.

  1. case LVAL_FUN: printf("<function>"); break;

We’re also going to add a new function for copying an lval. This is going to come in useful when we put things into, and take things out of, the environment. For numbers and functions we can just copy the relevant fields directly. For strings we need to copy using malloc and strcpy. To copy lists we need to allocate the correct amount of space and then copy each element individually.

  1. lval* lval_copy(lval* v) {
  2. lval* x = malloc(sizeof(lval));
  3. x->type = v->type;
  4. switch (v->type) {
  5. /* Copy Functions and Numbers Directly */
  6. case LVAL_FUN: x->fun = v->fun; break;
  7. case LVAL_NUM: x->num = v->num; break;
  8. /* Copy Strings using malloc and strcpy */
  9. case LVAL_ERR:
  10. x->err = malloc(strlen(v->err) + 1);
  11. strcpy(x->err, v->err); break;
  12. case LVAL_SYM:
  13. x->sym = malloc(strlen(v->sym) + 1);
  14. strcpy(x->sym, v->sym); break;
  15. /* Copy Lists by copying each sub-expression */
  16. case LVAL_SEXPR:
  17. case LVAL_QEXPR:
  18. x->count = v->count;
  19. x->cell = malloc(sizeof(lval*) * x->count);
  20. for (int i = 0; i < x->count; i++) {
  21. x->cell[i] = lval_copy(v->cell[i]);
  22. }
  23. break;
  24. }
  25. return x;
  26. }