You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
While using tengo embedded into some code, I wanted to make it possible to dynamically provide source code for imports, without having to import files from disk. Specifically, the import names I want to use do not map to files on disk, and are unknown before compiling a script (so I couldn't even somehow pre-generate them anywhere).
I couldn't find any easy way to do it, just a very ugly hack, based on trying to compile on a loop, handling any CompilerError on ImportExpr by generating the module I need, adding it to a ModuleMap, and trying again. Something like this:
moduleMap:=tengo.NewModuleMap()
script:=tengo.NewScript(src)
script.SetImports(moduleMap)
varc*tengo.Compiledvarerrerrordone:=falsefor!done {
done=truec, err=script.Compile()
varcerr*tengo.CompilerErroriferrors.As(err, &cerr) {
ifnode, ok:=cerr.Node.(*parser.ImportExpr); ok {
mSrc:=generateModuleSource(node.ModuleName)
moduleMap.AddSourceModule(node.ModuleName, mSrc)
err=nildone=false
}
}
}
iferr!=nil { ... }
// use c here
But this is beyond ugly.
There's a rather simple alternative: if we extract a trivial interface from *tengo.ModuleMap with just its Get method, and change a few places that declare parameters or fields with the new interface, I can pass an interface instead, and do my dynamic generation there.
Hi!
While using
tengo
embedded into some code, I wanted to make it possible to dynamically provide source code for imports, without having to import files from disk. Specifically, the import names I want to use do not map to files on disk, and are unknown before compiling a script (so I couldn't even somehow pre-generate them anywhere).I couldn't find any easy way to do it, just a very ugly hack, based on trying to compile on a loop, handling any
CompilerError
onImportExpr
by generating the module I need, adding it to aModuleMap
, and trying again. Something like this:But this is beyond ugly.
There's a rather simple alternative: if we extract a trivial interface from
*tengo.ModuleMap
with just itsGet
method, and change a few places that declare parameters or fields with the new interface, I can pass an interface instead, and do my dynamic generation there.E.g.:
This has the added benefit of getting the code closer to Go's good practice of taking interfaces instead of concrete types.
Will send a PR soon.
Thoughts?
The text was updated successfully, but these errors were encountered: