Load Function

We want to built a function that can load and evaluate a file when passed a string of its name. To implement this function we’ll need to make use of our grammar as we’ll need it to to read in the file contents, parse, and evaluate them. Our load function is going to rely on our mpc_parser* called Lispy.

Therefore, just like with functions, we need to forward declare our parser pointers, and place them at the top of the file.

  1. mpc_parser_t* Number;
  2. mpc_parser_t* Symbol;
  3. mpc_parser_t* String;
  4. mpc_parser_t* Comment;
  5. mpc_parser_t* Sexpr;
  6. mpc_parser_t* Qexpr;
  7. mpc_parser_t* Expr;
  8. mpc_parser_t* Lispy;

Our load function will be just like any other builtin. We need to start by checking that the input argument is a single string. Then we can use the mpc_parse_contents function to read in the contents of a file using a grammar. Just like mpc_parse this parses the contents of a file into some mpc_result object, which is our case is an abstract syntax tree again or an error.

Slightly differently to our command prompt, on successfully parsing a file we shouldn’t treat it like one expression. When typing into a file we let users list multiple expressions and evaluate all of them individually. To achieve this behaviour we need to loop over each expression in the contents of the file and evaluate it one by one. If there are any errors we should print them and continue.

If there is a parse error we’re going to extract the message and put it into a error lval which we return. If there are no errors the return value for this builtin can just be the empty expression. The full code for this looks like this.

  1. lval* builtin_load(lenv* e, lval* a) {
  2. LASSERT_NUM("load", a, 1);
  3. LASSERT_TYPE("load", a, 0, LVAL_STR);
  4. /* Parse File given by string name */
  5. mpc_result_t r;
  6. if (mpc_parse_contents(a->cell[0]->str, Lispy, &r)) {
  7. /* Read contents */
  8. lval* expr = lval_read(r.output);
  9. mpc_ast_delete(r.output);
  10. /* Evaluate each Expression */
  11. while (expr->count) {
  12. lval* x = lval_eval(e, lval_pop(expr, 0));
  13. /* If Evaluation leads to error print it */
  14. if (x->type == LVAL_ERR) { lval_println(x); }
  15. lval_del(x);
  16. }
  17. /* Delete expressions and arguments */
  18. lval_del(expr);
  19. lval_del(a);
  20. /* Return empty list */
  21. return lval_sexpr();
  22. } else {
  23. /* Get Parse Error as String */
  24. char* err_msg = mpc_err_string(r.error);
  25. mpc_err_delete(r.error);
  26. /* Create new error message using it */
  27. lval* err = lval_err("Could not load Library %s", err_msg);
  28. free(err_msg);
  29. lval_del(a);
  30. /* Cleanup and return error */
  31. return err;
  32. }
  33. }