Hi all,
I'd like to be able to compile Nim (or generate from Nim) code in a specialised C-based DSL. For example I'd like to write something like this in Nim
func_declare test1(arg: DATA): DATA
func_create test2(arg: int): string = do_something(arg)
which would generate a file with
//DSL code
// function declaration for function 'test1' - DATA is a C typedef
DATA func_test1(DATA arg);
// implementing a function 'test2 '- do_something is a C macro
STRING func_test2(INT arg) {
do_something(arg);
}
I've been looking at the emit pragma and Source code filters in order to achieve this but I'm not quite sure this is the best way to go. If you have any suggestions, can point me to the right direction, or to some code that does something similar, I'd be grateful. Thanks.
Haven't you considered macros? You could have something like this:
import
my_awesome_DSL_macros
func_declare:
test1(arg: DATA): DATA
func_create:
test2(arg: int): string = do_something(arg)
The func_declare: and func_create: are macros which take a body of your DSL code, parse it and compile it to whatever you want. Of course, depending on how powerful your DSL is, writing these macros may be as hard as writing a compiler, but that depends on your use case.
This is my best shot at generating your C code without codegendecl or emit.
type
Data {.importc: "DATA".} = object
...
Int {.importc: "INT".} = int
String {.importc: "STRING".} = string
proc test1(arg: Data): Data {.exportc: "func_test1", importc: "func_test1".} # not sure if this is OK to do
proc do_something(arg: Int): String {.importc.}
proc test2(arg: Int): String {.exportc: "func_test2".} =
do_something(arg)
Of course I have no idea what your use case is so this might not be a good reference at all.