This repository has been archived by the owner on Sep 24, 2019. It is now read-only.
/
context.go
259 lines (220 loc) · 6.96 KB
/
context.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
// Copyright 2013-2015 Oliver Eilhard.
// Use of this source code is governed by the MIT LICENSE that
// can be found in the MIT-LICENSE file included in the project.
package mruby
/*
#cgo pkg-config: mruby
#include "mruby_go.h"
*/
import "C"
import (
"reflect"
"runtime"
"sync"
"unsafe"
)
var (
contextsFu sync.Mutex // guards contexts
contexts map[*C.mrb_state]*Context // list of all Contexts
)
// Context serves as the entry point for all communication with mruby.
type Context struct {
mrb *C.mrb_state
ctx *C.mrbc_context
methodsMu sync.Mutex // guards the next variables
methodsByRClass map[*C.struct_RClass]methodMap
noExec bool // automatically "run" the scripts given to the context
filename string // filename used internally
}
// NewContext creates a new mruby context. Use the options to handle
// configuration.
//
// Examples:
// ctx := mruby.NewContext()
// ctx := mruby.NewContext(mruby.SetNoExec(true), mruby.SetFilename("simple.rb"))
func NewContext(options ...func(*Context)) *Context {
contextsFu.Lock()
defer contextsFu.Unlock()
if contexts == nil {
contexts = make(map[*C.mrb_state]*Context)
}
ctx := &Context{
noExec: false,
filename: "(mruby-go)",
}
// Run configuration handlers
for _, option := range options {
option(ctx)
}
// Finalize setup of MRB context
cfilename := C.CString(ctx.filename)
defer C.free(unsafe.Pointer(cfilename))
captureErrors := C.mrb_bool(1)
noExec := C.mrb_bool(0)
if ctx.noExec {
noExec = C.mrb_bool(1)
}
ctx.mrb = C.mrb_open()
ctx.ctx = C.my_context_new(ctx.mrb, cfilename, captureErrors, noExec)
runtime.SetFinalizer(ctx, func(x *Context) {
contextsFu.Lock()
delete(contexts, x.mrb)
C.mrbc_context_free(x.mrb, x.ctx)
C.mrb_close(x.mrb)
x.mrb = nil
x.ctx = nil
contextsFu.Unlock()
})
contexts[ctx.mrb] = ctx
return ctx
}
// SetNoExec indicates whether scripts given to this context, e.g. via
// LoadString, are automatically run once loaded and/or parsed.
// It is used for configuring a Context (see NewContext for details).
func SetNoExec(noExec bool) func(*Context) {
return func(ctx *Context) {
ctx.noExec = noExec
}
}
// SetFilename sets the filename to be used in the context (default: "(mruby-go)").
// It is used for configuring a Context (see NewContext for details).
func SetFilename(filename string) func(*Context) {
return func(ctx *Context) {
ctx.filename = filename
}
}
// GC runs the full MRuby garbage collector.
func (ctx *Context) GC() {
C.mrb_full_gc(ctx.mrb)
}
// GC runs the incremental MRuby garbage collector.
func (ctx *Context) IncrementalGC() {
C.mrb_incremental_gc(ctx.mrb)
}
// ObjectClass runs the class for Object class.
func (ctx *Context) ObjectClass() *Class {
return &Class{ctx: ctx, class: ctx.mrb.object_class}
}
// ObjectModule is the same as ObjectClass, however it returns a Module.
func (ctx *Context) ObjectModule() *Module {
return &Module{ctx: ctx, module: ctx.mrb.object_class}
}
// KernelModule runs the class for the Kernel module.
func (ctx *Context) KernelModule() *Module {
return &Module{ctx: ctx, module: ctx.mrb.kernel_module}
}
// LoadString loads a snippet of Ruby code and returns its output.
// An error is returned if the interpreter failes or the Ruby code
// raises an exception of type RunError.
func (ctx *Context) LoadString(code string, args ...interface{}) (Value, error) {
ccode := C.CString(code)
defer C.free(unsafe.Pointer(ccode))
ai := C.mrb_gc_arena_save(ctx.mrb)
defer C.mrb_gc_arena_restore(ctx.mrb, ai)
// Create ARGV global variable and push the args into it
argv := C.CString("ARGV")
defer C.free(unsafe.Pointer(argv))
argvAry := C.mrb_ary_new_capa(ctx.mrb, C.mrb_int(len(args)))
for i := 0; i < len(args); i++ {
val, err := ctx.ToValue(args[i])
if err != nil {
return NilValue(ctx), err
}
C.mrb_ary_push(ctx.mrb, argvAry, val.v)
}
C.mrb_define_global_const(ctx.mrb, argv, argvAry)
result := C.mrb_load_string_cxt(ctx.mrb, ccode, ctx.ctx)
if C.has_exception(ctx.mrb) != 0 {
return NilValue(ctx), newRunError(ctx, true)
}
return Value{ctx: ctx, v: result}, nil
}
// LoadStringResult invokes LoadString and returns the Go value immediately.
// Use this method to skip testing the returned Value.
func (ctx *Context) LoadStringResult(code string, args ...interface{}) (interface{}, error) {
val, err := ctx.LoadString(code, args...)
if err != nil {
return NilValue(ctx), err
}
return val.ToInterface()
}
// ToValue stores the given value for encoding/decoding from/to Go and MRuby.
func (ctx *Context) ToValue(value interface{}) (Value, error) {
valof := reflect.ValueOf(value)
switch valof.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return Value{ctx: ctx, v: C.mrb_fixnum_value(C.mrb_int(valof.Int()))}, nil
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
return Value{ctx: ctx, v: C.mrb_fixnum_value(C.mrb_int(valof.Uint()))}, nil
case reflect.Float32, reflect.Float64:
return Value{ctx: ctx, v: C.get_float_value(ctx.mrb, C.mrb_float(valof.Float()))}, nil
case reflect.String:
cs := C.CString(valof.String())
defer C.free(unsafe.Pointer(cs))
return Value{ctx: ctx, v: C.mrb_str_new_cstr(ctx.mrb, cs)}, nil
case reflect.Bool:
if valof.Bool() {
return Value{ctx: ctx, v: C.mrb_true_value()}, nil
} else {
return Value{ctx: ctx, v: C.mrb_false_value()}, nil
}
case reflect.Array, reflect.Slice:
ary := C.mrb_ary_new(ctx.mrb)
for i := 0; i < valof.Len(); i++ {
elem, err := ctx.ToValue(valof.Index(i).Interface())
if err != nil {
return NilValue(ctx), err
}
C.mrb_ary_push(ctx.mrb, ary, elem.v)
}
return Value{ctx: ctx, v: ary}, nil
case reflect.Map:
hsh := C.mrb_hash_new(ctx.mrb)
for _, key := range valof.MapKeys() {
mapvalue := valof.MapIndex(key)
keyv, err := ctx.ToValue(key.String())
if err != nil {
return NilValue(ctx), err
}
valv, err := ctx.ToValue(mapvalue.Interface())
if err != nil {
return NilValue(ctx), err
}
C.mrb_hash_set(ctx.mrb, hsh, keyv.v, valv.v)
}
return Value{ctx: ctx, v: hsh}, nil
case reflect.Interface:
return ctx.ToValue(valof.Elem().Interface())
case reflect.Ptr:
// Drill down.
if valof.IsNil() {
return NilValue(ctx), nil
} else {
valof = valof.Elem()
return ctx.ToValue(valof.Interface())
}
}
return NilValue(ctx), nil
}
/*
// GetArgs extracts the arguments from args.
func (ctx *Context) GetArgs(format string, args Value) (Value, error) {
cformat := C.CString(format)
defer C.free(unsafe.Pointer(cformat))
v := C.my_get_args(ctx.mrb, args.v, cformat)
return Value{ctx: ctx, v: v}, nil
}
*/
// GetArgs extracts the arguments from args.
func (ctx *Context) GetArgs() ([]Value, error) {
getArgLock.Lock()
defer getArgLock.Unlock()
getArgAccumulator = make([]*C.mrb_value, 0)
C.my_get_args_all(ctx.mrb)
values := make([]Value, 0)
for _, v := range getArgAccumulator {
values = append(values, Value{ctx: ctx, v: *v})
}
getArgAccumulator = nil
return values, nil
}