mirascript 0.0.6__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,39 @@
1
+ from dataclasses import dataclass
2
+ from typing import Any, Callable, Dict, Optional, Union
3
+ from .module import VmModule
4
+ from .extern import VmExtern
5
+
6
+ ## 标记未初始化的值
7
+ Uninitialized = type("Uninitialized", (), {})()
8
+
9
+
10
+ ## 标记当前未返回的值
11
+ NotReturned = type("NotReturned", (), {})()
12
+
13
+
14
+ # 类型别名
15
+ VmPrimitive = Union[type(None), str, int, float, bool]
16
+
17
+ VmRecord = dict
18
+ VmArray = list
19
+ VmConst = Union[type(None), str, int, float, bool, dict, list]
20
+
21
+
22
+
23
+ VM_ARRAY_MAX_LENGTH = 2 ** 31 - 1
24
+
25
+ class VmFunctionLike():
26
+ def __call__(self, *args): ... # type: ignore
27
+
28
+
29
+ VmImmutable = Union[ VmConst , VmModule]
30
+
31
+ VmValue =Union[ VmImmutable , VmExtern]
32
+ VmUninitialized = type(Uninitialized)
33
+ VmAny = Union[VmValue , VmUninitialized]
34
+
35
+ kVmFunction = 'mirascript_vm_function'
36
+ def getVmFunctionInfo(value) :
37
+ if (not callable(value)):
38
+ return None
39
+ return getattr(value, kVmFunction, None)
@@ -0,0 +1,130 @@
1
+ # -*- coding: utf-8 -*-
2
+ from typing import Any, Callable, Dict, Iterable, Optional
3
+ from collections.abc import Mapping
4
+
5
+ from mirascript.vm.error import VmError
6
+ from mirascript.vm.types.const import Uninitialized
7
+ from .checker import is_vm_any
8
+
9
+ # from .function import VmFunction
10
+ from .extern import wrap_to_vm_value
11
+
12
+ # 依赖的外部函数和类型需在其他模块实现或导入
13
+ # from . import wrap_to_vm_value, is_vm_any
14
+
15
+ # 全局共享上下文
16
+ VmSharedContext: Dict[str, Any] = {}
17
+
18
+ # def define_vm_context_value(name: str, value: Any, override: bool = False):
19
+ # if not override and name in VmSharedContext:
20
+ # raise RuntimeError(f"Global variable '{name}' is already defined.")
21
+ # v = value
22
+ # # 如果是函数且不是VmFunction,自动包裹
23
+ # if callable(value) :
24
+ # v = VmFunction(value, isLib=True, fullName=f"global.{name}")
25
+ # VmSharedContext[name] = v if v is not None else None
26
+
27
+ _K_VM_CONTEXT = "__mira_vm_context__"
28
+
29
+
30
+ class VmContext:
31
+ def __init__(self):
32
+ setattr(self, _K_VM_CONTEXT, True)
33
+
34
+ def keys(self) -> Iterable[str]:
35
+ return VmSharedContext.keys()
36
+
37
+ def get(self, key: str) -> Any:
38
+ # return VmSharedContext.get(key, None)
39
+ val = VmSharedContext.get(key, Uninitialized)
40
+ if val is Uninitialized:
41
+ raise VmError(f"Global variable '{key}' is not defined.", None)
42
+ return val
43
+
44
+ def has(self, key: str) -> bool:
45
+ return key in VmSharedContext
46
+
47
+ def __getattr__(self, key):
48
+ return self.get(key)
49
+
50
+ def __getitem__(self, key):
51
+ return self.get(key)
52
+
53
+
54
+ class ValueVmContext(VmContext):
55
+ def __init__(self, env: Dict[str, Any]):
56
+ super().__init__()
57
+ self.env = env
58
+ self._cached_keys = None
59
+
60
+ def keys(self) -> Iterable[str]:
61
+ if self._cached_keys is None:
62
+ self._cached_keys = list(self.env.keys())
63
+ return list(self._cached_keys) + list(VmSharedContext.keys())
64
+
65
+ def get(self, key: str) -> Any:
66
+ # return self.env.get(key, None)
67
+ val = self.env.get(key, Uninitialized)
68
+ if val is Uninitialized:
69
+ raise VmError(f"Global variable '{key}' is not defined.", None)
70
+ return val
71
+
72
+ def has(self, key: str) -> bool:
73
+ return key in self.env
74
+
75
+
76
+ class FactoryVmContext(VmContext):
77
+ def __init__(
78
+ self,
79
+ getter: Callable[[str], Any],
80
+ enumerator: Optional[Callable[[], Iterable[str]]] = None,
81
+ ):
82
+ super().__init__()
83
+ self.getter = getter
84
+ self.enumerator = enumerator
85
+
86
+ def keys(self) -> Iterable[str]:
87
+ if not self.enumerator:
88
+ return VmSharedContext.keys()
89
+ return list(self.enumerator()) + list(VmSharedContext.keys())
90
+
91
+ def get(self, key: str) -> Any:
92
+ value = self.getter(key)
93
+ if value is not None:
94
+ return value
95
+ return VmSharedContext.get(key, None)
96
+
97
+ def has(self, key: str) -> bool:
98
+ return self.getter(key) is not None or key in VmSharedContext
99
+
100
+
101
+ def create_vm_context(*args) -> VmContext:
102
+ if len(args) == 0 or (args[0] is None and (len(args) < 2 or args[1] is None)):
103
+ return VmContext()
104
+ if callable(args[0]):
105
+ return FactoryVmContext(args[0], args[1] if len(args) > 1 else None)
106
+
107
+
108
+ vm_values = args[0] if len(args) > 0 else None
109
+ extern_values = args[1] if len(args) > 1 else None
110
+ env = dict(VmSharedContext)
111
+ if vm_values:
112
+ for key, value in vm_values.items():
113
+ if not is_vm_any(value, False):
114
+ continue
115
+ env[key] = value if value is not None else None
116
+ if extern_values:
117
+ for key, value in extern_values.items():
118
+ env[key] = None if value is None else wrap_to_vm_value(value, None)
119
+ return ValueVmContext(env)
120
+
121
+
122
+ def is_vm_context(context: Any) -> bool:
123
+ return (
124
+ isinstance(context, VmContext)
125
+ and getattr(context, _K_VM_CONTEXT, False) is True
126
+ )
127
+
128
+
129
+ # DefaultVmContext 实例
130
+ DefaultVmContext = VmContext()
@@ -0,0 +1,123 @@
1
+ # -*- coding: utf-8 -*-
2
+ from typing import Any
3
+
4
+ from mirascript.vm.error import VmError
5
+ from .wrapper import VmWrapper
6
+
7
+ # from .module import VmModule
8
+ # from ..error import VmError
9
+
10
+
11
+ def wrap_to_vm_value(value, caller=None):
12
+ if value is None:
13
+ return None
14
+ if callable(value):
15
+ return value
16
+ if isinstance(value, VmWrapper):
17
+ return value
18
+ if isinstance(value, (str, int, float, bool)):
19
+ return value
20
+ # Python 没有 bigint,symbol,undefined
21
+ return VmExtern(value, None)
22
+
23
+
24
+ def unwrap_from_vm_value(value):
25
+ if value is None or not isinstance(value, VmExtern):
26
+ return value
27
+ if value.caller is None or not callable(value.value):
28
+ return value.value
29
+ caller = value.caller.value
30
+ func = value.value
31
+
32
+ def proxy(*args, **kwargs):
33
+ return func(*args, **kwargs)
34
+
35
+ return proxy
36
+
37
+
38
+ class VmExtern(VmWrapper):
39
+
40
+ _VM_EXTERN_SYMBOL='mirascript.vm.extern'
41
+
42
+ def __init__(self, value, caller=None):
43
+ super().__init__(value)
44
+ self.caller = caller
45
+ setattr(self, self._VM_EXTERN_SYMBOL, True)
46
+
47
+ def access(self, key: str, read: bool) -> bool:
48
+
49
+ if key.startswith("_"):
50
+ return False
51
+ if callable(self.value) and key in ("prototype", "arguments", "caller"):
52
+ return False
53
+ if hasattr(self.value, key):
54
+ return True
55
+
56
+ if not read:
57
+ return True
58
+
59
+ if not key in self.value:
60
+ return False
61
+
62
+ if key == "constructor":
63
+ return False
64
+ # 跳过内建属性
65
+ return True
66
+
67
+ def has(self, key: str) -> bool:
68
+ return self.access(key, True)
69
+
70
+ def get(self, key: str) -> Any:
71
+ if not self.has(key):
72
+ return None
73
+
74
+ prop = self.value[key]
75
+ return wrap_to_vm_value(prop, self)
76
+
77
+ def set(self, key: str, value):
78
+ if not self.access(key, False):
79
+ return False
80
+ prop = unwrap_from_vm_value(value)
81
+ self.value[key] = prop
82
+ return True
83
+
84
+ def call(self, args):
85
+ if not callable(self.value):
86
+ raise VmError.from_("Not a callable extern",None,None)
87
+ caller = self.caller.value if self.caller else None
88
+ unwrapped_args = [unwrap_from_vm_value(a) for a in args]
89
+ # Python 没有 Reflect.apply,直接调用
90
+ ret = self.value(*unwrapped_args)
91
+ return wrap_to_vm_value(ret, self)
92
+
93
+ @property
94
+ def callable(self) -> bool:
95
+ return callable(self.value)
96
+
97
+ def keys(self):
98
+ keys = []
99
+ for key, _ in self.value.items():
100
+ if self.has(key):
101
+ keys.append(key)
102
+ return keys
103
+
104
+ def same(self, other) -> bool:
105
+ return (
106
+ isinstance(other, VmExtern)
107
+ and self.value is other.value
108
+ and self.caller is other.caller
109
+ )
110
+
111
+ @property
112
+ def type(self):
113
+ return "extern"
114
+
115
+ @property
116
+ def describe(self) -> str:
117
+ return type(self.value).__name__
118
+
119
+
120
+ def is_vm_extern(value) -> bool:
121
+ if value is None or not isinstance(value, object):
122
+ return False
123
+ return hasattr(value, VmExtern._VM_EXTERN_SYMBOL)
@@ -0,0 +1,28 @@
1
+
2
+ # VmFunction 相关实现,Python 版
3
+ from functools import wraps
4
+ from ..helpers import CpEnter, CpExit
5
+
6
+ from .const import kVmFunction
7
+
8
+
9
+ def VmFunction(fn, option = None):
10
+ if not callable(fn):
11
+ raise TypeError("Invalid function")
12
+ option = option or {}
13
+ if option.get("injectCp"):
14
+ original = fn
15
+
16
+ @wraps(original)
17
+ def wrapped(*args):
18
+ try:
19
+ CpEnter()
20
+ return original(*args)
21
+ finally:
22
+ CpExit()
23
+ fn = wrapped
24
+
25
+ setattr(fn, kVmFunction, option.get('fullName', getattr(original, '__name__', 'unknown')))
26
+
27
+ return fn
28
+
@@ -0,0 +1,33 @@
1
+ # -*- coding: utf-8 -*-
2
+ from typing import Any
3
+ from .wrapper import VmWrapper
4
+
5
+ class VmModule(VmWrapper):
6
+ """
7
+ Mirascript 模块包装器
8
+ """
9
+ def __init__(self, name: str, value: dict):
10
+ super().__init__(value)
11
+ self.name = name
12
+
13
+ def has(self, key):
14
+ return key in self.value
15
+
16
+ def get(self, key: str) -> Any:
17
+ if not self.has(key):
18
+ return None
19
+ return self.value.get(key, None)
20
+
21
+ def keys(self):
22
+ return list(self.value.keys())
23
+
24
+ def same(self, other) -> bool:
25
+ return self is other
26
+
27
+ @property
28
+ def type(self):
29
+ return 'module'
30
+
31
+ @property
32
+ def describe(self) -> str:
33
+ return self.name
@@ -0,0 +1,17 @@
1
+ # -*- coding: utf-8 -*-
2
+
3
+ K_VM_SCRIPT = '__mirascript_vm_script__'
4
+
5
+ class VmScript:
6
+ """
7
+ Mirascript 脚本对象,包装可调用对象及元数据
8
+ """
9
+ def __init__(self, func, source: str):
10
+ self.func = func
11
+ self.source = source
12
+ setattr(self, K_VM_SCRIPT, True)
13
+ def __call__(self, global_ctx=None):
14
+ return self.func(global_ctx) if global_ctx is not None else self.func()
15
+
16
+ def is_vm_script(value) -> bool:
17
+ return callable(value) and getattr(value, K_VM_SCRIPT, False) is True
@@ -0,0 +1,143 @@
1
+ # -*- coding: utf-8 -*-
2
+ from abc import ABC, abstractmethod
3
+ from .const import VmAny
4
+
5
+ class VmWrapper(ABC):
6
+ """
7
+ Mirascript 特殊值的包装器基类
8
+ """
9
+ def __init__(self, value):
10
+ self.value = value
11
+
12
+ @abstractmethod
13
+ def has(self, key: str) -> bool:
14
+ pass
15
+
16
+ @abstractmethod
17
+ def get(self, key: str) -> VmAny:
18
+ pass
19
+
20
+ @abstractmethod
21
+ def keys(self) -> list[str]:
22
+ pass
23
+
24
+ @abstractmethod
25
+ def same(self, other) -> bool:
26
+ pass
27
+
28
+ @property
29
+ @abstractmethod
30
+ def type(self)->str:
31
+ pass
32
+
33
+ @property
34
+ @abstractmethod
35
+ def describe(self) -> str:
36
+ pass
37
+
38
+ def toJSON(self):
39
+ return None
40
+
41
+ def __str__(self):
42
+ return f'<{self.type} {self.describe}>'
43
+
44
+
45
+ class VmModule(VmWrapper):
46
+ """
47
+ Mirascript 模块包装器
48
+ """
49
+ def __init__(self, name: str, value: dict):
50
+ super().__init__(value)
51
+ self.name = name
52
+
53
+ def has(self, key: str) -> bool:
54
+ return key in self.value
55
+
56
+ def get(self, key: str) -> VmAny:
57
+ if not self.has(key):
58
+ return None
59
+ return self.value.get(key, None)
60
+
61
+ def keys(self) -> list[str]:
62
+ return list(self.value.keys())
63
+
64
+ def same(self, other) -> bool:
65
+ return self is other
66
+
67
+ @property
68
+ def type(self):
69
+ return 'module'
70
+
71
+ @property
72
+ def describe(self) -> str:
73
+ return self.name
74
+
75
+
76
+ class VmExtern(VmWrapper):
77
+ def __init__(self, value, caller=None):
78
+ super().__init__(value)
79
+ self.caller = caller
80
+
81
+ def _access(self, key: str, read: bool) -> bool:
82
+ if key.startswith('_'):
83
+ return False
84
+ if callable(self.value) and key in ('prototype', 'arguments', 'caller'):
85
+ return False
86
+ if hasattr(self.value, key):
87
+ return True
88
+ if not read:
89
+ return True
90
+ if not hasattr(self.value, key):
91
+ return False
92
+ if key == 'constructor':
93
+ return False
94
+ # 跳过内建属性
95
+ return True
96
+
97
+ def has(self, key: str) -> bool:
98
+ return self._access(key, True)
99
+
100
+ def get(self, key: str) -> Any:
101
+ if not self.has(key):
102
+ return None
103
+ prop = getattr(self.value, key, None)
104
+ return wrap_to_vm_value(prop, self)
105
+
106
+ def set(self, key: str, value):
107
+ if not self._access(key, False):
108
+ return False
109
+ prop = unwrap_from_vm_value(value)
110
+ setattr(self.value, key, prop)
111
+ return True
112
+
113
+ def call(self, args):
114
+ if not callable(self.value):
115
+ raise Exception('Not a callable extern')
116
+ caller = self.caller.value if self.caller else None
117
+ unwrapped_args = [unwrap_from_vm_value(a) for a in args]
118
+ # Python 没有 Reflect.apply,直接调用
119
+ ret = self.value(*unwrapped_args)
120
+ return wrap_to_vm_value(ret, self)
121
+
122
+ @property
123
+ def callable(self) -> bool:
124
+ return callable(self.value)
125
+
126
+ def keys(self) -> list[str]:
127
+ keys = []
128
+ for key in dir(self.value):
129
+ if self.has(key):
130
+ keys.append(key)
131
+ return keys
132
+
133
+ def same(self, other) -> bool:
134
+ return isinstance(other, VmExtern) and self.value is other.value and self.caller is other.caller
135
+
136
+ @property
137
+ def type(self):
138
+ return 'extern'
139
+
140
+ @property
141
+ def describe(self) -> str:
142
+ return type(self.value).__name__
143
+
@@ -0,0 +1,56 @@
1
+ from abc import ABC, abstractmethod
2
+
3
+
4
+ class VmWrapper(ABC):
5
+
6
+
7
+ _VM_WRAPPER_SYMBOL='mirascript.vm.wrapper'
8
+
9
+
10
+
11
+ def __init__(self,value):
12
+
13
+ self.value=value
14
+ # 设置标识符号
15
+ setattr(self, self._VM_WRAPPER_SYMBOL, True)
16
+ pass
17
+
18
+ @abstractmethod
19
+ def has(self,key):
20
+ pass
21
+ @abstractmethod
22
+ def get(self,key):
23
+ pass
24
+ @abstractmethod
25
+ def keys(self):
26
+ pass
27
+ @abstractmethod
28
+ def same(self,other):
29
+ pass
30
+
31
+ @property
32
+ @abstractmethod
33
+ def type(self):
34
+ return None
35
+
36
+ @property
37
+ @abstractmethod
38
+ def describe(self):
39
+ return None
40
+
41
+
42
+ ## Convert the object to JSON
43
+ def toJSON(self):
44
+ return None
45
+
46
+ ## 转为字符串
47
+ def toString(self):
48
+ if self.describe is None:
49
+ return f"<{self.type}>"
50
+ return f"<{self.type} {self.describe}>"
51
+
52
+ def isVmWrapper(v):
53
+ if v is None or not isinstance(v,object):
54
+ return False
55
+
56
+ return hasattr(v,VmWrapper._VM_WRAPPER_SYMBOL)
@@ -0,0 +1,17 @@
1
+ Metadata-Version: 2.1
2
+ Name: mirascript
3
+ Version: 0.0.6
4
+ Summary: cloudpss mirascript
5
+ Home-page: https://www.cloudpss.net
6
+ Author: cloudpss
7
+ Author-email: zhangdaming@cloudpss.net
8
+ License: MIT Licence
9
+ Keywords: cloudpss,cloudpss-mirascript,mirascript
10
+ Platform: any
11
+ Classifier: Programming Language :: Rust
12
+ Classifier: Programming Language :: Python :: Implementation :: CPython
13
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
14
+ Requires-Python: >=3.7
15
+ Description-Content-Type: text/markdown
16
+
17
+ MiraScript 的 Python 绑定允许在 Python 中使用 MiraScript 编译器。它提供了一个简单的接口来编译 MiraScript 脚本,并返回编译结果和诊断信息。
@@ -0,0 +1,26 @@
1
+ mirascript/__init__.py,sha256=MTrrkzcQqU9pZtvnwBDbHKmxGEh63ttmI1m1s3NzLJM,293
2
+ mirascript/deep_nonlocal_fix.py,sha256=6JVPiiH68emz-92qB2MQXgMMP8fCj0Ig7vTiGFY33FA,6385
3
+ mirascript/diagnostics.py,sha256=9Tdb7GHwDVw2BXsaWWtJl1XHuMs9wWOhGC2SpdQhwPQ,2183
4
+ mirascript/emit.py,sha256=suUcLP6_zwp-jhu80kgXzoQtoPXMmVyoFKQyVzPOZe0,48852
5
+ mirascript/main.py,sha256=nhbI7x1NVkDbRTSZi37C4hNgXN0kAF7jgP_91dt3VIk,739
6
+ mirascript/subtle.py,sha256=HE8mTIUsC2fHPh3r7X10aHxaO0ViK5CY2N2VXCi7oZI,233
7
+ mirascript/vm/VmWrapper.py,sha256=5f0H-OuXStP5Xj0ZI3OcAmdxeukvd1tpAzhi0ANkO2Y,857
8
+ mirascript/vm/__init__.py,sha256=sTMYi45oM8UAmkHy_m--EqHJpL8hobYIcW97zUpkF8c,439
9
+ mirascript/vm/env.py,sha256=QsoSwAtPmZTGjcFFWWoYzwRMpO8pkTeaFI1_1F1XzFY,344
10
+ mirascript/vm/error.py,sha256=mGYxSmkrhv6QLWgu3SGo7Nt6RffkTdwarJtlFUo_H9Y,431
11
+ mirascript/vm/helpers.py,sha256=RgvrfVQj4b942m1FPNgiuowYDJOcTxbJ6ASAMgVyOLM,3082
12
+ mirascript/vm/operations.py,sha256=WwF15jpvNCcZ9LCHNh1hnHF4kI1nU6wLT_8dE7F_Sjo,14196
13
+ mirascript/vm/types/__init__.py,sha256=e4rOUSXBVJHvz74l8MGo3HSqXoGLo_VsVNuWfgdEBMc,831
14
+ mirascript/vm/types/checker.py,sha256=g8-WWWzcu816yt4gpSln2KzuyvSJ3YDGp41jaljyDlo,2510
15
+ mirascript/vm/types/const.py,sha256=cqttlQtd5vNTYE1T5J6MFjo4RTBqlPm6eWYZuBervbU,956
16
+ mirascript/vm/types/context.py,sha256=3UJrhOUT2ZNAXgavOkYB2SFl2g7ImUgj5AMzjlCFmN4,3987
17
+ mirascript/vm/types/extern.py,sha256=zvvrr3yO9uUnhvX-BANTYw_b73x3sC9xLKCwXAFqTqE,3335
18
+ mirascript/vm/types/function.py,sha256=blYYgGe5j1RZdGur8rMKjAgRLH6Wx56GeZ5fQN--LUU,678
19
+ mirascript/vm/types/module.py,sha256=vjVgLaHNmwQad5woMklzcMQR9xBqEllqQ14xd2QQzkk,604
20
+ mirascript/vm/types/script.py,sha256=OmZdxGtIrHSYPhoHTyNVXYPMtP3bqtbPPz8LtatEvlo,488
21
+ mirascript/vm/types/types.py,sha256=_VRnkTqp35XXMzLbK_gDNpjaurT8YcFFDUEuaaXhYhE,2897
22
+ mirascript/vm/types/wrapper.py,sha256=a1-UI_zgYk1bTL07lbRWJHevDaVvcnkJ0QY7e-D4e50,1085
23
+ mirascript-0.0.6.dist-info/METADATA,sha256=HrWiUkAN_Juak5jPAi8mB2klvDsTtKj8cRniNJzCWlo,704
24
+ mirascript-0.0.6.dist-info/WHEEL,sha256=oiQVh_5PnQM0E3gPdiz09WCNmwiHDMaGer_elqB3coM,92
25
+ mirascript-0.0.6.dist-info/top_level.txt,sha256=I-eqKgnvXv-32Ugvcg7P6CrGz1cjPstqxe_wdLwCme0,11
26
+ mirascript-0.0.6.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: bdist_wheel (0.42.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ mirascript