-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnative.go
115 lines (94 loc) · 2.45 KB
/
native.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
package dune
import (
"strings"
)
var allNativeFuncs []NativeFunction
var allNativeMap map[string]NativeFunction = make(map[string]NativeFunction)
var typeDefs = []string{header}
type NativeObject interface {
GetMethod(name string) NativeMethod
GetField(name string, vm *VM) (Value, error)
SetField(name string, v Value, vm *VM) error
}
// NativeFunction is a function written in Go as opposed to an interpreted function
type NativeFunction struct {
Name string
Arguments int
Index int
Permissions []string
Function func(this Value, args []Value, vm *VM) (Value, error)
}
type NativeMethod func(args []Value, vm *VM) (Value, error)
func (NativeMethod) Type() string {
return "[native method]"
}
type nativePrototype struct {
this Value
fn int
}
func (nativePrototype) Type() string {
return "[native prototype]"
}
func AddNativeFunc(f NativeFunction) {
// replace if it already exists
if existingFunc, ok := allNativeMap[f.Name]; ok {
f.Index = existingFunc.Index
allNativeMap[f.Name] = f
return
}
f.Index = len(allNativeFuncs)
allNativeFuncs = append(allNativeFuncs, f)
allNativeMap[f.Name] = f
}
func RegisterLib(funcs []NativeFunction, dts string) {
for _, f := range funcs {
AddNativeFunc(f)
}
if dts != "" {
typeDefs = append(typeDefs, dts)
}
}
func NativeFuncFromIndex(i int) NativeFunction {
return allNativeFuncs[i]
}
func NativeFuncFromName(name string) (NativeFunction, bool) {
f, ok := allNativeMap[name]
return f, ok
}
func AllNativeFuncs() []NativeFunction {
return allNativeFuncs
}
func TypeDefs() string {
return strings.Join(typeDefs, "\n\n")
}
const header = `/**
* ------------------------------------------------------------------
* Native definitions.
* ------------------------------------------------------------------
*/
// for the ts compiler
interface Boolean { }
interface Function { }
interface IArguments { }
interface Number { }
interface Object { }
interface RegExp { }
interface byte { }
declare const Symbol: symbol
declare const Array: any
interface Array<T> {
[n: number]: T
slice(start?: number, count?: number): Array<T>
range(start?: number, end?: number): Array<T>
append(v: T[]): T[]
push(...v: T[]): void
pushRange(v: T[]): void
length: number
insertAt(i: number, v: T): void
removeAt(i: number): void
removeAt(from: number, to: number): void
indexOf(v: T): number
join(sep: string): T
sort(comprarer: (a: T, b: T) => boolean): void
}
`