risor-io / risor

Fast and flexible scripting for Go developers and DevOps.
https://risor.io
Apache License 2.0
581 stars 24 forks source link

Add code generator for writing Risor Go modules #158

Closed applejag closed 6 months ago

applejag commented 6 months ago

Writing the Go modules for Risor is quite easy, but there's so much boilerplate. What if you wrote the functions as normal Go functions, and then generate the mapping functions to it?

Such as:

//risor:export
func Repeat(str string, count int) string {
    return strings.Repeat(str, count)
}

And it generates a file with this:

func gen_Repeat(ctx context.Context, args ...object.Object) object.Object {
    numArgs := len(args)
    if numArgs < 2 {
        return object.Errorf("type error: strings.repeat() takes 2 arguments (%d given)", len(args))
    }
    param1, err := object.AsString(args[0])
    if err != nil {
        return err
    }
    param2, err := object.AsInt(args[1])
    if err != nil {
        return err
    }
    return object.NewString(Repeat(param1, int(param2)))
}

func Module() *object.Module {
    return object.NewBuiltinsModule("strings", map[string]object.Object{
        "repeat": object.NewBuiltin("strings.repeat", gen_Repeat),
    })
}

This would not replace the docs generation and parsing proposed by https://github.com/risor-io/risor/issues/118#issuecomment-1859215640 but instead complement it. One does not exclude the other

applejag commented 6 months ago

I've always wanted to try toy with some simple Go parsing and generation, so I'm currently working on this, and will submit a PR later. So we can see if this could stay