Comments


While we’re building in new syntax to the language we may as well look at comments.

Just like in C, we can use comments in inform other people (or ourselves) about what the code is meant to do or why it has been written. In C comments go between /* and */. Lisp comments, on the other hand, start with ; and run to the end of the line.

I attempted to research why Lisps use ; for comments, but it appears that the origins of this have been lost in the mists of time. I imagine it as a small rebellion against the imperative languages such as C and Java which use semicolons so shamelessly and frequently to separate/terminate statements. Compared to Lisp all these languages are just comments.

So in lisp a comment is defined by a semicolon ; followed by any number of characters that are not newline characters represented by either \r or \n. We can use another regex to define it.

  1. comment : /;[^\\r\\n]*/ ;

As with strings we need to create a new parser and use this to update our language in mpca_lang. We also need to remember to add the parser to mpc_cleanup, and update the first integer argument to reflect the new number of parsers passed in.

Our final grammar now looks like this.

  1. mpca_lang(MPCA_LANG_DEFAULT,
  2. " \
  3. number : /-?[0-9]+/ ; \
  4. symbol : /[a-zA-Z0-9_+\\-*\\/\\\\=<>!&]+/ ; \
  5. string : /\"(\\\\.|[^\"])*\"/ ; \
  6. comment : /;[^\\r\\n]*/ ; \
  7. sexpr : '(' <expr>* ')' ; \
  8. qexpr : '{' <expr>* '}' ; \
  9. expr : <number> | <symbol> | <string> \
  10. | <comment> | <sexpr> | <qexpr>; \
  11. lispy : /^/ <expr>* /$/ ; \
  12. ",
  13. Number, Symbol, String, Comment, Sexpr, Qexpr, Expr, Lispy);

And the cleanup function looks like this.

  1. mpc_cleanup(8,
  2. Number, Symbol, String, Comment,
  3. Sexpr, Qexpr, Expr, Lispy);

Because comments are only for programmers reading the code, our internal function for reading them in just consists of ignoring them. We can add a clause to deal with them in a similar way to brackets and parenthesis in lval_read.

  1. if (strstr(t->children[i]->tag, "comment")) { continue; }

Comments won’t be of much use on the interactive prompt, but they will be very helpful for adding into files of code to annotate them.