risor-io/risor

Add code generator for writing Risor Go modules

Closed this issue · 1 comments

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 #118 (comment) but instead complement it. One does not exclude the other

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