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.
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.
mpca_lang(MPCA_LANG_DEFAULT,
" \
number : /-?[0-9]+/ ; \
symbol : /[a-zA-Z0-9_+\\-*\\/\\\\=<>!&]+/ ; \
string : /\"(\\\\.|[^\"])*\"/ ; \
comment : /;[^\\r\\n]*/ ; \
sexpr : '(' <expr>* ')' ; \
qexpr : '{' <expr>* '}' ; \
expr : <number> | <symbol> | <string> \
| <comment> | <sexpr> | <qexpr>; \
lispy : /^/ <expr>* /$/ ; \
",
Number, Symbol, String, Comment, Sexpr, Qexpr, Expr, Lispy);
And the cleanup function looks like this.
mpc_cleanup(8,
Number, Symbol, String, Comment,
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
.
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.