Reader Syntax
siiky
2022/03/15
2022/07/07
en
TIL a bit of reader syntax magic. With very few lines of code I was able to make available the #!sql reader syntax to let me read the contents of SQL files as a literal string (any file actually, but I was thinking of using it for SQL files only).
Here's the necessary code in its entirety:
There's one caveat with this approach, however: the reader syntax will be available to the whole program, not just the file or module that defined or imported it. This means that the identifiers must be unique, otherwise different definitions will collide with each other and the compiled program won't be what you expect. AND I think that it will be available not only at compile time, but at runtime as well -- very good to keep in mind!
Someone on IRC mentioned that it's possible to use -extend (-X) to make it available at compile time only. As an example, they said that compiling with -X srfi-19-literals would allow one to write #@1-1-22. Try this, after installing SRFI-19:
Relevant CHICKEN documentation for set-read-syntax! & friends:
https://wiki.call-cc.org/man/5/Module%20(chicken%20read-syntax)
https://api.call-cc.org/5/doc/chicken/read-syntax
And the relevant SRFI-19 literals documentation:
https://wiki.call-cc.org/eggref/5/srfi-19#date-literal-form
https://api.call-cc.org/5/doc/srfi-19/date-literal-form
-----
To make it more obvious why this is cool, here goes a slightly more realistic, though still simple, example.
Let's say we have these SQL files:
An example.scm:
And the set-read-syntax! call from before wrapped up in a module sql-reader-syntax. After compiling the module you can compile the example with csc -X sql-reader-syntax example.scm, and this is the result of running it:
The example.scm is basically transformed into this before being compiled:
And notice how schema, data, and select are constants (defined with define-constant, kinda similar to the static keyword in C).