> As @dsrw said, it's possible to write a sub-language in Nim, this is very 
> interesting.

You could have a macro that took a filename as a parameter, read the file, ran 
it through a parser of some sort, then used the parse tree to generate Nim code 
which would be compiled into your program. It would be a lot more work than 
just making a DSL with Nim syntax, but it's an option if you need it. As Araq 
says though, Nim syntax is really flexible. The Nim code you pass to a macro 
doesn't need to mean anything to the compiler, it just needs to be parsable. 
That means that it's still whitespace sensitive, blocks still have to start 
with `:`, your braces have to match up and things of that nature, but apart 
from the basic structural elements the code can be whatever you like.

Writing your DSL in Nim syntax and reading it with a macro has a lot of 
advantages. You don't have to write a parser. The elements of your parse tree 
all have line/file info associated with them, making it fairly easy to surface 
useful errors. You get lots of tools for easily transversing and searching your 
tree, and enforcing certain conditions about the code that's passed in. And you 
only have to fiddle with the bits that you actually care about. If you want to 
handle some constructs as normal Nim code you can just pass them along 
untouched, and the Nim compiler will do all the work.

Nim is definitely the closest thing to a universal language that I've found. 
There are things that it isn't particularly good at, but that's mostly due to a 
lack of libraries/ecosystem rather than a fundamental limitation of the 
language. One of my primary uses of Nim is as a super simple, logo inspired 
language to teach kids to code. The code doesn't look much like normal Nim. It 
has a completely different way to define functions, eschews immutability, puts 
lots of things into the global scope by default, and has custom syntax for 
drawing things and making simple behaviours. It runs in an interpreter (the 
NimVM, what Nim normally uses to evaluate macros and config files), makes 
everything reloadable on the fly, and doesn't even follow the normal Nim style 
conventions. It's probably the furthest thing from what Araq intended when he 
started writing Nim, but yet Nim is a great fit. I'm almost positive that I 
would have abandoned my project ages ago if I had started in any other language.

The Perl community has an adage along the lines of "easy things should be easy, 
and hard things should be possible". Nim does that really, really well.

Reply via email to