-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathload.go
125 lines (114 loc) · 2.43 KB
/
load.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
//
// Copyright (c) 2023 Markku Rossi
//
// All rights reserved.
//
package scheme
import (
"fmt"
"io"
"os"
"path"
"github.com/markkurossi/scheme/types"
)
var loadBuiltins = []Builtin{
{
Name: "scheme::load",
Args: []string{"caller<string>", "filename<string>"},
Return: types.Any,
Native: func(scm *Scheme, args []Value) (Value, error) {
caller, ok := args[0].(String)
if !ok {
return nil, fmt.Errorf("invalid caller: %v", args[0])
}
f, ok := args[1].(String)
if !ok {
return nil, fmt.Errorf("invalid filename: %v", args[1])
}
file := string(f)
if !path.IsAbs(file) {
file = path.Join(path.Dir(string(caller)), file)
}
if scm.Params.Verbose {
fmt.Printf("load: %v\n", file)
}
return scm.LoadFile(file)
},
},
{
Name: "scheme::stack-trace",
Return: &types.Type{
Enum: types.EnumPair,
Car: &types.Type{
Enum: types.EnumPair,
Car: types.String,
Cdr: types.InexactInteger,
},
Cdr: types.Any,
},
Native: func(scm *Scheme, args []Value) (Value, error) {
stack := scm.StackTrace()
var result, tail Pair
for _, frame := range stack {
p := NewPair(
NewPair(String(frame.Source),
NewNumber(frame.Line)),
nil)
if tail == nil {
result = p
} else {
tail.SetCdr(p)
}
tail = p
}
return result, nil
},
},
{
Name: "scheme::compile",
Args: []string{"ast<any>"},
Return: &types.Type{
Enum: types.EnumLambda,
Return: types.Any,
},
Native: func(scm *Scheme, args []Value) (Value, error) {
lib, ok := args[0].(*Library)
if !ok {
return nil, fmt.Errorf("invalid library: %v", args[0])
}
v, err := lib.Compile()
if err != nil {
return nil, fmt.Errorf("<<%s", err.Error())
}
return v, nil
},
},
}
// LoadFile loads and compiles the file.
func (scm *Scheme) LoadFile(file string) (Value, error) {
in, err := os.Open(file)
if err != nil {
return nil, err
}
defer in.Close()
return scm.Load(file, in)
}
// Load loads and compiles the input.
func (scm *Scheme) Load(source string, in io.Reader) (Value, error) {
c := NewParser(scm)
library, err := c.Parse(source, in)
if err != nil {
return nil, err
}
if false {
fmt.Printf("Code:\n")
for _, c := range library.Init {
fmt.Printf("%s\n", c)
}
}
return NewPair(&Identifier{Name: "library"},
NewPair(library.Name,
NewPair(library.Exports,
NewPair(library.Imports,
NewPair(library, nil))))), nil
}