-
Notifications
You must be signed in to change notification settings - Fork 0
/
importer.go
53 lines (45 loc) · 1.16 KB
/
importer.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package main
import (
"context"
"fmt"
"os"
"github.com/risor-io/risor"
"github.com/risor-io/risor/compiler"
"github.com/risor-io/risor/object"
"github.com/risor-io/risor/parser"
)
type embedImporter struct {
globals []string
}
func newEmbedImporter() *embedImporter {
cfg := risor.NewConfig()
return &embedImporter{
globals: cfg.GlobalNames(),
}
}
func (i *embedImporter) Import(ctx context.Context, name string) (*object.Module, error) {
// check if file name.risor exists
var source []byte
if _, err := os.Stat("lib/" + name + ".risor"); os.IsNotExist(err) {
source, err = _rsrLib.ReadFile("lib/" + name + ".risor")
if err != nil {
return nil, fmt.Errorf("import error: module %q not found", name)
}
} else {
source, err = os.ReadFile("lib/" + name + ".risor")
if err != nil {
return nil, fmt.Errorf("import error: module %q not found", name)
}
}
ast, err := parser.Parse(ctx, string(source))
if err != nil {
return nil, err
}
var opts []compiler.Option
opts = append(opts, compiler.WithGlobalNames(i.globals))
code, err := compiler.Compile(ast, opts...)
if err != nil {
return nil, err
}
return object.NewModule(name, code), nil
}