-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathenv.go
323 lines (283 loc) · 8.07 KB
/
env.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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
package interpreter
import (
"fmt"
"github.com/Eclalang/Ecla/interpreter/eclaDecl"
"os"
"path/filepath"
"runtime"
"github.com/Eclalang/Ecla/errorHandler"
"github.com/Eclalang/Ecla/interpreter/eclaType"
"github.com/Eclalang/Ecla/lexer"
met "github.com/Eclalang/Ecla/metrics"
"github.com/Eclalang/Ecla/parser"
libs "github.com/Eclalang/LibraryController"
)
func InitBuildIn() *Scope {
vars := NewScopeMain()
v, err := eclaType.NewVar("typeof", "", eclaType.NewTypeOf())
if err != nil {
panic(err)
}
vars.Set("typeOf", v)
v, err = eclaType.NewVar("sizeof", "", eclaType.NewSizeOf())
if err != nil {
panic(err)
}
vars.Set("sizeOf", v)
v, err = eclaType.NewVar("len", "", eclaType.NewLen())
if err != nil {
panic(err)
}
vars.Set("len", v)
v, err = eclaType.NewVar("append", "", eclaType.NewAppend())
if err != nil {
panic(err)
}
vars.Set("append", v)
return vars
}
// Env is the environment in which the code is executed.
type Env struct {
Vars *Scope
OS string
ARCH string
SyntaxTree *parser.File
Tokens []lexer.Token
File string
Code string
Libs map[string]libs.Lib
ErrorHandle *errorHandler.ErrorHandler
ExecutedFunc []*eclaType.Function
TypeDecl []eclaDecl.TypeDecl
}
// NewEnv returns a new Env.
func NewEnv() *Env {
return &Env{
OS: runtime.GOOS,
ARCH: runtime.GOARCH,
Vars: InitBuildIn(),
Libs: make(map[string]libs.Lib),
ErrorHandle: errorHandler.NewHandler(),
ExecutedFunc: []*eclaType.Function{},
}
}
// NewTemporaryEnv returns a new temporary Env.
// Temporary Env are used to import modules.
func NewTemporaryEnv(ErrorHandler *errorHandler.ErrorHandler) *Env {
return &Env{
OS: runtime.GOOS,
ARCH: runtime.GOARCH,
Vars: InitBuildIn(),
Libs: make(map[string]libs.Lib),
ErrorHandle: ErrorHandler,
ExecutedFunc: []*eclaType.Function{},
}
}
func (env *Env) String() string {
return fmt.Sprintf("Env{OS: %s, ARCH: %s , CODE: %s }", env.OS, env.ARCH, env.Code)
}
// SetCode sets the code to be executed.
func (env *Env) SetCode(code string) {
env.Code = code
}
// SetFile sets the file to be executed.
func (env *Env) SetFile(file string) {
env.File = file
}
// SetVar sets the value of the variable with the given name.
func (env *Env) SetVar(name string, value *eclaType.Var) {
env.Vars.Set(name, value)
}
// GetVar returns the value of the variable with the given name.
func (env *Env) GetVar(name string) (*eclaType.Var, bool) {
v, ok := env.Vars.Get(name)
return v, ok
}
// CheckIfVarExistsInCurrentScope returns true if the variable exists in the current scope.
func (env *Env) CheckIfVarExistsInCurrentScope(name string) bool {
return env.Vars.CheckIfVarExistsInCurrentScope(name)
}
// NewScope creates a new scope.
func (env *Env) NewScope(Type ScopeType) {
env.Vars.GoDeep(Type)
}
// SetScope sets the most deep scope.
func (env *Env) SetScope(s *Scope) {
env.Vars.GoDeepWithSpecificScope(s)
}
// EndScope ends the current scope.
func (env *Env) EndScope() {
env.Vars.GoUp()
}
// SetFunction sets the function with the given name.
func (env *Env) SetFunction(name string, f *eclaType.Function) error {
v, err := eclaType.NewVar(name, f.GetType(), f)
if err != nil {
return err
}
env.Vars.Set(name, v)
return nil
}
// Execute executes Env.Code or Env.File.
func (env *Env) Execute() {
// catch all panics
defer func() {
if r := recover(); r != nil {
env.ErrorHandle.HandleError(0, 0,
fmt.Sprintf("an internal error occured please report it to the developers on https://github.com/Eclalang/Ecla/issues : %v", r),
errorHandler.LevelFatal)
}
}()
if env.File != "" {
var err error
env.Code, err = readFile(env.File)
if err != nil {
env.ErrorHandle.HandleError(0, 0, err.Error(), errorHandler.LevelFatal)
}
}
// Lexing
env.Tokens = lexer.Lexer(env.Code)
// Parsing
pars := parser.Parser{Tokens: env.Tokens, ErrorHandler: env.ErrorHandle}
env.SyntaxTree = pars.Parse()
// Execute
Run(env)
}
func (env *Env) ExecuteMetrics() met.Metrics {
if env.File != "" {
var err error
env.Code, err = readFile(env.File)
if err != nil {
env.ErrorHandle.HandleError(0, 0, err.Error(), errorHandler.LevelFatal)
}
}
m := met.NewMetrics()
m.StartTimers()
// Lexing
m.StartLexerTimer()
env.Tokens = lexer.Lexer(env.Code)
m.StopLexerTimer()
// Parsing
m.StartParserTimer()
pars := parser.Parser{Tokens: env.Tokens, ErrorHandler: env.ErrorHandle}
env.SyntaxTree = pars.Parse()
m.StopParserTimer()
// Execute
m.StartInterpreterTimer()
Run(env)
m.StopInterpreterTimer()
m.StopTotalTimer()
return *m
}
// Load the file
func (env *Env) Load() {
var err error
env.Code, err = readFile(env.File)
if err != nil {
env.ErrorHandle.HandleError(0, 0, err.Error(), errorHandler.LevelFatal)
}
// Lexing
env.Tokens = lexer.Lexer(env.Code)
// Parsing
pars := parser.Parser{Tokens: env.Tokens, ErrorHandler: env.ErrorHandle}
env.SyntaxTree = pars.Parse()
Load(env)
}
// Import executes an import statement.
func (env *Env) Import(stmt parser.ImportStmt) {
file := stmt.ModulePath
temp := libs.Import(file)
if temp == nil {
if !filepath.IsAbs(file) {
file = filepath.Join(filepath.Dir(env.File), stmt.ModulePath)
}
if _, err := os.Stat(file); os.IsNotExist(err) {
env.ErrorHandle.HandleError(stmt.StartLine(), stmt.StartPos(), fmt.Sprintf("module '%s' not found", file), errorHandler.LevelFatal)
} else if err != nil {
env.ErrorHandle.HandleError(stmt.StartLine(), stmt.StartPos(), err.Error(), errorHandler.LevelFatal)
}
tempsEnv := NewTemporaryEnv(env.ErrorHandle)
tempsEnv.SetFile(file)
tempsEnv.Load()
temp = tempsEnv.ConvertToLib(env)
}
name := parser.GetPackageNameByPath(file)
env.Libs[name] = temp
v, err := eclaType.NewVar(name, "", eclaType.NewLib(name))
if err != nil {
env.ErrorHandle.HandleError(stmt.StartLine(), stmt.StartPos(), err.Error(), errorHandler.LevelFatal)
}
env.Vars.Set(name, v)
}
// AddFunctionExecuted adds a function to the pile of executed functions.
func (env *Env) AddFunctionExecuted(f *eclaType.Function) {
env.ExecutedFunc = append(env.ExecutedFunc, f)
}
// GetFunctionExecuted returns the last function executed.
func (env *Env) GetFunctionExecuted() *eclaType.Function {
return env.ExecutedFunc[len(env.ExecutedFunc)-1]
}
// RemoveFunctionExecuted removes the last function executed.
func (env *Env) RemoveFunctionExecuted() {
env.ExecutedFunc = env.ExecutedFunc[:len(env.ExecutedFunc)-1]
}
// envLib represents a library and that uses to compartiment the scope of the library and the scope of the main program.
type envLib struct {
Var *Scope
Libs map[string]libs.Lib
env *Env
}
// Call calls the function with the given name and arguments.
func (lib *envLib) Call(name string, args []eclaType.Type) ([]eclaType.Type, error) {
function, ok := lib.Var.Get(name)
if !ok {
return nil, fmt.Errorf("function '%s' not found", name)
}
if !function.IsFunction() {
return nil, fmt.Errorf("'%s' is not a function", name)
}
f := function.GetFunction()
if f == nil {
return nil, fmt.Errorf("function '%s' is nil", name)
}
// TODO : Change this to more clean code
// Save the current libs
temps := lib.env.Libs
// Set the libs of the lib
lib.env.Libs = lib.Libs
// Run the function
r1, r2 := RunFunctionCallExprWithArgs(name, lib.env, f, args)
// Restore the libs
lib.env.Libs = temps
return r1, r2
}
func (lib *envLib) GetVar(name string) (*eclaType.Var, bool) {
return lib.Var.Get(name)
}
// ConvertToLib converts the Env to a Lib.
func (env *Env) ConvertToLib(MainEnv *Env) libs.Lib {
return &envLib{
Var: env.Vars,
Libs: env.Libs,
env: MainEnv,
}
}
func (env *Env) AddTypeDecl(t eclaDecl.TypeDecl) {
env.TypeDecl = append(env.TypeDecl, t)
}
func (env *Env) GetTypeDecl(name string) (eclaDecl.TypeDecl, bool) {
for _, t := range env.TypeDecl {
if t.GetName() == name {
return t, true
}
}
return nil, false
}
// readFile reads the file at the given path and returns its contents as a string.
func readFile(file string) (string, error) {
v, err := os.ReadFile(file)
if err != nil {
return "", err
}
return string(v), nil
}