Compare commits
361 Commits
v0.9.8
...
v0.20.0-al
| Author | SHA1 | Date | |
|---|---|---|---|
| bddf28b4ad | |||
| daa28dcfd6 | |||
| 14d30a7b3e | |||
| 16502ecc01 | |||
| 9d891b5596 | |||
| 87b7c66282 | |||
| c8df79a072 | |||
| 2aef84604b | |||
| dbecad996a | |||
| c4aded50f1 | |||
| 93b361a2ac | |||
| 923bf102de | |||
| 4a90455131 | |||
| 2ff57d1c0b | |||
| 30fd065bc5 | |||
| f4c04829b1 | |||
| 6816e51239 | |||
| 5ed61829e1 | |||
| 72173b4778 | |||
| 4ee300a22b | |||
| 476d98b9c7 | |||
| cf9153c134 | |||
| b3fa8790e3 | |||
| 27dafe3307 | |||
| 53502e12cf | |||
| 774763be13 | |||
| cabf09e247 | |||
| 2fd10140cf | |||
| 7afea75454 | |||
| 8a2b0d7c2e | |||
| 586b6acbbc | |||
| def62e2940 | |||
| 18329f0a4c | |||
| 39612a1ff3 | |||
| ea1dd6f9ae | |||
| 66eaf6b8b0 | |||
| 157782b43e | |||
| 51fd13e734 | |||
| 293c69a605 | |||
| 88e59231da | |||
| 02dbf535bc | |||
| a4368cc9ba | |||
| dbe9657b26 | |||
| d486e2ab19 | |||
| 293b4e265b | |||
| bf34552321 | |||
| 4f41357953 | |||
| b2177683de | |||
| 081a934747 | |||
| 4f5c9bafa1 | |||
| 1ff3a5ae62 | |||
| 93f44e5a00 | |||
| 67aa4302e0 | |||
| df1646dc15 | |||
| 48cc6325b8 | |||
| f42d5d12ed | |||
| 6617171472 | |||
| f35c8cd3fb | |||
|
|
aa182fb169 | ||
| 8a15a5398f | |||
| ad85c3bc9b | |||
| a3cbe455a1 | |||
|
|
f7a228975f | ||
| 299a8e7791 | |||
| af1e64767a | |||
| f31726e98b | |||
| 4bb2337f39 | |||
| c5fac44362 | |||
|
|
d7e757bcf8 | ||
| c013d0eec5 | |||
| 7f5929bc87 | |||
| d769a9c8ca | |||
| c64d167893 | |||
| 0776d0ddeb | |||
| 3f101ca250 | |||
| 85f2bd5a10 | |||
| c172bcfad7 | |||
| 1d2a528bbb | |||
| d80e858a89 | |||
| 24fc6dc464 | |||
| e38666f12d | |||
| c7079dd82e | |||
| 0fea6b5537 | |||
| 00a84fb58a | |||
| 80fbc071ed | |||
| 14f20897d6 | |||
| a84b82d206 | |||
| 80111d5ada | |||
| fb7e27af82 | |||
| e9a2aa9745 | |||
| 4741e341b7 | |||
| 1b4b249859 | |||
| 78100e8696 | |||
| d0a0e2dd71 | |||
| 7962aa5da0 | |||
| 0667201605 | |||
| afd04ed972 | |||
| 9c137574f5 | |||
| 6597b261fd | |||
| 8432f7fbab | |||
| e731de2162 | |||
| b87fb08d1c | |||
| e7077b1315 | |||
| 05e9feee9b | |||
| af85703bd9 | |||
| 68a996f830 | |||
| 8f944e0b14 | |||
| 6910ea3e26 | |||
| d01938487a | |||
| 606f097989 | |||
| a3cf4fa476 | |||
| 3c1ff6ea41 | |||
| 2990cdc4aa | |||
| f301d130f9 | |||
| 0ae4764c85 | |||
| 8def6257df | |||
| f62d198166 | |||
| 0c71bc3582 | |||
| ea99cbea1d | |||
| b400ab81f0 | |||
| 63ff11def1 | |||
| b1a4c65adb | |||
| 9b28cd4de0 | |||
| e55d48d713 | |||
| 3ea72f0aac | |||
| fe1ee3883a | |||
| 083a01f29f | |||
| 0b0a3bb836 | |||
| 9bb8278477 | |||
| 92647fbea2 | |||
| 1928551023 | |||
| 018889b5eb | |||
| 05244f9bef | |||
| 36c9d4ad99 | |||
| 0bc513d580 | |||
| 678f4ca8a4 | |||
| f4aa568f0c | |||
| 1bb938dcbd | |||
| dc4e554a35 | |||
| 7c016f6ba6 | |||
| cfef52aecd | |||
| 53ee92e20d | |||
| 9b5a303c21 | |||
| 4c0a77ed23 | |||
| 46173ff549 | |||
| 2fb7ddd890 | |||
| e2505597ff | |||
| 17ed9d7d52 | |||
| 5a9e33e695 | |||
| b98409abe7 | |||
| 5420ad460c | |||
| 9587a748eb | |||
| ac2a4f3d6e | |||
| d888d9ab4e | |||
| 2582d51a98 | |||
| 843b65f13b | |||
| c2857a0566 | |||
| 684a033525 | |||
| 503ca79dab | |||
| 46768e4cdd | |||
| f61360f739 | |||
| 8fbf9ef29d | |||
| d6138bc6f4 | |||
| c37a7cb772 | |||
| 4e1a77cc50 | |||
| d614b3741e | |||
| 738bc50939 | |||
| 167abfe3d9 | |||
| aab5c86588 | |||
| 5cd02ac08a | |||
| 0b67ddce42 | |||
| 1e2c17456e | |||
| 8731f5d9ef | |||
| fb3803cae9 | |||
| 84e4052871 | |||
| 2dc662a4d4 | |||
| 2b017d9208 | |||
| 0ca8ae944c | |||
| 1e03b104df | |||
| 7ba34e7e01 | |||
| c016b1db34 | |||
| 3d1ed08473 | |||
| 34ee276556 | |||
| 53f20a9a8f | |||
| 76fd6b8318 | |||
| dfff666284 | |||
| 44fab858d3 | |||
| fea58a4dd6 | |||
| 71308a13a1 | |||
| 34f9b088c7 | |||
| 70929d7ceb | |||
| 2beca068a4 | |||
| e0ab8a5a7b | |||
| e6f9326ae3 | |||
| 58cbacdc85 | |||
| dcbdbcfcdc | |||
| 1662e8e0e9 | |||
| 73fa62a23e | |||
| ca79161505 | |||
| be4fe82588 | |||
| 8ec21a7f99 | |||
| 1431ce0a6e | |||
| e9c13e44b4 | |||
| 6b838ae55d | |||
| de99c0dd92 | |||
| b92cfccb84 | |||
| b03c311956 | |||
| a164f08e1e | |||
| d850c4a16f | |||
| 17fbfabff5 | |||
| e84882e076 | |||
| f224b417bb | |||
| f9458e66c1 | |||
| d22cb515f7 | |||
| 595e11ddfd | |||
| 328d93cd3f | |||
| ccaa268362 | |||
| b04f4899ca | |||
| 4677fba701 | |||
| cbfbc28504 | |||
| 2042b49e0d | |||
| aee0457d9f | |||
| 9b69b1221b | |||
| cbb73b451f | |||
| 5844ca9e7d | |||
| b6318cb8c1 | |||
| efd1e5bd62 | |||
| 5549bdd804 | |||
| 926fc3b17a | |||
| 9dae44278d | |||
| 2fb62b26a0 | |||
| a1e50285a9 | |||
| 25dbefef6f | |||
| 5ef16c5f21 | |||
| 5f0075272c | |||
| 38469741fd | |||
| bbc6058347 | |||
| 2254f22936 | |||
| 9de4038788 | |||
| 0f8243a7ad | |||
| 95ac5d1800 | |||
| 5132019ce6 | |||
| d7061c0c9d | |||
| f28a1e3c66 | |||
| cf3f840b3c | |||
| 12b3973b38 | |||
| b95b4f6928 | |||
| f821998801 | |||
| 27b5642047 | |||
| 85b3bba5d0 | |||
| 343f4ba04b | |||
| 00b27e8999 | |||
| 97877832c4 | |||
| 33d29271f9 | |||
| 9f0e732e37 | |||
| c2b3372d74 | |||
| 8a0fcfae8b | |||
| 08ca3db67b | |||
| 813f761e47 | |||
| 5728c48f16 | |||
| 106abc76e1 | |||
| 6a5b1598d4 | |||
| 0ade2b2855 | |||
| 6cf446e54b | |||
| da07acc6b0 | |||
| f7207d99ba | |||
| 57f2b37401 | |||
| 8f864222ae | |||
| c33b78b029 | |||
| b5b9d3f230 | |||
| 93fa3e2460 | |||
| c1ef761ec7 | |||
| 19e7692756 | |||
| 0fbccbc05f | |||
| b2a24943a4 | |||
| 063fc51f40 | |||
| 126789d49a | |||
| 21394a3b4b | |||
| 11c91600da | |||
| c13c4aefca | |||
| 4fa67549fb | |||
| 26f4c24659 | |||
| 82cf6e6f53 | |||
| e3f3f9ca4e | |||
| 24d77ea34d | |||
| b28da75420 | |||
| caa30083d3 | |||
| 2ddd8c3879 | |||
| 1eefb729d7 | |||
| b6f3a31eca | |||
| d1b6a4d4b2 | |||
| 81fa66684a | |||
| 0b6c174e42 | |||
| bf33381e30 | |||
| 44422d4dcf | |||
| 97b499c0b4 | |||
| 8ccfe499df | |||
| f6df0a2c47 | |||
| e2f32fd0bf | |||
| 1e00dc6530 | |||
| de491bdd62 | |||
| 30ec92fd65 | |||
| f869a524ff | |||
| 72627c08bc | |||
| 0595c3c046 | |||
| 2063a2484d | |||
| a0304183c4 | |||
| e442da5b3b | |||
| 54d12749dc | |||
| 7955f1663a | |||
| 032ef3e37d | |||
| d500546236 | |||
| c9d62cc617 | |||
| fb37d46acc | |||
| 5099430289 | |||
| 73690a2668 | |||
| 7ab3443351 | |||
| b60259c345 | |||
| 7b67dc7719 | |||
| 5a29133561 | |||
| c0106e941b | |||
| 736760b2ee | |||
| 83cc4b6a54 | |||
| 24013bf240 | |||
| a3cf7eb036 | |||
| 0012da9855 | |||
| 364463dc6a | |||
| 8e94683757 | |||
| e1530c49ee | |||
| 4c0290bf21 | |||
| 10cb22c510 | |||
| b939c7c891 | |||
| 032f4d98ae | |||
| ae1519ea4f | |||
| a96756e1ac | |||
| 35f2dbf162 | |||
| c153f9babb | |||
| 0c8d3a04bd | |||
| 0491e6fac9 | |||
| 7137325491 | |||
| 8f183d1ca3 | |||
| db800a4038 | |||
| a851bb543b | |||
| 81c76f4977 | |||
| 7ca81db573 | |||
| b0915648ea | |||
| 9121683e77 | |||
| 8f5882ff0a | |||
| 38bd2f5187 | |||
| 514ac27aca | |||
| 60f6a4e18d | |||
| 046c86681b | |||
| 5ea4b6bdaf | |||
| 500384326f | |||
| eb1bab7e76 | |||
| 928f73a4bf | |||
| c3522aea64 | |||
| e5bab5763c | |||
| 34c598e6d8 | |||
| d06321d9b5 | |||
| bee7e19fc3 |
@@ -1,3 +1,4 @@
|
|||||||
|
src
|
||||||
test
|
test
|
||||||
typings
|
typings
|
||||||
bundled
|
bundled
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
{
|
{
|
||||||
"version": "0.9.8",
|
"version": "0.20.0-alpha.0",
|
||||||
"useWorkspaces": true,
|
"useWorkspaces": true,
|
||||||
"npmClient": "yarn",
|
"npmClient": "yarn",
|
||||||
"packages": [
|
"packages": [
|
||||||
|
|||||||
@@ -9,10 +9,9 @@
|
|||||||
"bs": "lerna bootstrap",
|
"bs": "lerna bootstrap",
|
||||||
"clean": "lerna run clean",
|
"clean": "lerna run clean",
|
||||||
"watch": "lerna run watch --parallel",
|
"watch": "lerna run watch --parallel",
|
||||||
"build": "lerna run build --scope=\"@ccms/!(plugins)\"",
|
"build": "lerna run build",
|
||||||
"build:plugins": "lerna run build --scope=\"@ccms/plugins\"",
|
|
||||||
"ug": "yarn upgrade-interactive --latest",
|
"ug": "yarn upgrade-interactive --latest",
|
||||||
"np": "lerna exec \"npm publish --access=public --registry https://registry.npmjs.org\" --scope=\"@ccms/!(client|plugins)\"",
|
"np": "./script/push.sh",
|
||||||
"lsp": "npm login --registry=https://registry.npmjs.org --scope=@ccms",
|
"lsp": "npm login --registry=https://registry.npmjs.org --scope=@ccms",
|
||||||
"lp": "lerna publish --registry https://registry.npmjs.org"
|
"lp": "lerna publish --registry https://registry.npmjs.org"
|
||||||
},
|
},
|
||||||
@@ -20,6 +19,6 @@
|
|||||||
"packages/*"
|
"packages/*"
|
||||||
],
|
],
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"lerna": "^3.22.1"
|
"lerna": "^4.0.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/amqp",
|
"name": "@ccms/amqp",
|
||||||
"version": "0.9.8",
|
"version": "0.20.0-alpha.0",
|
||||||
"description": "MiaoScript amqp package",
|
"description": "MiaoScript amqp package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -19,17 +19,17 @@
|
|||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ccms/api": "^0.9.8",
|
"@ccms/api": "^0.20.0-alpha.0",
|
||||||
"@ccms/common": "^0.9.8",
|
"@ccms/common": "^0.19.0",
|
||||||
"@ccms/container": "^0.9.8"
|
"@ccms/container": "^0.19.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@ccms/nashorn": "^0.9.8",
|
"@ccms/nashorn": "^0.19.0",
|
||||||
"@javatypes/amqp-client": "^0.0.3",
|
"@javatypes/amqp-client": "^0.0.3",
|
||||||
"@javatypes/spring-amqp": "^0.0.3",
|
"@javatypes/spring-amqp": "^0.0.3",
|
||||||
"@javatypes/spring-rabbit": "^0.0.3",
|
"@javatypes/spring-rabbit": "^0.0.3",
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^4.0.3"
|
"typescript": "^4.5.5"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ export abstract class ChannelAwareMessageListenerAdapter<T = any> {
|
|||||||
if (message.getMessageProperties().getContentType() == MessageProperties.CONTENT_TYPE_JSON) {
|
if (message.getMessageProperties().getContentType() == MessageProperties.CONTENT_TYPE_JSON) {
|
||||||
content = JSON.parse(content)
|
content = JSON.parse(content)
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error: any) {
|
||||||
if (manual) {
|
if (manual) {
|
||||||
channel.basicReject(message.getMessageProperties().getDeliveryTag(), true)
|
channel.basicReject(message.getMessageProperties().getDeliveryTag(), true)
|
||||||
} else {
|
} else {
|
||||||
@@ -42,7 +42,7 @@ export abstract class ChannelAwareMessageListenerAdapter<T = any> {
|
|||||||
} else {
|
} else {
|
||||||
channel.basicNack(deliveryTag, false, true)
|
channel.basicNack(deliveryTag, false, true)
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error: any) {
|
||||||
channel.basicReject(deliveryTag, this.onError(error, message, channel))
|
channel.basicReject(deliveryTag, this.onError(error, message, channel))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/api",
|
"name": "@ccms/api",
|
||||||
"version": "0.9.8",
|
"version": "0.20.0-alpha.0",
|
||||||
"description": "MiaoScript api package",
|
"description": "MiaoScript api package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -19,16 +19,16 @@
|
|||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ccms/common": "^0.9.8",
|
"@ccms/common": "^0.19.0",
|
||||||
"@ccms/container": "^0.9.8",
|
"@ccms/container": "^0.19.0",
|
||||||
"@ccms/ployfill": "^0.9.8",
|
"@ccms/polyfill": "^0.20.0-alpha.0",
|
||||||
"base64-js": "^1.3.1",
|
"base64-js": "^1.5.1",
|
||||||
"source-map-builder": "^0.0.7"
|
"source-map-builder": "^0.0.7"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/base64-js": "^1.3.0",
|
"@types/base64-js": "^1.3.0",
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^4.0.3"
|
"typescript": "^4.5.5"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import i18n from '@ccms/i18n'
|
import i18n from '@ccms/i18n'
|
||||||
import { injectable } from "@ccms/container"
|
import { injectable } from "@ccms/container"
|
||||||
import { plugin } from './interfaces'
|
import { plugin } from './plugin'
|
||||||
|
|
||||||
export namespace command {
|
export namespace command {
|
||||||
@injectable()
|
@injectable()
|
||||||
@@ -44,12 +44,37 @@ export namespace command {
|
|||||||
protected setExecutor(plugin: plugin.Plugin, command: any, executor: Function) {
|
protected setExecutor(plugin: plugin.Plugin, command: any, executor: Function) {
|
||||||
return (sender: any, _: any, command: string, args: string[]) => {
|
return (sender: any, _: any, command: string, args: string[]) => {
|
||||||
try {
|
try {
|
||||||
return executor(sender, command, Java.from(args))
|
let time = Date.now()
|
||||||
} catch (ex) {
|
let result = executor(sender, command, Java.from(args))
|
||||||
console.i18n("ms.api.command.execute.error", { player: sender.name, plugin: plugin.description.name, command, args: Java.from(args).join(' '), ex })
|
let cost = Date.now() - time
|
||||||
|
if (cost > global.ScriptSlowExecuteTime) {
|
||||||
|
console.i18n("ms.api.command.execute.slow", {
|
||||||
|
player: sender.name,
|
||||||
|
plugin: plugin.description.name,
|
||||||
|
command,
|
||||||
|
args: Java.from(args).join(' '),
|
||||||
|
cost
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
} catch (ex: any) {
|
||||||
|
console.i18n("ms.api.command.execute.error", {
|
||||||
|
player: sender.name,
|
||||||
|
plugin: plugin.description.name,
|
||||||
|
command,
|
||||||
|
args: Java.from(args).join(' '),
|
||||||
|
ex
|
||||||
|
})
|
||||||
console.ex(ex)
|
console.ex(ex)
|
||||||
if (sender.name != 'CONSOLE') {
|
if (sender.name != 'CONSOLE') {
|
||||||
console.sender(sender, [i18n.translate("ms.api.command.execute.error", { player: sender.name, plugin: plugin.description.name, command, args: Java.from(args).join(' '), ex }), ...console.stack(ex)])
|
console.sender(sender, [i18n.translate("ms.api.command.execute.error", {
|
||||||
|
player: sender.name,
|
||||||
|
plugin: plugin.description.name,
|
||||||
|
command,
|
||||||
|
args: Java.from(args).join(' '),
|
||||||
|
ex
|
||||||
|
}),
|
||||||
|
...console.stack(ex)])
|
||||||
}
|
}
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
@@ -58,13 +83,42 @@ export namespace command {
|
|||||||
protected setTabCompleter(plugin: plugin.Plugin, command: any, tabCompleter: Function) {
|
protected setTabCompleter(plugin: plugin.Plugin, command: any, tabCompleter: Function) {
|
||||||
return (sender: any, _: any, command: string, args: string[]) => {
|
return (sender: any, _: any, command: string, args: string[]) => {
|
||||||
try {
|
try {
|
||||||
|
let time = Date.now()
|
||||||
var token = args[args.length - 1]
|
var token = args[args.length - 1]
|
||||||
var complete = tabCompleter(sender, command, Java.from(args)) || []
|
var complete = tabCompleter(sender, command, Java.from(args)) || []
|
||||||
return this.copyPartialMatches(complete, token)
|
let result = this.copyPartialMatches(complete, token)
|
||||||
} catch (ex) {
|
let cost = Date.now() - time
|
||||||
console.i18n("ms.api.command.tab.completer.error", { player: sender.name, plugin: plugin.description.name, command, args: Java.from(args).join(' '), ex })
|
if (cost > global.ScriptSlowExecuteTime) {
|
||||||
|
console.i18n("ms.api.command.tab.completer.slow", {
|
||||||
|
player: sender.name,
|
||||||
|
plugin: plugin.description.name,
|
||||||
|
command,
|
||||||
|
args: Java.from(args).join(' '),
|
||||||
|
cost
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
} catch (ex: any) {
|
||||||
|
console.i18n("ms.api.command.tab.completer.error", {
|
||||||
|
player: sender.name,
|
||||||
|
plugin: plugin.description.name,
|
||||||
|
command,
|
||||||
|
args: Java.from(args).join(' '),
|
||||||
|
ex
|
||||||
|
})
|
||||||
console.ex(ex)
|
console.ex(ex)
|
||||||
console.sender(sender, [i18n.translate("ms.api.command.tab.completer.error", { player: sender.name, plugin: plugin.description.name, command, args: Java.from(args).join(' '), ex }), ...console.stack(ex)])
|
if (sender.name != 'CONSOLE') {
|
||||||
|
console.sender(sender, [
|
||||||
|
i18n.translate("ms.api.command.tab.completer.error", {
|
||||||
|
player: sender.name,
|
||||||
|
plugin: plugin.description.name,
|
||||||
|
command,
|
||||||
|
args: Java.from(args).join(' '),
|
||||||
|
ex
|
||||||
|
}),
|
||||||
|
...console.stack(ex)
|
||||||
|
])
|
||||||
|
}
|
||||||
return []
|
return []
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import * as base64 from 'base64-js'
|
|||||||
const Arrays = Java.type('java.util.Arrays')
|
const Arrays = Java.type('java.util.Arrays')
|
||||||
const Level = Java.type('java.util.logging.Level')
|
const Level = Java.type('java.util.logging.Level')
|
||||||
const Paths = Java.type('java.nio.file.Paths')
|
const Paths = Java.type('java.nio.file.Paths')
|
||||||
const ignoreLogPrefix = ['java.', 'javax.', 'sun.', 'net.minecraft.', 'org.bukkit.', 'jdk.nashorn.', 'io.netty.', 'org.spongepowered.', 'org.apache', 'org.springframework']
|
const ignoreLogPrefix = ['java.', 'javax.', 'sun.', 'net.minecraft.', 'org.bukkit.', 'jdk.nashorn.', 'org.openjdk.nashorn', 'io.netty.', 'org.spongepowered.', 'org.apache', 'org.springframework']
|
||||||
|
|
||||||
enum LogLevel {
|
enum LogLevel {
|
||||||
ALL,
|
ALL,
|
||||||
@@ -19,7 +19,8 @@ enum LogLevel {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export class MiaoScriptConsole implements Console {
|
export class MiaoScriptConsole implements Console {
|
||||||
Console: NodeJS.ConsoleConstructor
|
Console: any
|
||||||
|
memory: any
|
||||||
|
|
||||||
private static sourceMaps: { [key: string]: SourceMapBuilder } = {}
|
private static sourceMaps: { [key: string]: SourceMapBuilder } = {}
|
||||||
private static sourceFileMaps: { [key: string]: string } = {}
|
private static sourceFileMaps: { [key: string]: string } = {}
|
||||||
@@ -27,7 +28,8 @@ export class MiaoScriptConsole implements Console {
|
|||||||
private _level: LogLevel = LogLevel.INFO
|
private _level: LogLevel = LogLevel.INFO
|
||||||
|
|
||||||
protected logger: any
|
protected logger: any
|
||||||
protected prefix: string = '§6[§bMiaoScript§6]§r '
|
|
||||||
|
public prefix: string = '§6[§bMiaoScript§6]§r '
|
||||||
|
|
||||||
constructor(name?: string) {
|
constructor(name?: string) {
|
||||||
this.name = name
|
this.name = name
|
||||||
@@ -47,10 +49,10 @@ export class MiaoScriptConsole implements Console {
|
|||||||
set name(name: string) {
|
set name(name: string) {
|
||||||
if (name) {
|
if (name) {
|
||||||
this._name = `[${name}] `
|
this._name = `[${name}] `
|
||||||
// noinspection JSUnusedGlobalSymbols
|
|
||||||
this.prefix = `§6[§cMS§6][§b${name}§6]§r `
|
this.prefix = `§6[§cMS§6][§b${name}§6]§r `
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
log(...args: any[]): void {
|
log(...args: any[]): void {
|
||||||
this.logger.info(this.name + args.join(' '))
|
this.logger.info(this.name + args.join(' '))
|
||||||
}
|
}
|
||||||
@@ -90,7 +92,7 @@ export class MiaoScriptConsole implements Console {
|
|||||||
ex(ex: Error) {
|
ex(ex: Error) {
|
||||||
this.stack(ex).forEach(line => this.console(line))
|
this.stack(ex).forEach(line => this.console(line))
|
||||||
}
|
}
|
||||||
readSourceMap(fileName: string, lineNumber: number) {
|
readSourceMap(fileName: string, lineNumber: any) {
|
||||||
try {
|
try {
|
||||||
if (fileName.endsWith('js')) {
|
if (fileName.endsWith('js')) {
|
||||||
if (MiaoScriptConsole.sourceMaps[fileName] === undefined) {
|
if (MiaoScriptConsole.sourceMaps[fileName] === undefined) {
|
||||||
@@ -103,7 +105,7 @@ export class MiaoScriptConsole implements Console {
|
|||||||
let sourceMappingURL = lastLine.split('sourceMappingURL=', 2)[1]
|
let sourceMappingURL = lastLine.split('sourceMappingURL=', 2)[1]
|
||||||
if (sourceMappingURL.startsWith('data:application/json;base64,')) {
|
if (sourceMappingURL.startsWith('data:application/json;base64,')) {
|
||||||
sourceContent = String.fromCharCode(...Array.from(base64.toByteArray(sourceMappingURL.split(',', 2)[1])))
|
sourceContent = String.fromCharCode(...Array.from(base64.toByteArray(sourceMappingURL.split(',', 2)[1])))
|
||||||
} else if (sourceMappingURL.startsWith('http')) {
|
} else if (sourceMappingURL.startsWith('http://') || sourceMappingURL.startsWith('https://')) {
|
||||||
// TODO
|
// TODO
|
||||||
} else {
|
} else {
|
||||||
let file = Paths.get(Paths.get(fileName, '..', sourceMappingURL).toFile().getCanonicalPath()).toFile()
|
let file = Paths.get(Paths.get(fileName, '..', sourceMappingURL).toFile().getCanonicalPath()).toFile()
|
||||||
@@ -121,7 +123,7 @@ export class MiaoScriptConsole implements Console {
|
|||||||
if (sourceMapping && lineNumber != sourceMapping.mapping.sourceLine) { lineNumber = sourceMapping.mapping.sourceLine }
|
if (sourceMapping && lineNumber != sourceMapping.mapping.sourceLine) { lineNumber = sourceMapping.mapping.sourceLine }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error: any) {
|
||||||
console.debug('search source map', fileName, 'line', lineNumber, 'error:', error)
|
console.debug('search source map', fileName, 'line', lineNumber, 'error:', error)
|
||||||
if (global.debug) {
|
if (global.debug) {
|
||||||
console.ex(error)
|
console.ex(error)
|
||||||
@@ -133,6 +135,7 @@ export class MiaoScriptConsole implements Console {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
stack(ex: Error, color: boolean = true): string[] {
|
stack(ex: Error, color: boolean = true): string[] {
|
||||||
|
if (!ex) return []
|
||||||
let stack = ex.getStackTrace()
|
let stack = ex.getStackTrace()
|
||||||
let cache = [(color ? '§c' : '') + ex]
|
let cache = [(color ? '§c' : '') + ex]
|
||||||
//@ts-ignore
|
//@ts-ignore
|
||||||
@@ -152,14 +155,17 @@ export class MiaoScriptConsole implements Console {
|
|||||||
} else {
|
} else {
|
||||||
let className = trace.className
|
let className = trace.className
|
||||||
var fileName = trace.fileName as string
|
var fileName = trace.fileName as string
|
||||||
if (className.startsWith('jdk.nashorn.internal.scripts')) {
|
var lineNumber = trace.lineNumber
|
||||||
|
if (className.startsWith('jdk.nashorn.internal.scripts') || className.startsWith('org.openjdk.nashorn.internal.scripts')) {
|
||||||
className = className.substr(className.lastIndexOf('$') + 1)
|
className = className.substr(className.lastIndexOf('$') + 1)
|
||||||
var { fileName, lineNumber } = this.readSourceMap(trace.fileName, trace.lineNumber)
|
var { fileName, lineNumber } = this.readSourceMap(fileName, lineNumber)
|
||||||
if (fileName.startsWith(root)) { fileName = fileName.split(root)[1] }
|
if (fileName.startsWith(root)) { fileName = fileName.split(root)[1] }
|
||||||
} else {
|
} else {
|
||||||
for (let prefix in ignoreLogPrefix) {
|
if (!global.debug) {
|
||||||
if (className.startsWith(ignoreLogPrefix[prefix])) {
|
for (let prefix in ignoreLogPrefix) {
|
||||||
return
|
if (className.startsWith(ignoreLogPrefix[prefix])) {
|
||||||
|
return
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -184,12 +190,15 @@ export class MiaoScriptConsole implements Console {
|
|||||||
countReset(label?: string): void {
|
countReset(label?: string): void {
|
||||||
throw new Error("Method not implemented.")
|
throw new Error("Method not implemented.")
|
||||||
}
|
}
|
||||||
dir(obj: any, options?: NodeJS.InspectOptions): void {
|
dir(obj: any, options?: any): void {
|
||||||
throw new Error("Method not implemented.")
|
throw new Error("Method not implemented.")
|
||||||
}
|
}
|
||||||
dirxml(...data: any[]): void {
|
dirxml(...data: any[]): void {
|
||||||
throw new Error("Method not implemented.")
|
throw new Error("Method not implemented.")
|
||||||
}
|
}
|
||||||
|
exception(message?: string, ...optionalParams: any[]): void {
|
||||||
|
throw new Error('Method not implemented.')
|
||||||
|
}
|
||||||
group(...label: any[]): void {
|
group(...label: any[]): void {
|
||||||
throw new Error("Method not implemented.")
|
throw new Error("Method not implemented.")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,14 @@
|
|||||||
export namespace constants {
|
export namespace constants {
|
||||||
|
export namespace ServiceIdentifier {
|
||||||
|
/**
|
||||||
|
* Runtime Server NettyPipeline
|
||||||
|
*/
|
||||||
|
export const NettyPipeline = Symbol("NettyPipeline")
|
||||||
|
/**
|
||||||
|
* Runtime Server RootLogger
|
||||||
|
*/
|
||||||
|
export const RootLogger = Symbol("RootLogger")
|
||||||
|
}
|
||||||
export namespace Reflect {
|
export namespace Reflect {
|
||||||
export const Method = {
|
export const Method = {
|
||||||
getServerConnection: [/*spigot 1.8.8*/'aq',/*spigot 1.12.2*/ 'an', /*spigot 1.14.4+*/'getServerConnection', /*catserver 1.12.2*/'func_147137_ag']
|
getServerConnection: [/*spigot 1.8.8*/'aq',/*spigot 1.12.2*/ 'an', /*spigot 1.14.4+*/'getServerConnection', /*catserver 1.12.2*/'func_147137_ag']
|
||||||
|
|||||||
@@ -57,7 +57,7 @@ export namespace event {
|
|||||||
this.mapEvent[simpleName] = clazz
|
this.mapEvent[simpleName] = clazz
|
||||||
count++
|
count++
|
||||||
}
|
}
|
||||||
} catch (ex) {
|
} catch (ex: any) {
|
||||||
//ignore already loaded class
|
//ignore already loaded class
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -82,9 +82,9 @@ export namespace event {
|
|||||||
let eventCls = this.mapEvent[event.toLowerCase()] || this.mapEvent[event.toLowerCase() + 'event']
|
let eventCls = this.mapEvent[event.toLowerCase()] || this.mapEvent[event.toLowerCase() + 'event']
|
||||||
if (!eventCls) {
|
if (!eventCls) {
|
||||||
try {
|
try {
|
||||||
eventCls = base.getClass(eventCls)
|
eventCls = base.getClass(event)
|
||||||
this.mapEvent[event] = eventCls
|
this.mapEvent[event] = eventCls
|
||||||
} catch (ex) {
|
} catch (ex: any) {
|
||||||
console.i18n("ms.api.event.not.found", { name, event })
|
console.i18n("ms.api.event.not.found", { name, event })
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -100,11 +100,11 @@ export namespace event {
|
|||||||
let time = Date.now()
|
let time = Date.now()
|
||||||
exec(event)
|
exec(event)
|
||||||
let cost = Date.now() - time
|
let cost = Date.now() - time
|
||||||
if (cost > 20) {
|
if (cost > global.ScriptSlowExecuteTime) {
|
||||||
console.i18n("ms.api.event.execute.slow", { name, event: this.class2Name(eventCls), cost })
|
console.i18n("ms.api.event.execute.slow", { name, event: this.class2Name(eventCls), cost })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (ex) {
|
} catch (ex: any) {
|
||||||
console.i18n("ms.api.event.execute.error", { name, event: this.class2Name(eventCls), ex })
|
console.i18n("ms.api.event.execute.error", { name, event: this.class2Name(eventCls), ex })
|
||||||
console.ex(ex)
|
console.ex(ex)
|
||||||
}
|
}
|
||||||
@@ -133,7 +133,12 @@ export namespace event {
|
|||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
let executor = exec.name || exec.executor || '[anonymous]'
|
let executor = exec.name || exec.executor || '[anonymous]'
|
||||||
// noinspection JSUnusedGlobalSymbols
|
// noinspection JSUnusedGlobalSymbols
|
||||||
var listener = this.register(eventCls, this.execute(name, exec, eventCls), priority, ignoreCancel)
|
var listener = this.register(
|
||||||
|
eventCls,
|
||||||
|
this.execute(name, exec, eventCls),
|
||||||
|
priority,
|
||||||
|
ignoreCancel
|
||||||
|
)
|
||||||
var listenerMap = this.listenerMap
|
var listenerMap = this.listenerMap
|
||||||
// add to cache Be used for close plugin to close event
|
// add to cache Be used for close plugin to close event
|
||||||
if (!listenerMap[name]) listenerMap[name] = []
|
if (!listenerMap[name]) listenerMap[name] = []
|
||||||
@@ -141,11 +146,21 @@ export namespace event {
|
|||||||
if (off['offed']) return
|
if (off['offed']) return
|
||||||
off['offed'] = true
|
off['offed'] = true
|
||||||
this.unregister(eventCls, listener)
|
this.unregister(eventCls, listener)
|
||||||
console.debug(i18n.translate("ms.api.event.unregister", { name, event: this.class2Name(eventCls), exec: executor }))
|
console.debug(i18n.translate("ms.api.event.unregister", {
|
||||||
|
name,
|
||||||
|
event: this.class2Name(eventCls),
|
||||||
|
exec: executor
|
||||||
|
}))
|
||||||
}
|
}
|
||||||
listenerMap[name].push(off)
|
listenerMap[name].push(off)
|
||||||
// noinspection JSUnresolvedVariable
|
// noinspection JSUnresolvedVariable
|
||||||
console.debug(i18n.translate("ms.api.event.register", { name, event: this.class2Name(eventCls), exec: executor }))
|
console.debug(i18n.translate("ms.api.event.register", {
|
||||||
|
name,
|
||||||
|
event: this.class2Name(eventCls),
|
||||||
|
exec: executor,
|
||||||
|
priority,
|
||||||
|
ignore: ignoreCancel
|
||||||
|
}))
|
||||||
return off
|
return off
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,11 +1,16 @@
|
|||||||
import "@ccms/nashorn"
|
import "@ccms/nashorn"
|
||||||
|
|
||||||
|
export * from './web'
|
||||||
|
export * from './amqp'
|
||||||
export * from './chat'
|
export * from './chat'
|
||||||
export * from './task'
|
export * from './task'
|
||||||
export * from './event'
|
export * from './event'
|
||||||
export * from './proxy'
|
export * from './proxy'
|
||||||
|
export * from './plugin'
|
||||||
|
export * from './server'
|
||||||
export * from './console'
|
export * from './console'
|
||||||
export * from './channel'
|
export * from './channel'
|
||||||
export * from './command'
|
export * from './command'
|
||||||
|
export * from './database'
|
||||||
|
export * from './particle'
|
||||||
export * from './constants'
|
export * from './constants'
|
||||||
export * from './interfaces'
|
|
||||||
|
|||||||
@@ -1,5 +0,0 @@
|
|||||||
export * from './web'
|
|
||||||
export * from './amqp'
|
|
||||||
export * from './plugin'
|
|
||||||
export * from './server'
|
|
||||||
export * from './database'
|
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
export interface NativePluginManager {
|
|
||||||
load(name: string): boolean;
|
|
||||||
unload(name: string): boolean;
|
|
||||||
reload(name: string): boolean;
|
|
||||||
delete(name: string): boolean;
|
|
||||||
}
|
|
||||||
494
packages/api/src/particle.ts
Normal file
494
packages/api/src/particle.ts
Normal file
@@ -0,0 +1,494 @@
|
|||||||
|
import { Autowired, injectable } from '@ccms/container'
|
||||||
|
|
||||||
|
import { task, plugin } from './index'
|
||||||
|
|
||||||
|
const UUID = Java.type('java.util.UUID')
|
||||||
|
const Math = Java.type('java.lang.Math')
|
||||||
|
|
||||||
|
export namespace particle {
|
||||||
|
/**
|
||||||
|
* 表示一个特效对象
|
||||||
|
*
|
||||||
|
* @author Zoyn
|
||||||
|
*/
|
||||||
|
export abstract class Particle {
|
||||||
|
private spawner: ParticleSpawner
|
||||||
|
private readonly uuid: string
|
||||||
|
|
||||||
|
private particle: any /* Particle */
|
||||||
|
private count: number = 1;
|
||||||
|
private offsetX: number = 0;
|
||||||
|
private offsetY: number = 0;
|
||||||
|
private offsetZ: number = 0;
|
||||||
|
private extra: number = 0;
|
||||||
|
private data: Object = null;
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
this.uuid = UUID.randomUUID().toString()
|
||||||
|
}
|
||||||
|
abstract show(location: any)
|
||||||
|
|
||||||
|
getUUID() {
|
||||||
|
return this.uuid
|
||||||
|
}
|
||||||
|
|
||||||
|
getSpawner() {
|
||||||
|
return this.spawner
|
||||||
|
}
|
||||||
|
|
||||||
|
setSpawner(spawner: ParticleSpawner) {
|
||||||
|
this.spawner = spawner
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
getParticle() {
|
||||||
|
return this.particle
|
||||||
|
}
|
||||||
|
|
||||||
|
setParticle(particle: any, data: any = null) {
|
||||||
|
this.particle = particle
|
||||||
|
this.data = data
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
getCount() {
|
||||||
|
return this.count
|
||||||
|
}
|
||||||
|
|
||||||
|
setCount(count: number) {
|
||||||
|
this.count = count
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
getOffsetX() {
|
||||||
|
return this.offsetX
|
||||||
|
}
|
||||||
|
|
||||||
|
setOffsetX(offsetX: number) {
|
||||||
|
this.offsetX = offsetX
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
getOffsetY() {
|
||||||
|
return this.offsetY
|
||||||
|
}
|
||||||
|
|
||||||
|
setOffsetY(offsetY: number) {
|
||||||
|
this.offsetY = offsetY
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
getOffsetZ() {
|
||||||
|
return this.offsetZ
|
||||||
|
}
|
||||||
|
|
||||||
|
setOffsetZ(offsetZ: number) {
|
||||||
|
this.offsetZ = offsetZ
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
getExtra() {
|
||||||
|
return this.extra
|
||||||
|
}
|
||||||
|
|
||||||
|
setExtra(extra: number) {
|
||||||
|
this.extra = extra
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
getData() {
|
||||||
|
return this.data
|
||||||
|
}
|
||||||
|
|
||||||
|
setData(data) {
|
||||||
|
this.data = data
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 通过给定一个坐标就可以使用已经指定的参数来播放粒子
|
||||||
|
*
|
||||||
|
* @param location 坐标
|
||||||
|
*/
|
||||||
|
spawn(location: any) {
|
||||||
|
if (!this.spawner) throw new Error(`particle ${this.uuid} not set spawner can't spawn!`)
|
||||||
|
this.spawner.spawn(location, this)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* 表示一条线
|
||||||
|
*
|
||||||
|
* @author Zoyn
|
||||||
|
*/
|
||||||
|
export class Line extends Particle {
|
||||||
|
private vector: any
|
||||||
|
private start: any
|
||||||
|
private end: any
|
||||||
|
/**
|
||||||
|
* 步长
|
||||||
|
*/
|
||||||
|
private step: number
|
||||||
|
/**
|
||||||
|
* 向量长度
|
||||||
|
*/
|
||||||
|
private length: number
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 构造一条线
|
||||||
|
*
|
||||||
|
* @param start 线的起点
|
||||||
|
* @param end 线的终点
|
||||||
|
*/
|
||||||
|
constructor(start: any, end: any)
|
||||||
|
/**
|
||||||
|
* 构造一条线
|
||||||
|
*
|
||||||
|
* @param start 线的起点
|
||||||
|
* @param end 线的终点
|
||||||
|
* @param step 每个粒子之间的间隔 (也即步长)
|
||||||
|
*/
|
||||||
|
constructor(start: any, end: any, step: number = 0.1) {
|
||||||
|
super()
|
||||||
|
this.start = start
|
||||||
|
this.end = end
|
||||||
|
this.step = step
|
||||||
|
// 对向量进行重置
|
||||||
|
this.resetVector()
|
||||||
|
}
|
||||||
|
|
||||||
|
show() {
|
||||||
|
for (let i = 0; i < this.length; i += this.step) {
|
||||||
|
let vectorTemp = this.vector.clone().multiply(i)
|
||||||
|
this.spawn(this.start.clone().add(vectorTemp))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取线的起始坐标
|
||||||
|
*
|
||||||
|
* @return {@link Location}
|
||||||
|
*/
|
||||||
|
getStart() {
|
||||||
|
return this.start
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 利用给定的坐标设置线的起始坐标
|
||||||
|
*
|
||||||
|
* @param start 起始坐标
|
||||||
|
* @return {@link Line}
|
||||||
|
*/
|
||||||
|
setStart(start) {
|
||||||
|
this.start = start
|
||||||
|
this.resetVector()
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取线的终点坐标
|
||||||
|
*
|
||||||
|
* @return {@link Location}
|
||||||
|
*/
|
||||||
|
getEnd() {
|
||||||
|
return this.end
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 利用给定的坐标设置线的终点坐标
|
||||||
|
*
|
||||||
|
* @param end 终点
|
||||||
|
* @return {@link Line}
|
||||||
|
*/
|
||||||
|
setEnd(end) {
|
||||||
|
this.end = end
|
||||||
|
this.resetVector()
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取每个粒子之间的间隔
|
||||||
|
*
|
||||||
|
* @return 也就是循环的步长
|
||||||
|
*/
|
||||||
|
getStep() {
|
||||||
|
return this.step
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 设置每个粒子之间的间隔
|
||||||
|
*
|
||||||
|
* @param step 间隔
|
||||||
|
* @return {@link Line}
|
||||||
|
*/
|
||||||
|
setStep(step) {
|
||||||
|
this.step = step
|
||||||
|
this.resetVector()
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 手动重设线的向量
|
||||||
|
*/
|
||||||
|
resetVector() {
|
||||||
|
this.vector = this.end.clone().subtract(this.start).toVector()
|
||||||
|
this.length = this.vector.length()
|
||||||
|
this.vector.normalize()
|
||||||
|
}
|
||||||
|
|
||||||
|
public static buildLine(locA: any, locB: any, step: number, particle: any) {
|
||||||
|
let vectorAB = locB.clone().subtract(locA).toVector()
|
||||||
|
let vectorLength = vectorAB.length()
|
||||||
|
vectorAB.normalize()
|
||||||
|
for (let i = 0; i < vectorLength; i += step) {
|
||||||
|
ParticleManager.globalSpawner.spawn(locA.clone().add(vectorAB.clone().multiply(i)), particle)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* 表示一个弧
|
||||||
|
*
|
||||||
|
* @author Zoyn
|
||||||
|
*/
|
||||||
|
export class Arc extends Particle {
|
||||||
|
private angle: number
|
||||||
|
private radius: number
|
||||||
|
private step: number
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 构造一个弧
|
||||||
|
*
|
||||||
|
* @param origin 弧所在的圆的圆点
|
||||||
|
* @param angle 弧所占的角度
|
||||||
|
* @param radius 弧所在的圆的半径
|
||||||
|
* @param step 每个粒子的间隔(也即步长)
|
||||||
|
*/
|
||||||
|
constructor(angle: number = 30, radius: number = 1, step: number = 1) {
|
||||||
|
super()
|
||||||
|
this.angle = angle
|
||||||
|
this.radius = radius
|
||||||
|
this.step = step
|
||||||
|
}
|
||||||
|
|
||||||
|
show(location: any) {
|
||||||
|
for (let i = 0; i < this.angle; i += this.step) {
|
||||||
|
let radians: number = Math.toRadians(i)
|
||||||
|
let x: number = this.radius * Math.cos(radians)
|
||||||
|
let z: number = this.radius * Math.sin(radians)
|
||||||
|
|
||||||
|
super.spawn(location.clone().add(x, 0, z))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
getAngle(): number {
|
||||||
|
return this.angle
|
||||||
|
}
|
||||||
|
|
||||||
|
setAngle(angle: number): Arc {
|
||||||
|
this.angle = angle
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
getRadius(): number {
|
||||||
|
return this.radius
|
||||||
|
}
|
||||||
|
|
||||||
|
setRadius(radius: number): Arc {
|
||||||
|
this.radius = radius
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
getStep(): number {
|
||||||
|
return this.step
|
||||||
|
}
|
||||||
|
|
||||||
|
setStep(step: number): Arc {
|
||||||
|
this.step = step
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* 表示一个圆
|
||||||
|
*
|
||||||
|
* @author Zoyn
|
||||||
|
*/
|
||||||
|
export class Circle extends Arc {
|
||||||
|
constructor(radius: number)
|
||||||
|
constructor(radius: number, step: number)
|
||||||
|
/**
|
||||||
|
* 构造一个圆
|
||||||
|
*
|
||||||
|
* @param origin 圆的圆点
|
||||||
|
* @param radius 圆的半径
|
||||||
|
* @param step 每个粒子的间隔(也即步长)
|
||||||
|
* @param period 特效周期(如果需要可以使用)
|
||||||
|
*/
|
||||||
|
constructor(radius: number = 1, step: number = 1) {
|
||||||
|
// Circle只需要控制这个fullArc就可以满足所有的要求
|
||||||
|
super(360, radius, step)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const AtomicInteger = Java.type("java.util.concurrent.atomic.AtomicInteger")
|
||||||
|
|
||||||
|
@injectable()
|
||||||
|
export abstract class ParticleManager {
|
||||||
|
public static globalSpawner: ParticleSpawner = undefined
|
||||||
|
@Autowired()
|
||||||
|
private taskManager: task.TaskManager
|
||||||
|
|
||||||
|
protected taskId: java.util.concurrent.atomic.AtomicInteger
|
||||||
|
protected cacheTasks = new Map<string, ParticleTask>()
|
||||||
|
protected pluginCacheTasks = new Map<string, Map<number, ParticleTask>>()
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
this.taskId = new AtomicInteger(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获得自增的任务ID
|
||||||
|
*/
|
||||||
|
public nextId() {
|
||||||
|
return this.taskId.incrementAndGet()
|
||||||
|
}
|
||||||
|
|
||||||
|
public getTaskManager() {
|
||||||
|
return this.taskManager
|
||||||
|
}
|
||||||
|
|
||||||
|
public create(particle: Particle, plugin?: plugin.Plugin) {
|
||||||
|
let uuid = particle.getUUID()
|
||||||
|
if (this.cacheTasks.has(uuid)) {
|
||||||
|
return this.cacheTasks.get(uuid)
|
||||||
|
}
|
||||||
|
let task = this.create0(plugin, particle)
|
||||||
|
this.cacheTasks.set(uuid, task)
|
||||||
|
if (plugin) {
|
||||||
|
if (!this.pluginCacheTasks.has(plugin.description.name)) {
|
||||||
|
this.pluginCacheTasks.set(plugin.description.name, new Map())
|
||||||
|
}
|
||||||
|
this.pluginCacheTasks.get(plugin.description.name).set(task.getTaskId(), task)
|
||||||
|
}
|
||||||
|
return task
|
||||||
|
}
|
||||||
|
|
||||||
|
public cancel(particle: Particle) {
|
||||||
|
let uuid = particle.getUUID()
|
||||||
|
if (this.cacheTasks.has(uuid)) {
|
||||||
|
this.cacheTasks.get(uuid).cancel()
|
||||||
|
this.cacheTasks.delete(uuid)
|
||||||
|
} else {
|
||||||
|
throw new Error(`particle ${uuid} not found!`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
disable(plugin: plugin.Plugin) {
|
||||||
|
if (this.pluginCacheTasks.has(plugin.description.name)) {
|
||||||
|
this.pluginCacheTasks
|
||||||
|
.get(plugin.description.name)
|
||||||
|
.forEach((task) => task.cancel())
|
||||||
|
this.pluginCacheTasks.delete(plugin.description.name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
protected create0(owner: plugin.Plugin, particle: Particle): ParticleTask {
|
||||||
|
particle.setSpawner(this.getGlobalSpawner())
|
||||||
|
return new ParticleTask(owner, particle, this)
|
||||||
|
}
|
||||||
|
protected abstract getGlobalSpawner(): ParticleSpawner
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ParticleTask {
|
||||||
|
|
||||||
|
private particle: Particle
|
||||||
|
private isAsync: boolean = false
|
||||||
|
private interval: number = 0
|
||||||
|
private _location: any
|
||||||
|
private _follow: any
|
||||||
|
|
||||||
|
private owner: plugin.Plugin
|
||||||
|
private taskId: number
|
||||||
|
private task: task.Task
|
||||||
|
private taskManager: task.TaskManager
|
||||||
|
protected particleManager: ParticleManager
|
||||||
|
|
||||||
|
constructor(owner: plugin.Plugin, particle: Particle, particleManager: ParticleManager) {
|
||||||
|
this.owner = owner
|
||||||
|
this.taskId = particleManager.nextId()
|
||||||
|
this.particle = particle
|
||||||
|
this.taskManager = particleManager.getTaskManager()
|
||||||
|
this.particleManager = particleManager
|
||||||
|
}
|
||||||
|
|
||||||
|
getOwner() {
|
||||||
|
return this.task.getOwner()
|
||||||
|
}
|
||||||
|
|
||||||
|
getTaskId() {
|
||||||
|
return this.taskId
|
||||||
|
}
|
||||||
|
|
||||||
|
getParticle() {
|
||||||
|
return this.particle
|
||||||
|
}
|
||||||
|
|
||||||
|
async(isAsync: boolean = true) {
|
||||||
|
this.isAsync = isAsync
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
timer(tick: number) {
|
||||||
|
this.interval = tick
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
follow(entity: { getLocation: () => any }) {
|
||||||
|
this._follow = entity
|
||||||
|
this._location = undefined
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
location(location: any) {
|
||||||
|
this._location = location
|
||||||
|
this._follow = undefined
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
submit() {
|
||||||
|
this.cancel()
|
||||||
|
if (this._follow && !this.interval) throw new Error(`enable follow entity but interval is ${this.interval}!`)
|
||||||
|
this.taskManager.create(() => {
|
||||||
|
this.task = this.taskManager
|
||||||
|
.create(() => {
|
||||||
|
try {
|
||||||
|
if (this._follow) {
|
||||||
|
if (!this._follow.isOnline()) return this.cancel()
|
||||||
|
this.particle.show(this._follow.getLocation().clone().add(0, 1, 0))
|
||||||
|
} else if (this._location) {
|
||||||
|
this.particle.show(this._location)
|
||||||
|
} else {
|
||||||
|
console.warn(`ParticleTask ${this.taskId} particle ${this.particle.getUUID()} cancel because entity and location both undefined!`)
|
||||||
|
this.task.cancel()
|
||||||
|
}
|
||||||
|
} catch (error: any) {
|
||||||
|
console.error(`§6插件 §a${this.owner.description.name} §c播放粒子发送异常 §4粒子播放任务已终止!`)
|
||||||
|
console.ex(error)
|
||||||
|
this.cancel()
|
||||||
|
}
|
||||||
|
}, this.owner)
|
||||||
|
.async(this.isAsync)
|
||||||
|
.timer(this.interval)
|
||||||
|
.submit()
|
||||||
|
}, this.owner).later(2).submit()
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
cancel() {
|
||||||
|
if (this.task != null) {
|
||||||
|
this.task.cancel()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export abstract class ParticleSpawner {
|
||||||
|
abstract spawnParticle(location: any, particle: any, count: number)
|
||||||
|
abstract spawn(location: any, particle: Particle)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -20,7 +20,7 @@ export namespace plugin {
|
|||||||
export abstract class PluginManager {
|
export abstract class PluginManager {
|
||||||
abstract scan(folder: string): void
|
abstract scan(folder: string): void
|
||||||
abstract build(): void
|
abstract build(): void
|
||||||
abstract loadFromFile(file: string, scanner?: plugin.PluginScanner): Plugin
|
abstract loadFromFile(file: string, ext?: any): Plugin
|
||||||
abstract load(...args: any[]): void
|
abstract load(...args: any[]): void
|
||||||
abstract enable(...args: any[]): void
|
abstract enable(...args: any[]): void
|
||||||
abstract disable(...args: any[]): void
|
abstract disable(...args: any[]): void
|
||||||
@@ -78,7 +78,7 @@ export namespace plugin {
|
|||||||
scan(target: any): PluginLoadMetadata[]
|
scan(target: any): PluginLoadMetadata[]
|
||||||
/**
|
/**
|
||||||
* 读取插件 返回插件加载元信息
|
* 读取插件 返回插件加载元信息
|
||||||
* @param target
|
* @param target
|
||||||
*/
|
*/
|
||||||
read(target: any): PluginLoadMetadata
|
read(target: any): PluginLoadMetadata
|
||||||
/**
|
/**
|
||||||
@@ -162,6 +162,14 @@ export namespace plugin {
|
|||||||
* 插件作者 不填默认为 Unknow
|
* 插件作者 不填默认为 Unknow
|
||||||
*/
|
*/
|
||||||
author?: string | string[]
|
author?: string | string[]
|
||||||
|
/**
|
||||||
|
* 脚本依赖
|
||||||
|
*/
|
||||||
|
depends?: string[]
|
||||||
|
/**
|
||||||
|
* 插件依赖
|
||||||
|
*/
|
||||||
|
nativeDepends?: string[]
|
||||||
/**
|
/**
|
||||||
* 插件源文件 必须指定为 __filename
|
* 插件源文件 必须指定为 __filename
|
||||||
*/
|
*/
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import { provideSingleton, Autowired } from '@ccms/container'
|
import { provideSingleton, Autowired, optional } from '@ccms/container'
|
||||||
import { channel } from './channel'
|
import { channel } from './channel'
|
||||||
|
|
||||||
export namespace proxy {
|
export namespace proxy {
|
||||||
@@ -44,7 +44,7 @@ export namespace proxy {
|
|||||||
* Get a list of players connected on a certain server, or on ALL the servers.
|
* Get a list of players connected on a certain server, or on ALL the servers.
|
||||||
* @param server count server
|
* @param server count server
|
||||||
* Response:
|
* Response:
|
||||||
* String server = in.readUTF(); // The name of the server you got the player list of, as given in args.
|
* String server = in.readUTF(); // The name of the server you got the player list of, as given in args.
|
||||||
* String[] playerList = in.readUTF().split(", ");
|
* String[] playerList = in.readUTF().split(", ");
|
||||||
*/
|
*/
|
||||||
playerList(server: string | "ALL") {
|
playerList(server: string | "ALL") {
|
||||||
@@ -98,7 +98,7 @@ export namespace proxy {
|
|||||||
return this.forward("ALL", channel, data)
|
return this.forward("ALL", channel, data)
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
* Send a custom plugin message to said server. This is one of the most useful channels ever.
|
* Send a custom plugin message to said server. This is one of the most useful channels ever.
|
||||||
* Remember, the sending and receiving server(s) need to have a player online.
|
* Remember, the sending and receiving server(s) need to have a player online.
|
||||||
* @param server reciver
|
* @param server reciver
|
||||||
* @param channel channelName
|
* @param channel channelName
|
||||||
@@ -112,7 +112,7 @@ export namespace proxy {
|
|||||||
return this.finalSend()
|
return this.finalSend()
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
* Send a custom plugin message to said server. This is one of the most useful channels ever.
|
* Send a custom plugin message to said server. This is one of the most useful channels ever.
|
||||||
* Remember, the sending and receiving server(s) need to have a player online.
|
* Remember, the sending and receiving server(s) need to have a player online.
|
||||||
* @param server reciver
|
* @param server reciver
|
||||||
* @param channel channelName
|
* @param channel channelName
|
||||||
@@ -147,6 +147,7 @@ export namespace proxy {
|
|||||||
}
|
}
|
||||||
@provideSingleton(BungeeCord)
|
@provideSingleton(BungeeCord)
|
||||||
export class BungeeCord {
|
export class BungeeCord {
|
||||||
|
@optional()
|
||||||
@Autowired()
|
@Autowired()
|
||||||
private channel: channel.Channel
|
private channel: channel.Channel
|
||||||
/**
|
/**
|
||||||
@@ -157,4 +158,4 @@ export namespace proxy {
|
|||||||
return new bungeecord.SubChannelBuilder(this.channel, player)
|
return new bungeecord.SubChannelBuilder(this.channel, player)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,7 @@
|
|||||||
import * as reflect from '@ccms/common/dist/reflect'
|
import * as reflect from '@ccms/common/dist/reflect'
|
||||||
import { injectable, inject } from '@ccms/container'
|
import { injectable, Autowired, ContainerInstance, Container, postConstruct } from '@ccms/container'
|
||||||
|
|
||||||
import { NativePluginManager } from './native_plugin'
|
import { constants } from './constants'
|
||||||
import { constants } from '../../constants'
|
|
||||||
|
|
||||||
export { NativePluginManager } from './native_plugin'
|
|
||||||
|
|
||||||
export namespace server {
|
export namespace server {
|
||||||
/**
|
/**
|
||||||
@@ -19,6 +16,43 @@ export namespace server {
|
|||||||
* Runtime Server Instance
|
* Runtime Server Instance
|
||||||
*/
|
*/
|
||||||
export const ServerInstance = Symbol("ServerInstance")
|
export const ServerInstance = Symbol("ServerInstance")
|
||||||
|
export interface NativePlugin {
|
||||||
|
name: string
|
||||||
|
version: string
|
||||||
|
authors?: string | string[]
|
||||||
|
enable: boolean
|
||||||
|
depends?: string[]
|
||||||
|
softDepends?: string[]
|
||||||
|
/**
|
||||||
|
* 插件本体
|
||||||
|
*/
|
||||||
|
origin: any
|
||||||
|
[key: string]: any
|
||||||
|
}
|
||||||
|
@injectable()
|
||||||
|
export abstract class NativePluginManager {
|
||||||
|
list(): NativePlugin[] {
|
||||||
|
throw new Error("Method not implemented.")
|
||||||
|
}
|
||||||
|
has(name: string): boolean {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
get(name: string): NativePlugin {
|
||||||
|
throw new Error("Method not implemented.")
|
||||||
|
}
|
||||||
|
enable(name: string): NativePlugin {
|
||||||
|
throw new Error("Method not implemented.")
|
||||||
|
}
|
||||||
|
disable(name: string): NativePlugin {
|
||||||
|
throw new Error("Method not implemented.")
|
||||||
|
}
|
||||||
|
reload(name: string): NativePlugin {
|
||||||
|
throw new Error("Method not implemented.")
|
||||||
|
}
|
||||||
|
delete(name: string): boolean {
|
||||||
|
throw new Error("Method not implemented.")
|
||||||
|
}
|
||||||
|
}
|
||||||
/**
|
/**
|
||||||
* MiaoScript Server
|
* MiaoScript Server
|
||||||
*/
|
*/
|
||||||
@@ -39,6 +73,12 @@ export namespace server {
|
|||||||
getService(service: string): any {
|
getService(service: string): any {
|
||||||
throw new Error("Method not implemented.")
|
throw new Error("Method not implemented.")
|
||||||
}
|
}
|
||||||
|
broadcast(message: string, permission: string) {
|
||||||
|
throw new Error("Method not implemented.")
|
||||||
|
}
|
||||||
|
broadcastMessage(message: string) {
|
||||||
|
throw new Error("Method not implemented.")
|
||||||
|
}
|
||||||
dispatchCommand(sender: string | any, command: string): boolean {
|
dispatchCommand(sender: string | any, command: string): boolean {
|
||||||
throw new Error("Method not implemented.")
|
throw new Error("Method not implemented.")
|
||||||
}
|
}
|
||||||
@@ -48,9 +88,6 @@ export namespace server {
|
|||||||
getPluginsFolder(): string {
|
getPluginsFolder(): string {
|
||||||
throw new Error("Method not implemented.")
|
throw new Error("Method not implemented.")
|
||||||
}
|
}
|
||||||
getNativePluginManager(): NativePluginManager {
|
|
||||||
throw new Error("Method not implemented.")
|
|
||||||
}
|
|
||||||
getDedicatedServer?(): any {
|
getDedicatedServer?(): any {
|
||||||
throw new Error("Method not implemented.")
|
throw new Error("Method not implemented.")
|
||||||
}
|
}
|
||||||
@@ -63,8 +100,9 @@ export namespace server {
|
|||||||
}
|
}
|
||||||
@injectable()
|
@injectable()
|
||||||
export class ServerChecker {
|
export class ServerChecker {
|
||||||
@inject(ServerType)
|
@Autowired(ServerType)
|
||||||
private serverType: string
|
private serverType: string
|
||||||
|
|
||||||
check(servers: string[]) {
|
check(servers: string[]) {
|
||||||
// Not set servers -> allow
|
// Not set servers -> allow
|
||||||
if (!servers || !servers.length) return true
|
if (!servers || !servers.length) return true
|
||||||
@@ -80,20 +118,23 @@ export namespace server {
|
|||||||
}
|
}
|
||||||
@injectable()
|
@injectable()
|
||||||
export abstract class ReflectServer extends server.Server {
|
export abstract class ReflectServer extends server.Server {
|
||||||
|
@Autowired(ContainerInstance)
|
||||||
|
private container: Container
|
||||||
|
|
||||||
protected pipeline: any
|
protected pipeline: any
|
||||||
protected rootLogger: any
|
protected rootLogger: any
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
super()
|
super()
|
||||||
this.reflect()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@postConstruct()
|
||||||
protected reflect() {
|
protected reflect() {
|
||||||
try {
|
try {
|
||||||
let consoleServer = this.getDedicatedServer()
|
let consoleServer = this.getDedicatedServer()
|
||||||
this.reflectPipeline(consoleServer)
|
this.reflectPipeline(consoleServer)
|
||||||
this.reflectRootLogger(consoleServer)
|
this.reflectRootLogger(consoleServer)
|
||||||
} catch (error) {
|
} catch (error: any) {
|
||||||
console.error('Error When Reflect MinecraftServer!', error)
|
console.error('Error When Reflect MinecraftServer!', error)
|
||||||
console.ex(error)
|
console.ex(error)
|
||||||
}
|
}
|
||||||
@@ -107,7 +148,11 @@ export namespace server {
|
|||||||
if (connection.class.name.indexOf('ServerConnection') !== -1
|
if (connection.class.name.indexOf('ServerConnection') !== -1
|
||||||
|| connection.class.name.indexOf('NetworkSystem') !== -1) { break }
|
|| connection.class.name.indexOf('NetworkSystem') !== -1) { break }
|
||||||
connection = undefined
|
connection = undefined
|
||||||
} catch (error) { }
|
} catch (error: any) {
|
||||||
|
if (global.debug) {
|
||||||
|
console.ex(error)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if (!connection) { console.error("Can't found ServerConnection!"); return }
|
if (!connection) { console.error("Can't found ServerConnection!"); return }
|
||||||
for (const field of constants.Reflect.Field.listeningChannels) {
|
for (const field of constants.Reflect.Field.listeningChannels) {
|
||||||
@@ -115,16 +160,30 @@ export namespace server {
|
|||||||
promise = reflect.on(connection).get(field).get().get(0)
|
promise = reflect.on(connection).get(field).get().get(0)
|
||||||
if (promise.class.name.indexOf('Promise') !== -1) { break }
|
if (promise.class.name.indexOf('Promise') !== -1) { break }
|
||||||
promise = undefined
|
promise = undefined
|
||||||
} catch (error) { }
|
} catch (error: any) {
|
||||||
|
if (global.debug) {
|
||||||
|
console.ex(error)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if (!promise) { console.error("Can't found listeningChannels!"); return }
|
if (!promise) { console.error("Can't found listeningChannels!"); return }
|
||||||
this.pipeline = reflect.on(promise).get('channel').get().pipeline()
|
this.pipeline = reflect.on(promise).get('channel').get().pipeline()
|
||||||
|
this.container.bind(constants.ServiceIdentifier.NettyPipeline).toConstantValue(this.pipeline)
|
||||||
}
|
}
|
||||||
protected reflectRootLogger(consoleServer: any) {
|
protected reflectRootLogger(consoleServer: any) {
|
||||||
try {
|
try {
|
||||||
this.rootLogger = reflect.on(consoleServer).get('LOGGER').get().parent
|
this.rootLogger = reflect.on(consoleServer).get('LOGGER').get().parent
|
||||||
} catch (error) {
|
} catch (error: any) {
|
||||||
try { this.rootLogger = reflect.on(consoleServer).get(0).get().parent } catch (error) { }
|
if (global.debug) {
|
||||||
|
console.ex(error)
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
this.rootLogger = reflect.on(consoleServer).get(0).get().parent
|
||||||
|
} catch (error: any) {
|
||||||
|
if (global.debug) {
|
||||||
|
console.ex(error)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if (this.rootLogger && this.rootLogger.class.name.indexOf('Logger') === -1) {
|
if (this.rootLogger && this.rootLogger.class.name.indexOf('Logger') === -1) {
|
||||||
console.error('Error Logger Class: ' + this.rootLogger.class.name)
|
console.error('Error Logger Class: ' + this.rootLogger.class.name)
|
||||||
@@ -135,6 +194,7 @@ export namespace server {
|
|||||||
this.rootLogger = this.rootLogger.parent
|
this.rootLogger = this.rootLogger.parent
|
||||||
}
|
}
|
||||||
if (!this.rootLogger) { console.error("Can't found rootLogger!") }
|
if (!this.rootLogger) { console.error("Can't found rootLogger!") }
|
||||||
|
this.container.bind(constants.ServiceIdentifier.RootLogger).toConstantValue(this.rootLogger)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,34 +1,66 @@
|
|||||||
import { plugin } from './index'
|
import { plugin } from './index'
|
||||||
import { injectable } from '@ccms/container'
|
import { injectable } from '@ccms/container'
|
||||||
|
|
||||||
|
const AtomicInteger = Java.type("java.util.concurrent.atomic.AtomicInteger")
|
||||||
|
|
||||||
export namespace task {
|
export namespace task {
|
||||||
@injectable()
|
@injectable()
|
||||||
export abstract class TaskManager {
|
export abstract class TaskManager {
|
||||||
protected cacheTasks = new Map<string, task.Task[]>()
|
protected taskId: java.util.concurrent.atomic.AtomicInteger
|
||||||
|
protected cacheTasks = new Map<number, task.Task>()
|
||||||
|
protected pluginCacheTasks = new Map<string, Map<number, task.Task>>()
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
this.taskId = new AtomicInteger(0)
|
||||||
|
process.on('task.finish', (task: task.Task) => {
|
||||||
|
let taskId = task.getTaskId()
|
||||||
|
this.cacheTasks.delete(taskId)
|
||||||
|
let ownerName = task.getOwner()?.description.name
|
||||||
|
if (ownerName && this.pluginCacheTasks.has(ownerName)) {
|
||||||
|
this.pluginCacheTasks.get(ownerName)?.delete(taskId)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
protected pluginCreate(plugin: plugin.Plugin, task: task.Task) {
|
protected pluginCreate(plugin: plugin.Plugin, task: task.Task) {
|
||||||
if (!this.cacheTasks.has(plugin.description.name)) {
|
if (!this.pluginCacheTasks.has(plugin.description.name)) {
|
||||||
this.cacheTasks.set(plugin.description.name, [])
|
this.pluginCacheTasks.set(plugin.description.name, new Map())
|
||||||
}
|
}
|
||||||
this.cacheTasks.get(plugin.description.name).push(task)
|
this.pluginCacheTasks.get(plugin.description.name).set(task.getTaskId(), task)
|
||||||
return task
|
return task
|
||||||
}
|
}
|
||||||
|
|
||||||
protected pluginDisable(plugin: plugin.Plugin) {
|
protected pluginDisable(plugin: plugin.Plugin) {
|
||||||
if (this.cacheTasks.has(plugin.description.name)) {
|
if (this.pluginCacheTasks.has(plugin.description.name)) {
|
||||||
this.cacheTasks.get(plugin.description.name).forEach(task => task.cancel())
|
this.pluginCacheTasks.get(plugin.description.name).forEach((task) => {
|
||||||
this.cacheTasks.delete(plugin.description.name)
|
task.cancel()
|
||||||
|
})
|
||||||
|
this.pluginCacheTasks.delete(plugin.description.name)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获得自增的任务ID
|
||||||
|
*/
|
||||||
|
protected nextId() {
|
||||||
|
return this.taskId.incrementAndGet()
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 创建任务
|
* 创建任务
|
||||||
* @param func 任务内容
|
* @param func 任务内容
|
||||||
*/
|
*/
|
||||||
create(func: Function, plugin?: plugin.Plugin): task.Task {
|
create(func: Function, plugin?: plugin.Plugin): task.Task {
|
||||||
if (Object.prototype.toString.call(func) !== "[object Function]") { throw TypeError('第一个参数 Task 必须为 function !') };
|
if (Object.prototype.toString.call(func) !== "[object Function]") { throw TypeError('第一个参数 Task 必须为 function !') };
|
||||||
let task = this.create0(func)
|
let task = this.create0(plugin, func, this.nextId())
|
||||||
|
this.cacheTasks.set(task.getTaskId(), task)
|
||||||
if (plugin) { return this.pluginCreate(plugin, task) }
|
if (plugin) { return this.pluginCreate(plugin, task) }
|
||||||
return task
|
return task
|
||||||
}
|
}
|
||||||
|
cancel(taskId: number) {
|
||||||
|
if (!this.cacheTasks.has(taskId)) { throw new Error(`Task ${taskId} not found!`) }
|
||||||
|
this.cacheTasks.get(taskId).cancel()
|
||||||
|
}
|
||||||
/**
|
/**
|
||||||
* 在主线程执行代码
|
* 在主线程执行代码
|
||||||
* @param func 执行内容
|
* @param func 执行内容
|
||||||
@@ -41,22 +73,33 @@ export namespace task {
|
|||||||
if (plugin) { return this.pluginDisable(plugin) }
|
if (plugin) { return this.pluginDisable(plugin) }
|
||||||
this.disable0()
|
this.disable0()
|
||||||
}
|
}
|
||||||
protected abstract create0(func: Function): task.Task
|
protected abstract create0(owner: plugin.Plugin, func: Function, id: number): task.Task
|
||||||
protected abstract disable0()
|
protected abstract disable0()
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
* 任务抽象
|
* 任务抽象
|
||||||
*/
|
*/
|
||||||
export abstract class Task {
|
export abstract class Task implements Cancelable {
|
||||||
protected plugin: any
|
|
||||||
protected func: Function
|
protected func: Function
|
||||||
protected isAsync: boolean = false;
|
protected isAsync: boolean = false;
|
||||||
protected laterTime: number = 0;
|
protected laterTime: number = 0;
|
||||||
protected interval: number = 0;
|
protected interval: number = 0;
|
||||||
|
protected owner: plugin.Plugin
|
||||||
|
protected taskId: number
|
||||||
|
protected innerTask: any
|
||||||
|
|
||||||
constructor(plugin: any, func: Function) {
|
constructor(owner: plugin.Plugin, func: Function, id: number) {
|
||||||
this.plugin = plugin
|
this.owner = owner
|
||||||
this.func = func
|
this.func = func
|
||||||
|
this.taskId = id
|
||||||
|
}
|
||||||
|
|
||||||
|
getOwner() {
|
||||||
|
return this.owner
|
||||||
|
}
|
||||||
|
|
||||||
|
getTaskId() {
|
||||||
|
return this.taskId
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -90,13 +133,16 @@ export namespace task {
|
|||||||
* 取消任务
|
* 取消任务
|
||||||
*/
|
*/
|
||||||
cancel(): boolean {
|
cancel(): boolean {
|
||||||
throw new Error("Method not implemented.")
|
let result = this.cancel0()
|
||||||
|
process.emit('task.finish', this)
|
||||||
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
protected run(...args: any[]): void {
|
protected run(...args: any[]): void {
|
||||||
try {
|
try {
|
||||||
this.func(...args)
|
this.func(...args)
|
||||||
} catch (ex) {
|
!this.interval && process.emit('task.finish', this)
|
||||||
|
} catch (ex: any) {
|
||||||
console.console('§4插件执行任务时发生错误', ex)
|
console.console('§4插件执行任务时发生错误', ex)
|
||||||
console.ex(ex)
|
console.ex(ex)
|
||||||
}
|
}
|
||||||
@@ -106,17 +152,22 @@ export namespace task {
|
|||||||
* 提交任务
|
* 提交任务
|
||||||
* @param args 任务参数
|
* @param args 任务参数
|
||||||
*/
|
*/
|
||||||
submit(...args: any[]): Cancelable {
|
submit(...args: any[]): task.Task {
|
||||||
let cancelable = this.submit0(...args)
|
this.innerTask = this.submit0(...args)
|
||||||
this.cancel = cancelable.cancel
|
return this
|
||||||
return cancelable
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 提交任务
|
* 提交任务
|
||||||
* @param args 任务参数
|
* @param args 任务参数
|
||||||
*/
|
*/
|
||||||
protected abstract submit0(...args: any[]): Cancelable
|
protected abstract submit0(...args: any[]): any
|
||||||
|
/**
|
||||||
|
* 取消任务
|
||||||
|
*/
|
||||||
|
protected cancel0(): boolean {
|
||||||
|
return this.innerTask?.cancel()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
* 返可取消的对象
|
* 返可取消的对象
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/bukkit",
|
"name": "@ccms/bukkit",
|
||||||
"version": "0.9.8",
|
"version": "0.20.0-alpha.0",
|
||||||
"description": "MiaoScript bukkit package",
|
"description": "MiaoScript bukkit package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -22,11 +22,11 @@
|
|||||||
"@javatypes/spigot-api": "^0.0.3",
|
"@javatypes/spigot-api": "^0.0.3",
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^4.0.3"
|
"typescript": "^4.5.5"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ccms/api": "^0.9.8",
|
"@ccms/api": "^0.20.0-alpha.0",
|
||||||
"@ccms/common": "^0.9.8",
|
"@ccms/common": "^0.19.0",
|
||||||
"@ccms/container": "^0.9.8"
|
"@ccms/container": "^0.19.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { channel, plugin } from '@ccms/api'
|
import { channel, plugin } from '@ccms/api'
|
||||||
import { inject, provideSingleton } from '@ccms/container'
|
import { inject, provideSingleton } from '@ccms/container'
|
||||||
|
|
||||||
const Bukkit = org.bukkit.Bukkit
|
const Bukkit: typeof org.bukkit.Bukkit = Java.type('org.bukkit.Bukkit')
|
||||||
const PluginMessageListener = Java.type("org.bukkit.plugin.messaging.PluginMessageListener")
|
const PluginMessageListener = Java.type("org.bukkit.plugin.messaging.PluginMessageListener")
|
||||||
const Messenger = Bukkit.getMessenger()
|
const Messenger = Bukkit.getMessenger()
|
||||||
|
|
||||||
@@ -32,7 +32,7 @@ export class BukkitChannel extends channel.Channel {
|
|||||||
onPluginMessageReceived: (/**String */ channel, /**Player */ player, /**byte[] */data) => {
|
onPluginMessageReceived: (/**String */ channel, /**Player */ player, /**byte[] */data) => {
|
||||||
try {
|
try {
|
||||||
listener(data, { channel, player, data })
|
listener(data, { channel, player, data })
|
||||||
} catch (error) {
|
} catch (error: any) {
|
||||||
console.ex(error)
|
console.ex(error)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,12 @@
|
|||||||
import { chat } from '@ccms/api'
|
import { chat } from '@ccms/api'
|
||||||
import { provideSingleton } from '@ccms/container'
|
import { provideSingleton } from '@ccms/container'
|
||||||
import bukkitChat from './enhance/chat'
|
import bukkitChat from './internal/chat'
|
||||||
|
|
||||||
@provideSingleton(chat.Chat)
|
@provideSingleton(chat.Chat)
|
||||||
export class BukkitChat extends chat.Chat {
|
export class BukkitChat extends chat.Chat {
|
||||||
|
get handle(): any {
|
||||||
|
return bukkitChat
|
||||||
|
}
|
||||||
sendJson(sender: any, json: string | object, type = 0) {
|
sendJson(sender: any, json: string | object, type = 0) {
|
||||||
bukkitChat.send(sender, typeof json === "string" ? json : JSON.stringify(json), type)
|
bukkitChat.send(sender, typeof json === "string" ? json : JSON.stringify(json), type)
|
||||||
}
|
}
|
||||||
@@ -16,7 +19,7 @@ export class BukkitChat extends chat.Chat {
|
|||||||
sendTitle(sender: any, title: string, subtitle: string = '', fadeIn: number = 20, time: number = 100, fadeOut: number = 20) {
|
sendTitle(sender: any, title: string, subtitle: string = '', fadeIn: number = 20, time: number = 100, fadeOut: number = 20) {
|
||||||
try {
|
try {
|
||||||
sender.sendTitle(title, subtitle, fadeIn, time, fadeOut)
|
sender.sendTitle(title, subtitle, fadeIn, time, fadeOut)
|
||||||
} catch (error) {
|
} catch (error: any) {
|
||||||
sender.sendTitle(title, subtitle)
|
sender.sendTitle(title, subtitle)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,35 +1,38 @@
|
|||||||
import '@ccms/nashorn'
|
import '@ccms/nashorn'
|
||||||
|
|
||||||
import { command, plugin } from '@ccms/api'
|
import { command, plugin } from '@ccms/api'
|
||||||
import * as reflect from '@ccms/common/dist/reflect'
|
|
||||||
import { provideSingleton, postConstruct, inject } from '@ccms/container'
|
import { provideSingleton, postConstruct, inject } from '@ccms/container'
|
||||||
|
import * as reflect from '@ccms/common/dist/reflect'
|
||||||
|
|
||||||
let Bukkit = org.bukkit.Bukkit
|
const Bukkit: typeof org.bukkit.Bukkit = Java.type('org.bukkit.Bukkit')
|
||||||
let TabCompleter = Java.type('org.bukkit.command.TabCompleter')
|
const TabCompleter = Java.type('org.bukkit.command.TabCompleter')
|
||||||
let PluginCommand = Java.type('org.bukkit.command.PluginCommand')
|
const PluginCommand = Java.type('org.bukkit.command.PluginCommand')
|
||||||
let CommandExecutor = Java.type('org.bukkit.command.CommandExecutor')
|
const CommandExecutor = Java.type('org.bukkit.command.CommandExecutor')
|
||||||
|
|
||||||
@provideSingleton(command.Command)
|
@provideSingleton(command.Command)
|
||||||
export class BukkitCommand extends command.Command {
|
export class BukkitCommand extends command.Command {
|
||||||
@inject(plugin.PluginInstance)
|
@inject(plugin.PluginInstance)
|
||||||
private pluginInstance: any
|
private pluginInstance: any
|
||||||
private commandMap: any
|
private commandMap: any
|
||||||
|
private knownCommands: any
|
||||||
|
|
||||||
@postConstruct()
|
@postConstruct()
|
||||||
init() {
|
init() {
|
||||||
this.commandMap = reflect.on(Bukkit.getPluginManager()).get('commandMap').get()
|
this.commandMap = reflect.on(Bukkit.getPluginManager()).get('commandMap').get()
|
||||||
|
this.knownCommands = reflect.on(this.commandMap).get('knownCommands').get()
|
||||||
}
|
}
|
||||||
create(plugin: any, command: string) {
|
create(plugin: any, command: string) {
|
||||||
var cmd = this.commandMap.getCommand(command)
|
var cmd = this.commandMap.getCommand(command)
|
||||||
if (cmd && cmd instanceof PluginCommand) { return cmd };
|
if (cmd instanceof PluginCommand) { return cmd };
|
||||||
cmd = reflect.on(PluginCommand).create(command, this.pluginInstance).get()
|
cmd = reflect.on(PluginCommand).create(command, this.pluginInstance).get()
|
||||||
this.commandMap.register(plugin.description.name, cmd)
|
this.commandMap.register(plugin.description.name, cmd)
|
||||||
return cmd
|
return cmd
|
||||||
}
|
}
|
||||||
remove(plugin: any, command: string) {
|
remove(plugin: any, command: string) {
|
||||||
var cmd = this.commandMap.getCommand(command)
|
var cmd = this.commandMap.getCommand(command)
|
||||||
if (cmd && cmd instanceof PluginCommand) {
|
if (cmd instanceof PluginCommand) {
|
||||||
cmd.unregister(this.commandMap)
|
cmd.unregister(this.commandMap)
|
||||||
|
this.knownCommands.remove(command)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
tabComplete(sender: any, input: string, index?: number): string[] {
|
tabComplete(sender: any, input: string, index?: number): string[] {
|
||||||
|
|||||||
@@ -1,20 +1,20 @@
|
|||||||
import { MiaoScriptConsole } from '@ccms/api'
|
import { MiaoScriptConsole } from '@ccms/api'
|
||||||
|
|
||||||
let Bukkit = org.bukkit.Bukkit;
|
const Bukkit: typeof org.bukkit.Bukkit = Java.type('org.bukkit.Bukkit')
|
||||||
|
|
||||||
export class BukkitConsole extends MiaoScriptConsole {
|
export class BukkitConsole extends MiaoScriptConsole {
|
||||||
sender(sender, ...args) {
|
sender(sender, ...args) {
|
||||||
if (!(sender instanceof Java.type('org.bukkit.command.CommandSender'))) {
|
if (!(sender instanceof Java.type('org.bukkit.command.CommandSender'))) {
|
||||||
this.error(`First parameter ${sender} not instanceof org.bukkit.command.CommandSender can't send message!`)
|
this.error(`First parameter ${sender} not instanceof org.bukkit.command.CommandSender can't send message!`)
|
||||||
return;
|
return
|
||||||
}
|
}
|
||||||
if (Object.prototype.toString.call(args[0]) === "[object Array]") {
|
if (Object.prototype.toString.call(args[0]) === "[object Array]") {
|
||||||
args[0].forEach(line => sender.sendMessage(this.prefix + line))
|
args[0].forEach(line => sender.sendMessage(this.prefix + line))
|
||||||
} else {
|
} else {
|
||||||
sender.sendMessage(this.prefix + args.join(' '));
|
sender.sendMessage(this.prefix + args.join(' '))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
console(...args: string[]): void {
|
console(...args: string[]): void {
|
||||||
this.sender(Bukkit.getConsoleSender(), args.join(' '));
|
this.sender(Bukkit.getConsoleSender(), args.join(' '))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,118 +0,0 @@
|
|||||||
/*global Java, base, module, exports, require*/
|
|
||||||
let ChatSerializer: any
|
|
||||||
let nmsChatSerializerMethodName: string
|
|
||||||
let PacketPlayOutChat: any
|
|
||||||
let chatMessageTypes: any
|
|
||||||
|
|
||||||
let RemapUtils: any
|
|
||||||
|
|
||||||
let playerConnectionFieldName: string
|
|
||||||
let sendPacketMethodName: string
|
|
||||||
|
|
||||||
let above_1_16 = false
|
|
||||||
let downgrade = false
|
|
||||||
/**
|
|
||||||
* 获取NMS版本
|
|
||||||
*/
|
|
||||||
let nmsVersion = undefined
|
|
||||||
/**
|
|
||||||
* 获取NMS类
|
|
||||||
*/
|
|
||||||
function nmsCls(name: string) {
|
|
||||||
return base.getClass(['net.minecraft.server', nmsVersion, name].join('.'))
|
|
||||||
}
|
|
||||||
|
|
||||||
function remapMethod(clazz: any, origin: string, test: string, params: any) {
|
|
||||||
try {
|
|
||||||
return clazz.getMethod(origin, params)
|
|
||||||
} catch (ex) {
|
|
||||||
if (RemapUtils) {
|
|
||||||
return clazz.getMethod(RemapUtils.mapMethod(clazz, origin, params), params)
|
|
||||||
} else {
|
|
||||||
return clazz.getMethod(test, params)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function remapFieldName(clazz: any, origin: string, test: string) {
|
|
||||||
try {
|
|
||||||
return clazz.getField(origin)
|
|
||||||
} catch (ex) {
|
|
||||||
if (RemapUtils) {
|
|
||||||
return clazz.getField(RemapUtils.mapFieldName(clazz, origin))
|
|
||||||
} else {
|
|
||||||
return clazz.getField(test)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function init() {
|
|
||||||
//@ts-ignore
|
|
||||||
nmsVersion = org.bukkit.Bukkit.server.class.name.split('.')[3]
|
|
||||||
try {
|
|
||||||
RemapUtils = Java.type('catserver.server.remapper.RemapUtils')
|
|
||||||
} catch (ex) {
|
|
||||||
}
|
|
||||||
let nmsChatSerializerClass = nmsCls(nmsVersion.split("_")[1] > 7 ? "IChatBaseComponent$ChatSerializer" : "ChatSerializer")
|
|
||||||
let nmsChatSerializerMethod = remapMethod(nmsChatSerializerClass, 'a', 'func_150699_a', base.getClass('java.lang.String'))
|
|
||||||
nmsChatSerializerMethodName = nmsChatSerializerMethod.getName()
|
|
||||||
ChatSerializer = Java.type(nmsChatSerializerClass.getName())
|
|
||||||
let packetTypeClass = nmsCls("PacketPlayOutChat")
|
|
||||||
PacketPlayOutChat = Java.type(packetTypeClass.getName())
|
|
||||||
let packetTypeConstructor: { parameterTypes: any[] }
|
|
||||||
let constructors = packetTypeClass.constructors
|
|
||||||
Java.from(constructors).forEach(function (c) {
|
|
||||||
if (c.parameterTypes.length === 2) {
|
|
||||||
packetTypeConstructor = c
|
|
||||||
}
|
|
||||||
if (c.parameterTypes.length === 3) {
|
|
||||||
packetTypeConstructor = c
|
|
||||||
above_1_16 = true
|
|
||||||
}
|
|
||||||
})
|
|
||||||
let parameterTypes = packetTypeConstructor.parameterTypes
|
|
||||||
let nmsChatMessageTypeClass = parameterTypes[1]
|
|
||||||
if (nmsChatMessageTypeClass.isEnum()) {
|
|
||||||
chatMessageTypes = nmsChatMessageTypeClass.getEnumConstants()
|
|
||||||
}
|
|
||||||
let playerConnectionField = remapFieldName(nmsCls('EntityPlayer'), 'playerConnection', 'field_71135_a')
|
|
||||||
playerConnectionFieldName = playerConnectionField.getName()
|
|
||||||
sendPacketMethodName = remapMethod(playerConnectionField.getType(), 'sendPacket', 'func_179290_a', nmsCls('Packet')).getName()
|
|
||||||
}
|
|
||||||
|
|
||||||
function json(sender: { name: string }, json: string) {
|
|
||||||
if (downgrade) {
|
|
||||||
return '/tellraw ' + sender.name + ' ' + json
|
|
||||||
} else {
|
|
||||||
send(sender, json, 0)
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function send(sender: any, json: any, type: number) {
|
|
||||||
let packet
|
|
||||||
if (above_1_16) {
|
|
||||||
packet = new PacketPlayOutChat(ChatSerializer[nmsChatSerializerMethodName](json), chatMessageTypes == null ? type : chatMessageTypes[type], sender.getUniqueId())
|
|
||||||
} else {
|
|
||||||
packet = new PacketPlayOutChat(ChatSerializer[nmsChatSerializerMethodName](json), chatMessageTypes == null ? type : chatMessageTypes[type])
|
|
||||||
}
|
|
||||||
sendPacket(sender, packet)
|
|
||||||
}
|
|
||||||
|
|
||||||
function sendPacket(player: { handle: { [x: string]: { [x: string]: (arg0: any) => void } } }, p: any) {
|
|
||||||
player.handle[playerConnectionFieldName][sendPacketMethodName](p)
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
init()
|
|
||||||
} catch (ex) {
|
|
||||||
org.bukkit.Bukkit.getConsoleSender().sendMessage(`§6[§cMS§6][§bbukkit§6][§achat§6] §cNMS Inject Error §4${ex} §cDowngrade to Command Mode...`)
|
|
||||||
downgrade = true
|
|
||||||
}
|
|
||||||
|
|
||||||
let chat = {
|
|
||||||
json,
|
|
||||||
send
|
|
||||||
}
|
|
||||||
|
|
||||||
export default chat
|
|
||||||
@@ -1,13 +1,13 @@
|
|||||||
import { event, plugin } from '@ccms/api'
|
import { event, plugin } from '@ccms/api'
|
||||||
import { inject, provideSingleton } from '@ccms/container';
|
import { inject, provideSingleton } from '@ccms/container'
|
||||||
import * as reflect from '@ccms/common/dist/reflect'
|
import * as reflect from '@ccms/common/dist/reflect'
|
||||||
|
|
||||||
const Bukkit = Java.type("org.bukkit.Bukkit");
|
const Bukkit = Java.type("org.bukkit.Bukkit")
|
||||||
const Event = Java.type("org.bukkit.event.Event");
|
const Event = Java.type("org.bukkit.event.Event")
|
||||||
const Modifier = Java.type("java.lang.reflect.Modifier");
|
const Modifier = Java.type("java.lang.reflect.Modifier")
|
||||||
const Listener = Java.type("org.bukkit.event.Listener");
|
const Listener = Java.type("org.bukkit.event.Listener")
|
||||||
const EventPriority = Java.type("org.bukkit.event.EventPriority");
|
const EventPriority = Java.type("org.bukkit.event.EventPriority")
|
||||||
const EventExecutor = Java.type("org.bukkit.plugin.EventExecutor");
|
const EventExecutor = Java.type("org.bukkit.plugin.EventExecutor")
|
||||||
|
|
||||||
@provideSingleton(event.Event)
|
@provideSingleton(event.Event)
|
||||||
export class BukkitEvent extends event.Event {
|
export class BukkitEvent extends event.Event {
|
||||||
@@ -15,7 +15,7 @@ export class BukkitEvent extends event.Event {
|
|||||||
private pluginInstance: any
|
private pluginInstance: any
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
super('org/bukkit/event');
|
super('org/bukkit/event')
|
||||||
}
|
}
|
||||||
|
|
||||||
getJarFile(resource: string) {
|
getJarFile(resource: string) {
|
||||||
@@ -27,10 +27,10 @@ export class BukkitEvent extends event.Event {
|
|||||||
// 访问符为Public
|
// 访问符为Public
|
||||||
Modifier.isPublic(clazz.getModifiers()) &&
|
Modifier.isPublic(clazz.getModifiers()) &&
|
||||||
// 不是抽象类
|
// 不是抽象类
|
||||||
!Modifier.isAbstract(clazz.getModifiers());
|
!Modifier.isAbstract(clazz.getModifiers())
|
||||||
}
|
}
|
||||||
register(eventCls: any, exec: Function, priority: event.EventPriority, ignoreCancel: boolean) {
|
register(eventCls: any, exec: Function, priority: event.EventPriority, ignoreCancel: boolean) {
|
||||||
let listener = new Listener({});
|
let listener = new Listener({})
|
||||||
Bukkit.pluginManager.registerEvent(
|
Bukkit.pluginManager.registerEvent(
|
||||||
eventCls,
|
eventCls,
|
||||||
listener,
|
listener,
|
||||||
@@ -39,10 +39,10 @@ export class BukkitEvent extends event.Event {
|
|||||||
execute: exec
|
execute: exec
|
||||||
}),
|
}),
|
||||||
this.pluginInstance,
|
this.pluginInstance,
|
||||||
ignoreCancel);
|
ignoreCancel)
|
||||||
return listener;
|
return listener
|
||||||
}
|
}
|
||||||
unregister(event: any, listener: any): void {
|
unregister(event: any, listener: any): void {
|
||||||
reflect.on(event).call('getHandlerList').get().unregister(listener);
|
reflect.on(event).call('getHandlerList').get().unregister(listener)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,9 +8,12 @@ import './chat'
|
|||||||
import './task'
|
import './task'
|
||||||
import './event'
|
import './event'
|
||||||
import './server'
|
import './server'
|
||||||
|
import { BukkitNativePluginManager } from './plugin'
|
||||||
import './command'
|
import './command'
|
||||||
import './channel'
|
import './channel'
|
||||||
|
import './particle'
|
||||||
|
|
||||||
export default function BukkitImpl(container: Container) {
|
export default function BukkitImpl(container: Container) {
|
||||||
container.bind(server.Console).toConstantValue(BukkitConsole)
|
container.bind(server.Console).toConstantValue(BukkitConsole)
|
||||||
|
container.rebind(server.NativePluginManager).toConstantValue(new BukkitNativePluginManager())
|
||||||
}
|
}
|
||||||
|
|||||||
176
packages/bukkit/src/internal/chat.ts
Normal file
176
packages/bukkit/src/internal/chat.ts
Normal file
@@ -0,0 +1,176 @@
|
|||||||
|
/*global Java, base, module, exports, require*/
|
||||||
|
let bukkitChatInvoke: BukkitChatInvoke
|
||||||
|
/**
|
||||||
|
* 获取NMS类
|
||||||
|
*/
|
||||||
|
abstract class BukkitChatInvoke {
|
||||||
|
private downgrade: boolean = false
|
||||||
|
protected RemapUtils: any
|
||||||
|
|
||||||
|
protected ChatSerializer: any
|
||||||
|
protected nmsChatSerializerMethodName: string
|
||||||
|
protected PacketPlayOutChat: any
|
||||||
|
protected chatMessageTypes: any
|
||||||
|
protected playerConnectionFieldName: string
|
||||||
|
protected sendPacketMethodName: string
|
||||||
|
|
||||||
|
constructor(private nmsVersion) {
|
||||||
|
}
|
||||||
|
|
||||||
|
init() {
|
||||||
|
try {
|
||||||
|
try {
|
||||||
|
this.RemapUtils = Java.type('catserver.server.remapper.RemapUtils')
|
||||||
|
} catch (ex: any) {
|
||||||
|
}
|
||||||
|
let nmsChatSerializerClass = this.getNmsChatSerializerClass()
|
||||||
|
let nmsChatSerializerMethod = this.remapMethod(nmsChatSerializerClass, 'a', 'func_150699_a', base.getClass('java.lang.String'))
|
||||||
|
this.nmsChatSerializerMethodName = nmsChatSerializerMethod.getName()
|
||||||
|
this.ChatSerializer = Java.type(nmsChatSerializerClass.getName())
|
||||||
|
let packetTypeClass = this.getPacketPlayOutChatClass()
|
||||||
|
this.PacketPlayOutChat = Java.type(packetTypeClass.getName())
|
||||||
|
let constructors = packetTypeClass.constructors
|
||||||
|
for (const constructor of Java.from(constructors)) {
|
||||||
|
let parameterTypes = constructor.parameterTypes
|
||||||
|
if (parameterTypes.length === 2 || parameterTypes.length === 3) {
|
||||||
|
let nmsChatMessageTypeClass = parameterTypes[1]
|
||||||
|
if (nmsChatMessageTypeClass.isEnum()) {
|
||||||
|
this.chatMessageTypes = nmsChatMessageTypeClass.getEnumConstants()
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let playerConnectionField = this.getPlayerConnectionField()
|
||||||
|
this.playerConnectionFieldName = playerConnectionField.getName()
|
||||||
|
this.sendPacketMethodName = this.remapMethod(playerConnectionField.getType(), 'sendPacket', 'func_179290_a', this.getPacketClass()).getName()
|
||||||
|
} catch (ex: any) {
|
||||||
|
org.bukkit.Bukkit.getConsoleSender().sendMessage(`§6[§cMS§6][§bbukkit§6][§achat§6] §cNMS Inject Error §4${ex} §cDowngrade to Command Mode...`)
|
||||||
|
this.downgrade = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
abstract getNmsChatSerializerClass()
|
||||||
|
abstract getPacketPlayOutChatClass()
|
||||||
|
abstract getPacketPlayOutChat(sender: any, json: any, type: number)
|
||||||
|
abstract getPlayerConnectionField()
|
||||||
|
abstract getPacketClass()
|
||||||
|
|
||||||
|
nmsCls(name: string) {
|
||||||
|
return base.getClass(['net.minecraft.server', this.nmsVersion, name].join('.'))
|
||||||
|
}
|
||||||
|
|
||||||
|
remapMethod(clazz: any, origin: string, test: string, params: any) {
|
||||||
|
try {
|
||||||
|
return clazz.getMethod(origin, params)
|
||||||
|
} catch (ex: any) {
|
||||||
|
if (this.RemapUtils) {
|
||||||
|
return clazz.getMethod(this.RemapUtils.mapMethod(clazz, origin, params), params)
|
||||||
|
} else {
|
||||||
|
return clazz.getMethod(test, params)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
remapFieldName(clazz: any, origin: string, test: string) {
|
||||||
|
try {
|
||||||
|
return clazz.getField(origin)
|
||||||
|
} catch (ex: any) {
|
||||||
|
if (this.RemapUtils) {
|
||||||
|
return clazz.getField(this.RemapUtils.mapFieldName(clazz, origin))
|
||||||
|
} else {
|
||||||
|
return clazz.getField(test)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
json(sender: { name: string }, json: string) {
|
||||||
|
if (this.downgrade) {
|
||||||
|
return '/tellraw ' + sender.name + ' ' + json
|
||||||
|
} else {
|
||||||
|
this.send(sender, json, 0)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
send(sender: any, json: any, type: number) {
|
||||||
|
this.sendPacket(sender, this.getPacketPlayOutChat(sender, json, type))
|
||||||
|
}
|
||||||
|
sendPacket(player: { handle: { [x: string]: { [x: string]: (arg0: any) => void } } }, p: any) {
|
||||||
|
player.handle[this.playerConnectionFieldName][this.sendPacketMethodName](p)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class BukkitChatInvokeBase extends BukkitChatInvoke {
|
||||||
|
getPacketPlayOutChat(sender: any, json: any, type: number) {
|
||||||
|
return new this.PacketPlayOutChat(this.ChatSerializer[this.nmsChatSerializerMethodName](json), type)
|
||||||
|
}
|
||||||
|
getNmsChatSerializerClass() {
|
||||||
|
return this.nmsCls("ChatSerializer")
|
||||||
|
}
|
||||||
|
getPacketPlayOutChatClass() {
|
||||||
|
return this.nmsCls("PacketPlayOutChat")
|
||||||
|
}
|
||||||
|
getPlayerConnectionField() {
|
||||||
|
return this.remapFieldName(this.nmsCls('EntityPlayer'), 'playerConnection', 'field_71135_a')
|
||||||
|
}
|
||||||
|
getPacketClass() {
|
||||||
|
return this.nmsCls('Packet')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class BukkitChatInvoke_1_7_10 extends BukkitChatInvokeBase {
|
||||||
|
}
|
||||||
|
|
||||||
|
class BukkitChatInvoke_1_8 extends BukkitChatInvoke_1_7_10 {
|
||||||
|
getPacketPlayOutChat(sender: any, json: any, type: number) {
|
||||||
|
return new this.PacketPlayOutChat(this.ChatSerializer[this.nmsChatSerializerMethodName](json), this.chatMessageTypes[type])
|
||||||
|
}
|
||||||
|
getNmsChatSerializerClass() {
|
||||||
|
return this.nmsCls("IChatBaseComponent$ChatSerializer")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
class BukkitChatInvoke_1_16_5 extends BukkitChatInvoke_1_8 {
|
||||||
|
getPacketPlayOutChat(sender: any, json: any, type: number) {
|
||||||
|
return new this.PacketPlayOutChat(this.ChatSerializer[this.nmsChatSerializerMethodName](json), this.chatMessageTypes[type], sender.getUniqueId())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class BukkitChatInvoke_1_17_1 extends BukkitChatInvoke_1_16_5 {
|
||||||
|
getPacketPlayOutChatClass() {
|
||||||
|
return base.getClass('net.minecraft.network.protocol.game.PacketPlayOutChat')
|
||||||
|
}
|
||||||
|
getNmsChatSerializerClass() {
|
||||||
|
return base.getClass('net.minecraft.network.chat.IChatBaseComponent$ChatSerializer')
|
||||||
|
}
|
||||||
|
getPlayerConnectionField() {
|
||||||
|
return base.getClass('net.minecraft.server.level.EntityPlayer').getField('b')
|
||||||
|
}
|
||||||
|
getPacketClass() {
|
||||||
|
return base.getClass('net.minecraft.network.protocol.Packet')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
let Bukkit: typeof org.bukkit.Bukkit = Java.type('org.bukkit.Bukkit')
|
||||||
|
// @ts-ignore
|
||||||
|
let nmsVersion = Bukkit.getServer().class.name.split('.')[3]
|
||||||
|
let nmsSubVersion = nmsVersion.split("_")[1]
|
||||||
|
if (nmsSubVersion >= 8) {
|
||||||
|
bukkitChatInvoke = new BukkitChatInvoke_1_8(nmsVersion)
|
||||||
|
} else if (nmsSubVersion >= 16) {
|
||||||
|
bukkitChatInvoke = new BukkitChatInvoke_1_16_5(nmsVersion)
|
||||||
|
} else if (nmsSubVersion >= 17) {
|
||||||
|
bukkitChatInvoke = new BukkitChatInvoke_1_17_1(nmsVersion)
|
||||||
|
} else {
|
||||||
|
bukkitChatInvoke = new BukkitChatInvoke_1_7_10(nmsVersion)
|
||||||
|
}
|
||||||
|
bukkitChatInvoke.init()
|
||||||
|
} catch (ex: any) {
|
||||||
|
}
|
||||||
|
|
||||||
|
let chat = {
|
||||||
|
invoke: bukkitChatInvoke,
|
||||||
|
json: bukkitChatInvoke.json.bind(bukkitChatInvoke),
|
||||||
|
send: bukkitChatInvoke.send.bind(bukkitChatInvoke)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default chat
|
||||||
31
packages/bukkit/src/particle.ts
Normal file
31
packages/bukkit/src/particle.ts
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
import { provideSingleton } from '@ccms/container'
|
||||||
|
import { particle } from '@ccms/api'
|
||||||
|
|
||||||
|
@provideSingleton(particle.ParticleManager)
|
||||||
|
export class BukkitParticleManager extends particle.ParticleManager {
|
||||||
|
private globalSpawner = new BukkitParticleSpawner()
|
||||||
|
constructor() {
|
||||||
|
super()
|
||||||
|
particle.ParticleManager.globalSpawner = this.globalSpawner
|
||||||
|
}
|
||||||
|
protected getGlobalSpawner() {
|
||||||
|
return this.globalSpawner
|
||||||
|
}
|
||||||
|
}
|
||||||
|
export class BukkitParticleSpawner extends particle.ParticleSpawner {
|
||||||
|
spawnParticle(location: any, particle: any, count: number = 1) {
|
||||||
|
location.getWorld().spawnParticle(particle, location, count)
|
||||||
|
}
|
||||||
|
spawn(location: any, particle: particle.Particle) {
|
||||||
|
location.getWorld().spawnParticle(
|
||||||
|
particle.getParticle(),
|
||||||
|
location,
|
||||||
|
particle.getCount(),
|
||||||
|
particle.getOffsetX(),
|
||||||
|
particle.getOffsetY(),
|
||||||
|
particle.getOffsetZ(),
|
||||||
|
particle.getExtra(),
|
||||||
|
particle.getData()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
52
packages/bukkit/src/plugin.ts
Normal file
52
packages/bukkit/src/plugin.ts
Normal file
@@ -0,0 +1,52 @@
|
|||||||
|
import { server } from '@ccms/api'
|
||||||
|
|
||||||
|
const Bukkit: typeof org.bukkit.Bukkit = Java.type('org.bukkit.Bukkit')
|
||||||
|
|
||||||
|
export class BukkitNativePluginManager extends server.NativePluginManager {
|
||||||
|
private bukkitPluginManager: org.bukkit.plugin.PluginManager
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
super()
|
||||||
|
this.bukkitPluginManager = Bukkit.getPluginManager()
|
||||||
|
}
|
||||||
|
|
||||||
|
list(): server.NativePlugin[] {
|
||||||
|
return Java.from(this.bukkitPluginManager.getPlugins()).map(plugin => this.convert(plugin))
|
||||||
|
}
|
||||||
|
has(name: string): boolean {
|
||||||
|
return !!this.bukkitPluginManager.getPlugin(name)
|
||||||
|
}
|
||||||
|
get(name: string): server.NativePlugin {
|
||||||
|
return this.convert(this.bukkitPluginManager.getPlugin(name))
|
||||||
|
}
|
||||||
|
enable(name: string): server.NativePlugin {
|
||||||
|
let origin = this.bukkitPluginManager.getPlugin(name)
|
||||||
|
if (!origin) { throw new Error(`Native Plugin ${name} not found.`) }
|
||||||
|
if (!origin.isEnabled()) {
|
||||||
|
this.bukkitPluginManager.enablePlugin(origin)
|
||||||
|
}
|
||||||
|
return this.convert(origin)
|
||||||
|
}
|
||||||
|
disable(name: string): server.NativePlugin {
|
||||||
|
let origin = this.bukkitPluginManager.getPlugin(name)
|
||||||
|
if (!origin) { throw new Error(`Native Plugin ${name} not found.`) }
|
||||||
|
if (origin.isEnabled()) {
|
||||||
|
this.bukkitPluginManager.disablePlugin(origin)
|
||||||
|
}
|
||||||
|
return this.convert(origin)
|
||||||
|
}
|
||||||
|
|
||||||
|
private convert(plugin: org.bukkit.plugin.Plugin): server.NativePlugin {
|
||||||
|
if (!plugin) return plugin as any
|
||||||
|
let desc = plugin.getDescription()
|
||||||
|
return {
|
||||||
|
name: plugin.getName(),
|
||||||
|
version: desc.getVersion(),
|
||||||
|
authors: Java.from(desc.getAuthors()),
|
||||||
|
depends: Java.from(desc.getDepend()),
|
||||||
|
softDepends: Java.from(desc.getSoftDepend()),
|
||||||
|
enable: plugin.isEnabled(),
|
||||||
|
origin: plugin
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,10 +1,9 @@
|
|||||||
import { server, constants } from '@ccms/api'
|
import { server } from '@ccms/api'
|
||||||
import { provideSingleton } from '@ccms/container'
|
import { provideSingleton } from '@ccms/container'
|
||||||
|
|
||||||
import * as reflect from '@ccms/common/dist/reflect'
|
import * as reflect from '@ccms/common/dist/reflect'
|
||||||
import chat from './enhance/chat'
|
|
||||||
|
|
||||||
let Bukkit = org.bukkit.Bukkit
|
const Bukkit: typeof org.bukkit.Bukkit = Java.type('org.bukkit.Bukkit')
|
||||||
|
|
||||||
@provideSingleton(server.Server)
|
@provideSingleton(server.Server)
|
||||||
export class BukkitServer extends server.ReflectServer {
|
export class BukkitServer extends server.ReflectServer {
|
||||||
@@ -30,6 +29,12 @@ export class BukkitServer extends server.ReflectServer {
|
|||||||
getService(service: string) {
|
getService(service: string) {
|
||||||
return Bukkit.getServicesManager().getRegistration(base.getClass(service))?.getProvider()
|
return Bukkit.getServicesManager().getRegistration(base.getClass(service))?.getProvider()
|
||||||
}
|
}
|
||||||
|
broadcast(message: string, permission: string) {
|
||||||
|
return Bukkit.broadcast(message, permission)
|
||||||
|
}
|
||||||
|
broadcastMessage(message: string) {
|
||||||
|
return Bukkit.broadcastMessage(message)
|
||||||
|
}
|
||||||
dispatchCommand(sender: string | any, command: string): boolean {
|
dispatchCommand(sender: string | any, command: string): boolean {
|
||||||
if (typeof sender === 'string') {
|
if (typeof sender === 'string') {
|
||||||
sender = this.getPlayer(sender)
|
sender = this.getPlayer(sender)
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { task, plugin } from '@ccms/api'
|
import { task, plugin } from '@ccms/api'
|
||||||
import { inject, provideSingleton } from '@ccms/container'
|
import { provideSingleton } from '@ccms/container'
|
||||||
|
|
||||||
const Bukkit = Java.type('org.bukkit.Bukkit')
|
const Bukkit = Java.type('org.bukkit.Bukkit')
|
||||||
const BukkitRunnable = Java.type('org.bukkit.scheduler.BukkitRunnable')
|
const BukkitRunnable = Java.type('org.bukkit.scheduler.BukkitRunnable')
|
||||||
@@ -7,28 +7,25 @@ const Callable = Java.type('java.util.concurrent.Callable')
|
|||||||
|
|
||||||
@provideSingleton(task.TaskManager)
|
@provideSingleton(task.TaskManager)
|
||||||
export class BukkitTaskManager extends task.TaskManager {
|
export class BukkitTaskManager extends task.TaskManager {
|
||||||
@inject(plugin.PluginInstance)
|
create0(owner: plugin.Plugin, func: Function, id: number): task.Task {
|
||||||
private pluginInstance: any
|
return new BukkitTask(owner, func, id)
|
||||||
|
|
||||||
create0(func: Function): task.Task {
|
|
||||||
return new BukkitTask(this.pluginInstance, func)
|
|
||||||
}
|
}
|
||||||
callSyncMethod(func: Function): any {
|
callSyncMethod(func: Function): any {
|
||||||
return Bukkit.getScheduler().callSyncMethod(this.pluginInstance, new Callable({ call: () => func() })).get()
|
return Bukkit.getScheduler().callSyncMethod(base.getInstance(), new Callable({ call: () => func() })).get()
|
||||||
}
|
}
|
||||||
disable0() {
|
disable0() {
|
||||||
Bukkit.getScheduler().cancelTasks(this.pluginInstance)
|
Bukkit.getScheduler().cancelTasks(base.getInstance())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export class BukkitTask extends task.Task {
|
export class BukkitTask extends task.Task {
|
||||||
submit0(...args: any[]): task.Cancelable {
|
submit0(...args: any[]): task.Cancelable {
|
||||||
let run = new BukkitRunnable({ run: () => this.run(...args) })
|
let run = new BukkitRunnable({ run: () => this.run(...args) })
|
||||||
let funcName = `runTask${this.interval ? 'Timer' : 'Later'}${this.isAsync ? 'Asynchronously' : ''}`
|
let suffix = this.isAsync ? 'Asynchronously' : ''
|
||||||
if (this.interval) {
|
if (this.interval) {
|
||||||
return run[funcName](this.plugin, this.laterTime, this.interval)
|
return run[`runTaskTimer${suffix}`](base.getInstance(), this.laterTime, this.interval)
|
||||||
} else {
|
} else {
|
||||||
return run[funcName](this.plugin, this.laterTime)
|
return run[`runTaskLater${suffix}`](base.getInstance(), this.laterTime)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/bungee",
|
"name": "@ccms/bungee",
|
||||||
"version": "0.9.8",
|
"version": "0.20.0-alpha.0",
|
||||||
"description": "MiaoScript bungee package",
|
"description": "MiaoScript bungee package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -22,11 +22,11 @@
|
|||||||
"@javatypes/bungee-api": "^0.0.3",
|
"@javatypes/bungee-api": "^0.0.3",
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^4.0.3"
|
"typescript": "^4.5.5"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ccms/api": "^0.9.8",
|
"@ccms/api": "^0.20.0-alpha.0",
|
||||||
"@ccms/common": "^0.9.8",
|
"@ccms/common": "^0.19.0",
|
||||||
"@ccms/container": "^0.9.8"
|
"@ccms/container": "^0.19.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -79,7 +79,7 @@ export class BungeeEvent extends event.Event {
|
|||||||
currentPriorityMap.put(listener, methods);
|
currentPriorityMap.put(listener, methods);
|
||||||
this.bakeHandlers.invoke(this.eventBus, eventCls);
|
this.bakeHandlers.invoke(this.eventBus, eventCls);
|
||||||
return listener;
|
return listener;
|
||||||
} catch (ex) {
|
} catch (ex: any) {
|
||||||
console.ex(ex)
|
console.ex(ex)
|
||||||
} finally {
|
} finally {
|
||||||
this.lock.unlock()
|
this.lock.unlock()
|
||||||
@@ -108,7 +108,7 @@ export class BungeeEvent extends event.Event {
|
|||||||
}
|
}
|
||||||
this.bakeHandlers.invoke(this.eventBus, eventCls);
|
this.bakeHandlers.invoke(this.eventBus, eventCls);
|
||||||
}
|
}
|
||||||
} catch (ex) {
|
} catch (ex: any) {
|
||||||
console.ex(ex)
|
console.ex(ex)
|
||||||
} finally {
|
} finally {
|
||||||
this.lock.unlock()
|
this.lock.unlock()
|
||||||
|
|||||||
@@ -3,13 +3,15 @@
|
|||||||
import { server } from '@ccms/api'
|
import { server } from '@ccms/api'
|
||||||
import { Container } from '@ccms/container'
|
import { Container } from '@ccms/container'
|
||||||
|
|
||||||
import { BungeeConsole } from './console';
|
import { BungeeConsole } from './console'
|
||||||
import './event';
|
import './task'
|
||||||
import './server';
|
import './event'
|
||||||
import './command';
|
import './server'
|
||||||
import './channel';
|
import { BungeeNativePluginManager } from './plugin'
|
||||||
import './task';
|
import './command'
|
||||||
|
import './channel'
|
||||||
|
|
||||||
export default function BungeeImpl(container: Container) {
|
export default function BungeeImpl(container: Container) {
|
||||||
container.bind(server.Console).toConstantValue(BungeeConsole);
|
container.bind(server.Console).toConstantValue(BungeeConsole)
|
||||||
|
container.rebind(server.NativePluginManager).toConstantValue(new BungeeNativePluginManager())
|
||||||
}
|
}
|
||||||
|
|||||||
36
packages/bungee/src/plugin.ts
Normal file
36
packages/bungee/src/plugin.ts
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
import { server } from '@ccms/api'
|
||||||
|
|
||||||
|
let Bungee: net.md_5.bungee.api.ProxyServer = base.getInstance().getProxy()
|
||||||
|
|
||||||
|
export class BungeeNativePluginManager extends server.NativePluginManager {
|
||||||
|
private bungeePluginManager: net.md_5.bungee.api.plugin.PluginManager
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
super()
|
||||||
|
this.bungeePluginManager = Bungee.getPluginManager()
|
||||||
|
}
|
||||||
|
|
||||||
|
list(): server.NativePlugin[] {
|
||||||
|
return Java.from(this.bungeePluginManager.getPlugins()).map(plugin => this.convert(plugin))
|
||||||
|
}
|
||||||
|
has(name: string): boolean {
|
||||||
|
return !!this.bungeePluginManager.getPlugin(name)
|
||||||
|
}
|
||||||
|
get(name: string): server.NativePlugin {
|
||||||
|
return this.convert(this.bungeePluginManager.getPlugin(name))
|
||||||
|
}
|
||||||
|
|
||||||
|
private convert(plugin: net.md_5.bungee.api.plugin.Plugin): server.NativePlugin {
|
||||||
|
if (!plugin) return plugin as any
|
||||||
|
let desc = plugin.getDescription()
|
||||||
|
return {
|
||||||
|
name: desc.getName(),
|
||||||
|
version: desc.getVersion(),
|
||||||
|
authors: [desc.getAuthor()],
|
||||||
|
depends: Java.from(desc.getDepends()) as any,
|
||||||
|
softDepends: Java.from(desc.getSoftDepends()) as any,
|
||||||
|
enable: true,
|
||||||
|
origin: plugin
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -26,7 +26,7 @@ export class BungeeServer implements server.Server {
|
|||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
this.pipeline = reflect.on(base.getInstance().getProxy()).get('listeners').get().toArray()[0].pipeline()
|
this.pipeline = reflect.on(base.getInstance().getProxy()).get('listeners').get().toArray()[0].pipeline()
|
||||||
wait.cancel()
|
wait.cancel()
|
||||||
} catch (ex) {
|
} catch (ex: any) {
|
||||||
count++
|
count++
|
||||||
if (count > 50) {
|
if (count > 50) {
|
||||||
console.error('Reflect BungeeCord netty channel pipeline error time > 50times. Err: ' + ex)
|
console.error('Reflect BungeeCord netty channel pipeline error time > 50times. Err: ' + ex)
|
||||||
@@ -38,7 +38,7 @@ export class BungeeServer implements server.Server {
|
|||||||
}).later(10).timer(20).submit()
|
}).later(10).timer(20).submit()
|
||||||
try {
|
try {
|
||||||
this.rootLogger = Bungee.getLogger()
|
this.rootLogger = Bungee.getLogger()
|
||||||
} catch (error) {
|
} catch (error: any) {
|
||||||
console.error("Can't found rootLogger!")
|
console.error("Can't found rootLogger!")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -58,6 +58,12 @@ export class BungeeServer implements server.Server {
|
|||||||
getService(service: string) {
|
getService(service: string) {
|
||||||
throw new Error("Method not implemented.")
|
throw new Error("Method not implemented.")
|
||||||
}
|
}
|
||||||
|
broadcast(message: string, permission: string) {
|
||||||
|
return Bungee.broadcast(message)
|
||||||
|
}
|
||||||
|
broadcastMessage(message: string) {
|
||||||
|
return Bungee.broadcast(message)
|
||||||
|
}
|
||||||
dispatchCommand(sender: string | any, command: string): boolean {
|
dispatchCommand(sender: string | any, command: string): boolean {
|
||||||
if (typeof sender === 'string') {
|
if (typeof sender === 'string') {
|
||||||
sender = this.getPlayer(sender)
|
sender = this.getPlayer(sender)
|
||||||
|
|||||||
@@ -6,17 +6,14 @@ let TimeUnit = Java.type('java.util.concurrent.TimeUnit')
|
|||||||
|
|
||||||
@provideSingleton(task.TaskManager)
|
@provideSingleton(task.TaskManager)
|
||||||
export class BungeeTaskManager extends task.TaskManager {
|
export class BungeeTaskManager extends task.TaskManager {
|
||||||
@inject(plugin.PluginInstance)
|
create0(owner: plugin.Plugin, func: Function, id: number): task.Task {
|
||||||
private pluginInstance: any
|
return new BungeeTask(owner, func, id)
|
||||||
|
|
||||||
create0(func: Function): task.Task {
|
|
||||||
return new BungeeTask(this.pluginInstance, func)
|
|
||||||
}
|
}
|
||||||
callSyncMethod(func: Function): any {
|
callSyncMethod(func: Function): any {
|
||||||
return func()
|
return func()
|
||||||
}
|
}
|
||||||
disable0() {
|
disable0() {
|
||||||
this.pluginInstance.getProxy().getScheduler().cancel(this.pluginInstance)
|
base.getInstance().getProxy().getScheduler().cancel(base.getInstance())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -24,12 +21,12 @@ export class BungeeTask extends task.Task {
|
|||||||
submit0(...args: any[]): task.Cancelable {
|
submit0(...args: any[]): task.Cancelable {
|
||||||
let run = new Runnable({ run: () => this.run(...args) })
|
let run = new Runnable({ run: () => this.run(...args) })
|
||||||
if (this.isAsync) {
|
if (this.isAsync) {
|
||||||
return this.plugin.getProxy().getScheduler().runAsync(this.plugin, run)
|
return base.getInstance().getProxy().getScheduler().runAsync(base.getInstance(), run)
|
||||||
}
|
}
|
||||||
if (this.interval) {
|
if (this.interval) {
|
||||||
return this.plugin.getProxy().getScheduler().schedule(this.plugin, run, this.laterTime * 50, this.interval * 50, TimeUnit.MILLISECONDS)
|
return base.getInstance().getProxy().getScheduler().schedule(base.getInstance(), run, this.laterTime * 50, this.interval * 50, TimeUnit.MILLISECONDS)
|
||||||
} else {
|
} else {
|
||||||
return this.plugin.getProxy().getScheduler().schedule(this.plugin, run, this.laterTime * 50, TimeUnit.MILLISECONDS)
|
return base.getInstance().getProxy().getScheduler().schedule(base.getInstance(), run, this.laterTime * 50, TimeUnit.MILLISECONDS)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
1
packages/client/.gitignore
vendored
Normal file
1
packages/client/.gitignore
vendored
Normal file
@@ -0,0 +1 @@
|
|||||||
|
src/emp.ts
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"private": true,
|
"private": true,
|
||||||
"name": "@ccms/client",
|
"name": "@ccms/client",
|
||||||
"version": "0.9.4",
|
"version": "0.19.0",
|
||||||
"description": "MiaoScript client package",
|
"description": "MiaoScript client package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -19,13 +19,19 @@
|
|||||||
"watch": "tsc --watch",
|
"watch": "tsc --watch",
|
||||||
"build": "yarn clean && tsc",
|
"build": "yarn clean && tsc",
|
||||||
"start": "node dist/index.js",
|
"start": "node dist/index.js",
|
||||||
|
"debug": "DEBUG=minecraft-protocol node dist/index.js",
|
||||||
|
"emp": "node dist/emp.js",
|
||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"minecraft-protocol": "^1.16.0"
|
"axios": "^0.25.0",
|
||||||
|
"minecraft-protocol": "^1.30.0",
|
||||||
|
"minecraft-protocol-forge": "^1.0.0",
|
||||||
|
"proxy-agent": "^5.0.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@types/node": "^17.0.17",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^4.0.3"
|
"typescript": "^4.5.5"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,13 +1,15 @@
|
|||||||
import { createInterface } from 'readline'
|
import { createInterface } from 'readline'
|
||||||
import { createClient } from 'minecraft-protocol'
|
import { Client, createClient } from 'minecraft-protocol'
|
||||||
|
|
||||||
import { attachForge } from './forge'
|
import { attachForge } from './forge'
|
||||||
import { attachEvents } from './event'
|
import { attachEvents } from './event'
|
||||||
|
|
||||||
let username = process.argv[2] || 'Mr_jtb'
|
let readUserInfo = process.argv[2] || 'Mr_jtb'
|
||||||
let password = process.argv[3] || ''
|
let realUserInfo = readUserInfo.split(":")
|
||||||
let version = process.argv[4] || '1.12.2'
|
let username = realUserInfo[0]
|
||||||
let readAddress = process.argv[5] || '192.168.2.5:25577'
|
let password = realUserInfo[1] || ''
|
||||||
|
let version = process.argv[3] || '1.12.2'
|
||||||
|
let readAddress = process.argv[4] || '192.168.2.25:25565'
|
||||||
let realAddress = readAddress.split(":")
|
let realAddress = readAddress.split(":")
|
||||||
let address = realAddress[0]
|
let address = realAddress[0]
|
||||||
let port = parseInt(realAddress[1] || "25565")
|
let port = parseInt(realAddress[1] || "25565")
|
||||||
@@ -18,17 +20,23 @@ function commandLineCreateClient() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function createConnection(host: string, port: number, username: string, password: string) {
|
function createConnection(host: string, port: number, username: string, password: string) {
|
||||||
let client = createClient({
|
let clientOptions: any = {
|
||||||
version,
|
version,
|
||||||
host,
|
host,
|
||||||
port,
|
port,
|
||||||
username,
|
username,
|
||||||
password,
|
password,
|
||||||
clientToken: 'd02c7f39-2376-45da-a5a5-50e24fa8b185',
|
// clientToken: 'd02c7f39-2376-45da-a5a5-50e24fa8b185',
|
||||||
//@ts-ignore
|
//@ts-ignore
|
||||||
authServer: 'https://mcsso.yumc.pw/api/yggdrasil/authserver',
|
// authServer: 'https://skin.yumc.pw/api/yggdrasil/authserver',
|
||||||
sessionServer: 'https://mcsso.yumc.pw/api/yggdrasil/sessionserver'
|
// sessionServer: 'https://skin.yumc.pw/api/yggdrasil/sessionserver'
|
||||||
})
|
}
|
||||||
|
if (clientOptions.password) {
|
||||||
|
clientOptions.clientToken = 'd02c7f39-2376-45da-a5a5-50e24fa8b185'
|
||||||
|
clientOptions.authServer = 'https://skin.yumc.pw/api/yggdrasil/authserver'
|
||||||
|
clientOptions.sessionServer = 'https://skin.yumc.pw/api/yggdrasil/sessionserver'
|
||||||
|
}
|
||||||
|
let client = createClient(clientOptions)
|
||||||
|
|
||||||
attachCommon(client)
|
attachCommon(client)
|
||||||
attachForge(client)
|
attachForge(client)
|
||||||
@@ -36,7 +44,24 @@ function createConnection(host: string, port: number, username: string, password
|
|||||||
return client
|
return client
|
||||||
}
|
}
|
||||||
|
|
||||||
function attachCommon(client) {
|
function attachCommon(client: Client) {
|
||||||
|
client.on('login', () => {
|
||||||
|
// client.registerChannel('updater', ['string', []])
|
||||||
|
// client.registerChannel('updater-enabled', ['string', []])
|
||||||
|
// client.registerChannel('dragoncore', ['string', []])
|
||||||
|
// client.registerChannel('dragoncore:main', ['string', []])
|
||||||
|
client.on('REGISTER', (array) => {
|
||||||
|
for (const channel of array) {
|
||||||
|
client.on('channel', console.log)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
// client.on('dragoncore:main', (data) => {
|
||||||
|
// console.log(data)
|
||||||
|
// })
|
||||||
|
})
|
||||||
|
client.on('custom_payload', (data) => {
|
||||||
|
console.log('custom_payload' + JSON.stringify(data))
|
||||||
|
})
|
||||||
client.on('error', (error) => {
|
client.on('error', (error) => {
|
||||||
console.log("Client Error", error)
|
console.log("Client Error", error)
|
||||||
})
|
})
|
||||||
|
|||||||
5
packages/client/start.sh
Executable file
5
packages/client/start.sh
Executable file
@@ -0,0 +1,5 @@
|
|||||||
|
while :; do
|
||||||
|
yarn emp
|
||||||
|
echo 进程退出 休眠120秒!
|
||||||
|
sleep 120
|
||||||
|
done
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/common",
|
"name": "@ccms/common",
|
||||||
"version": "0.9.8",
|
"version": "0.19.0",
|
||||||
"description": "MiaoScript api package",
|
"description": "MiaoScript api package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -19,11 +19,11 @@
|
|||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@ccms/nashorn": "^0.9.8",
|
"@ccms/nashorn": "^0.19.0",
|
||||||
"@javatypes/jdk": "^0.0.3",
|
"@javatypes/jdk": "^0.0.3",
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^4.0.3"
|
"typescript": "^4.5.5"
|
||||||
},
|
},
|
||||||
"gitHead": "562e2d00175c9d3a99c8b672aa07e6d92706a027"
|
"gitHead": "562e2d00175c9d3a99c8b672aa07e6d92706a027"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ interface RequestConfig {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function request(config: RequestConfig) {
|
function request(config: RequestConfig) {
|
||||||
// @ts-ignore
|
// @ts-ignore XMLHttpRequest class only exist nashorn polyfill
|
||||||
let xhr = new XMLHttpRequest()
|
let xhr = new XMLHttpRequest()
|
||||||
xhr.open(config.method, config.url, false)
|
xhr.open(config.method, config.url, false)
|
||||||
for (const header in config.headers) {
|
for (const header in config.headers) {
|
||||||
@@ -44,6 +44,7 @@ function request(config: RequestConfig) {
|
|||||||
if (xhr.getResponseHeader("Content-Type").indexOf('application/json') != -1) {
|
if (xhr.getResponseHeader("Content-Type").indexOf('application/json') != -1) {
|
||||||
xhr.responseType = "json"
|
xhr.responseType = "json"
|
||||||
}
|
}
|
||||||
|
// @ts-ignore get only exist nashorn polyfill
|
||||||
return xhr.get()
|
return xhr.get()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,14 +1,15 @@
|
|||||||
/// <reference types="@javatypes/jdk" />
|
/// <reference types="@javatypes/jdk" />
|
||||||
|
|
||||||
|
const JavaClass = Java.type('java.lang.Class')
|
||||||
|
const JavaObject = Java.type('java.lang.Object')
|
||||||
|
const NoSuchFieldException = Java.type('java.lang.NoSuchFieldException')
|
||||||
|
const fieldCache = new Map<string, java.lang.reflect.Field>()
|
||||||
|
const methodCache = new Map<string, java.lang.reflect.Method>()
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 反射工具类
|
* 反射工具类
|
||||||
* Created by MiaoWoo on 2017/2/9 0009.
|
* Created by MiaoWoo on 2017/2/9 0009.
|
||||||
*/
|
*/
|
||||||
const JavaClass = Java.type('java.lang.Class')
|
|
||||||
const JavaObject = Java.type('java.lang.Object')
|
|
||||||
const NoSuchFieldException = Java.type('java.lang.NoSuchFieldException')
|
|
||||||
const methodCache = []
|
|
||||||
|
|
||||||
class Reflect {
|
class Reflect {
|
||||||
private obj: java.lang.Object
|
private obj: java.lang.Object
|
||||||
private class: java.lang.Class<any>
|
private class: java.lang.Class<any>
|
||||||
@@ -34,15 +35,26 @@ class Reflect {
|
|||||||
return Java.from(declaredMethods(this.class))
|
return Java.from(declaredMethods(this.class))
|
||||||
}
|
}
|
||||||
|
|
||||||
field(name: string | java.lang.String): Reflect {
|
field(nameOrIndex: string | java.lang.String | number, declared = false): java.lang.reflect.Field {
|
||||||
try {
|
if (nameOrIndex == undefined || nameOrIndex == null) throw new Error(`reflect field name can't be ${nameOrIndex} from ${this.class.getName()}!`)
|
||||||
// Try getting a public field
|
let key = this.class.getName() + ':' + nameOrIndex + ':' + declared
|
||||||
let field = this.class.getField(name)
|
if (fieldCache.has(key)) {
|
||||||
return on(field.get(this.obj))
|
return fieldCache.get(key)
|
||||||
} catch (ex) {
|
|
||||||
// Try again, getting a non-public field
|
|
||||||
return on(accessible(declaredField(this.class, name)).get(this.obj))
|
|
||||||
}
|
}
|
||||||
|
let field = null
|
||||||
|
if (typeof nameOrIndex == "number") {
|
||||||
|
field = this.fields(declared)[nameOrIndex]
|
||||||
|
} else {
|
||||||
|
try {
|
||||||
|
// Try getting a public field
|
||||||
|
field = this.class.getField(nameOrIndex)
|
||||||
|
} catch (ex: any) {
|
||||||
|
// Try again, getting a non-public field
|
||||||
|
field = declaredField(this.class, nameOrIndex)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!field) throw new Error(`can't reflect field ${typeof nameOrIndex == "number" ? 'index' : 'name'} ${nameOrIndex} from ${this.class.getName()}!`)
|
||||||
|
return accessible(field)
|
||||||
}
|
}
|
||||||
|
|
||||||
fields(declared = false): java.lang.reflect.Field[] {
|
fields(declared = false): java.lang.reflect.Field[] {
|
||||||
@@ -50,7 +62,7 @@ class Reflect {
|
|||||||
}
|
}
|
||||||
|
|
||||||
values(declared = false) {
|
values(declared = false) {
|
||||||
return this.fields(declared).reduce((cache, field) => { return cache[field.getName()] = this.field(field.getName()).get() }, {}) as any
|
return this.fields(declared).reduce((cache, field) => { return cache[field.getName()] = this.get(field.getName()).get() }, {}) as any
|
||||||
}
|
}
|
||||||
|
|
||||||
call(...args: any[]): Reflect {
|
call(...args: any[]): Reflect {
|
||||||
@@ -64,17 +76,12 @@ class Reflect {
|
|||||||
get(index: number, declared?: boolean): Reflect
|
get(index: number, declared?: boolean): Reflect
|
||||||
get(prop: string): Reflect
|
get(prop: string): Reflect
|
||||||
get(param?: string | number, declared: boolean = true): Reflect | any {
|
get(param?: string | number, declared: boolean = true): Reflect | any {
|
||||||
if (param == undefined || param == null) return this.obj
|
if (arguments.length === 0) return this.obj
|
||||||
if (typeof param == "number") {
|
return on(this.field(param, declared).get(this.obj))
|
||||||
return on(accessible(this.fields(declared)[param]).get(this.obj))
|
|
||||||
}
|
|
||||||
if (typeof param == "string") {
|
|
||||||
return this.field(param)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
set(name: any, value: any): Reflect {
|
set(param: string | number, value: any, declared: boolean = true): Reflect {
|
||||||
accessible(declaredField(this.class, name)).set(this.obj, value)
|
this.field(param, declared).set(this.obj, value)
|
||||||
return this
|
return this
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -106,10 +113,10 @@ function declaredConstructor(clazz, param) {
|
|||||||
let constructor
|
let constructor
|
||||||
try {
|
try {
|
||||||
constructor = clazz.getDeclaredConstructor(types(param))
|
constructor = clazz.getDeclaredConstructor(types(param))
|
||||||
} catch (ex) {
|
} catch (ex: any) {
|
||||||
try {
|
try {
|
||||||
constructor = clazz.getDeclaredConstructor(types(param, true))
|
constructor = clazz.getDeclaredConstructor(types(param, true))
|
||||||
} catch (ex) {
|
} catch (ex: any) {
|
||||||
constructor = clazz.getDeclaredConstructors()[0]
|
constructor = clazz.getDeclaredConstructors()[0]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -125,7 +132,7 @@ function declaredField(clazz: java.lang.Class<any>, name: string | java.lang.Str
|
|||||||
try {
|
try {
|
||||||
field = target.getDeclaredField(name)
|
field = target.getDeclaredField(name)
|
||||||
if (field !== null) { break }
|
if (field !== null) { break }
|
||||||
} catch (e) {
|
} catch (error: any) {
|
||||||
if (target === undefined) { break }
|
if (target === undefined) { break }
|
||||||
target = target.getSuperclass()
|
target = target.getSuperclass()
|
||||||
}
|
}
|
||||||
@@ -136,64 +143,43 @@ function declaredField(clazz: java.lang.Class<any>, name: string | java.lang.Str
|
|||||||
return field
|
return field
|
||||||
}
|
}
|
||||||
|
|
||||||
function declaredMethod(clazz: java.lang.Class<any>, name: string, ...clazzs: java.lang.Class<any>[]): java.lang.reflect.Method {
|
function declaredMethod(clazz: java.lang.Class<any>, nameOrIndex: string | number, ...clazzs: java.lang.Class<any>[]): java.lang.reflect.Method {
|
||||||
let key = clazz.getName() + '.' + name + ':' + (clazzs || []).join(':')
|
let key = clazz.getName() + '.' + nameOrIndex + ':' + (clazzs || []).map(c => c.getName()).join(':')
|
||||||
if (!methodCache[key]) {
|
if (methodCache.has(key)) { return methodCache.get(key) }
|
||||||
|
if (typeof nameOrIndex === "number") {
|
||||||
|
methodCache.set(key, declaredMethods(clazz)[nameOrIndex])
|
||||||
|
} else {
|
||||||
try {
|
try {
|
||||||
// @ts-ignore
|
methodCache.set(key, clazz.getMethod(nameOrIndex, clazzs as any))
|
||||||
methodCache[key] = clazz.getMethod(name, clazzs)
|
} catch (ex: any) {
|
||||||
} catch (ex) {
|
|
||||||
try {
|
try {
|
||||||
methodCache[key] = clazz.getDeclaredMethod(name, clazzs as any)
|
methodCache.set(key, clazz.getDeclaredMethod(nameOrIndex, clazzs as any))
|
||||||
} catch (ex) {
|
} catch (ex: any) {
|
||||||
for (const m of Java.from(declaredMethods(clazz))) {
|
for (const m of Java.from(declaredMethods(clazz))) {
|
||||||
if (m.getName() == name) {
|
if (m.getName() == nameOrIndex) {
|
||||||
methodCache[key] = m
|
methodCache.set(key, m)
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return methodCache[key]
|
if (!methodCache.has(key)) throw new Error(`can't reflect method ${typeof nameOrIndex == "number" ? 'index' : 'name'} ${nameOrIndex} from ${clazz.getName()}!`)
|
||||||
|
return methodCache.get(key)
|
||||||
}
|
}
|
||||||
|
|
||||||
function declaredMethods(clazz: java.lang.Class<any>) {
|
function declaredMethods(clazz: java.lang.Class<any>) {
|
||||||
return clazz.getDeclaredMethods()
|
return clazz.getDeclaredMethods()
|
||||||
}
|
}
|
||||||
|
|
||||||
let classMethodsCache: any[] = []
|
|
||||||
|
|
||||||
function mapToObject(javaObj) {
|
function mapToObject(javaObj) {
|
||||||
if (!javaObj || !javaObj.class) { throw new TypeError(`参数 ${javaObj} 不是一个Java对象!`) }
|
if (!Java.isJavaObject(javaObj)) { throw new TypeError(`参数 ${javaObj} 不是一个Java对象!`) }
|
||||||
let target = {}
|
let target = Proxy.newProxy(javaObj, {
|
||||||
getJavaObjectMethods(javaObj).forEach(t => mapMethod(target, javaObj, t))
|
apply: (target, name, args) => { return args ? javaObj[name](args) : javaObj[name]() }
|
||||||
|
})
|
||||||
return target
|
return target
|
||||||
}
|
}
|
||||||
|
|
||||||
function getJavaObjectMethods(javaObj) {
|
|
||||||
let className = javaObj.class.name
|
|
||||||
if (!classMethodsCache[className]) {
|
|
||||||
let names: any[] = []
|
|
||||||
let methods = javaObj.class.methods
|
|
||||||
for (let i in methods) {
|
|
||||||
names.push(methods[i].name)
|
|
||||||
}
|
|
||||||
classMethodsCache[className] = names
|
|
||||||
}
|
|
||||||
return classMethodsCache[className]
|
|
||||||
}
|
|
||||||
|
|
||||||
function mapMethod(target, source, name) {
|
|
||||||
target[name] = function __SimpleDynamicMethod__(...args) {
|
|
||||||
if (args.length > 0) {
|
|
||||||
return source[name](args)
|
|
||||||
} else {
|
|
||||||
return source[name]()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function on(obj) {
|
function on(obj) {
|
||||||
// if (!obj || !obj.class) { throw new TypeError(`参数 ${obj} 不是一个Java对象!`) }
|
// if (!obj || !obj.class) { throw new TypeError(`参数 ${obj} 不是一个Java对象!`) }
|
||||||
return new Reflect(obj)
|
return new Reflect(obj)
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/compile",
|
"name": "@ccms/compile",
|
||||||
"version": "0.9.4",
|
"version": "0.19.0",
|
||||||
"description": "MiaoScript compile package",
|
"description": "MiaoScript compile package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -21,6 +21,6 @@
|
|||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^4.0.3"
|
"typescript": "^4.5.5"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/container",
|
"name": "@ccms/container",
|
||||||
"version": "0.9.8",
|
"version": "0.19.0",
|
||||||
"description": "MiaoScript container package",
|
"description": "MiaoScript container package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -19,13 +19,13 @@
|
|||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@ccms/nashorn": "^0.9.8",
|
"@ccms/nashorn": "^0.19.0",
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^4.0.3"
|
"typescript": "^4.5.5"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"inversify": "^5.0.1",
|
"inversify": "^6.0.1",
|
||||||
"inversify-binding-decorators": "^4.0.0"
|
"inversify-binding-decorators": "^4.0.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -37,8 +37,8 @@ export const provideSingletonNamed = (identifier: interfaces.ServiceIdentifier<a
|
|||||||
*/
|
*/
|
||||||
export const JavaClass = (className: string) => {
|
export const JavaClass = (className: string) => {
|
||||||
return function (target: object, propertyKey: string, index?: number) {
|
return function (target: object, propertyKey: string, index?: number) {
|
||||||
try { target[propertyKey] = Java.type(className).class; return } catch (error) { }
|
try { target[propertyKey] = Java.type(className).class; return } catch (error: any) { }
|
||||||
try { target[propertyKey] = base.getClass(className); return } catch (error) { }
|
try { target[propertyKey] = base.getClass(className); return } catch (error: any) { }
|
||||||
console.warn('JavaClass', className, 'Inject target', target.constructor.name, 'propertyKey', propertyKey, 'failed!')
|
console.warn('JavaClass', className, 'Inject target', target.constructor.name, 'propertyKey', propertyKey, 'failed!')
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -49,8 +49,8 @@ export const JavaClass = (className: string) => {
|
|||||||
*/
|
*/
|
||||||
export const JSClass = (className: string) => {
|
export const JSClass = (className: string) => {
|
||||||
return function (target: object, propertyKey: string, index?: number) {
|
return function (target: object, propertyKey: string, index?: number) {
|
||||||
try { target[propertyKey] = Java.type(className); return } catch (error) { }
|
try { target[propertyKey] = Java.type(className); return } catch (error: any) { }
|
||||||
try { target[propertyKey] = base.getClass(className).static; return } catch (error) { }
|
try { target[propertyKey] = base.getClass(className).static; return } catch (error: any) { }
|
||||||
console.warn('JSClass', className, 'Inject target', target.constructor.name, 'propertyKey', propertyKey, 'failed!')
|
console.warn('JSClass', className, 'Inject target', target.constructor.name, 'propertyKey', propertyKey, 'failed!')
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -66,7 +66,7 @@ export const Autowired = (className?: any) => {
|
|||||||
return inject(className)(target, propertyKey, index)
|
return inject(className)(target, propertyKey, index)
|
||||||
}
|
}
|
||||||
let type = Reflect.getMetadata('design:type', target, propertyKey)
|
let type = Reflect.getMetadata('design:type', target, propertyKey)
|
||||||
if (type && type !== Object && Java.isJavaObject(type)) {
|
if (type && type !== Object && !Java.isJavaObject(type)) {
|
||||||
inject(type)(target, propertyKey, index)
|
inject(type)(target, propertyKey, index)
|
||||||
named(className || propertyKey)(target, propertyKey, index)
|
named(className || propertyKey)(target, propertyKey, index)
|
||||||
} else if (container.isBound(ioc.Autowired)) {
|
} else if (container.isBound(ioc.Autowired)) {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/core",
|
"name": "@ccms/core",
|
||||||
"version": "0.9.8",
|
"version": "0.20.0-alpha.0",
|
||||||
"description": "MiaoScript api package",
|
"description": "MiaoScript api package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -21,11 +21,11 @@
|
|||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^4.0.3"
|
"typescript": "^4.5.5"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ccms/api": "^0.9.8",
|
"@ccms/api": "^0.20.0-alpha.0",
|
||||||
"@ccms/container": "^0.9.8"
|
"@ccms/container": "^0.19.0"
|
||||||
},
|
},
|
||||||
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
|
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,44 +1,38 @@
|
|||||||
let containerStartTime = Date.now()
|
let containerStartTime = Date.now()
|
||||||
console.i18n("ms.core.ioc.initialize", { scope: global.scope })
|
console.i18n("ms.core.ioc.initialize", { scope: global.scope })
|
||||||
import { plugin, server, task, constants } from '@ccms/api'
|
import { plugin, server, task, constants } from '@ccms/api'
|
||||||
import { DefaultContainer as container, inject, provideSingleton, ContainerInstance, buildProviderModule } from '@ccms/container'
|
import { DefaultContainer as container, provideSingleton, ContainerInstance, buildProviderModule, Autowired } from '@ccms/container'
|
||||||
console.i18n("ms.core.ioc.completed", { scope: global.scope, time: (Date.now() - containerStartTime) / 1000 })
|
console.i18n("ms.core.ioc.completed", { scope: global.scope, time: (Date.now() - containerStartTime) / 1000 })
|
||||||
import http from '@ccms/common/dist/http'
|
import http from '@ccms/common/dist/http'
|
||||||
|
|
||||||
@provideSingleton(MiaoScriptCore)
|
@provideSingleton(MiaoScriptCore)
|
||||||
class MiaoScriptCore {
|
class MiaoScriptCore {
|
||||||
@inject(server.Console)
|
@Autowired(server.Console)
|
||||||
private Console: Console
|
private Console: Console
|
||||||
@inject(task.TaskManager)
|
@Autowired(plugin.PluginFolder)
|
||||||
private taskManager: task.TaskManager
|
|
||||||
@inject(plugin.PluginFolder)
|
|
||||||
private pluginFolder: string
|
private pluginFolder: string
|
||||||
@inject(plugin.PluginManager)
|
@Autowired()
|
||||||
|
private taskManager: task.TaskManager
|
||||||
|
@Autowired()
|
||||||
private pluginManager: plugin.PluginManager
|
private pluginManager: plugin.PluginManager
|
||||||
|
|
||||||
enable() {
|
enable() {
|
||||||
|
process.emit('core.before.enable')
|
||||||
this.loadServerConsole()
|
this.loadServerConsole()
|
||||||
this.loadTaskFunction()
|
|
||||||
global.level = "TRACE"
|
|
||||||
this.loadPlugins()
|
this.loadPlugins()
|
||||||
|
process.emit('core.after.enable')
|
||||||
return () => this.disable()
|
return () => this.disable()
|
||||||
}
|
}
|
||||||
|
|
||||||
loadServerConsole() {
|
loadServerConsole() {
|
||||||
|
process.emit('core.before.load.console')
|
||||||
//@ts-ignore
|
//@ts-ignore
|
||||||
global.setGlobal('console', new this.Console(), { writable: false, configurable: false })
|
global.setGlobal('console', new this.Console(), { writable: false, configurable: false })
|
||||||
}
|
process.emit('core.after.load.console')
|
||||||
|
|
||||||
loadTaskFunction() {
|
|
||||||
global.setGlobal('setTimeout', (func: Function, tick: number, ...args: any[]) => {
|
|
||||||
return this.taskManager.create(func).later(tick).submit(...args)
|
|
||||||
}, { writable: false, configurable: false })
|
|
||||||
global.setGlobal('setInterval', (func: Function, tick: number, ...args: any[]) => {
|
|
||||||
return this.taskManager.create(func).timer(tick).submit(...args)
|
|
||||||
}, { writable: false, configurable: false })
|
|
||||||
}
|
}
|
||||||
|
|
||||||
loadPlugins() {
|
loadPlugins() {
|
||||||
|
process.emit('core.before.load.plugins')
|
||||||
let loadPluginStartTime = new Date().getTime()
|
let loadPluginStartTime = new Date().getTime()
|
||||||
console.i18n("ms.core.plugin.initialize")
|
console.i18n("ms.core.plugin.initialize")
|
||||||
this.pluginManager.scan(this.pluginFolder)
|
this.pluginManager.scan(this.pluginFolder)
|
||||||
@@ -46,15 +40,25 @@ class MiaoScriptCore {
|
|||||||
this.pluginManager.load(this.pluginManager.getPlugins())
|
this.pluginManager.load(this.pluginManager.getPlugins())
|
||||||
this.pluginManager.enable(this.pluginManager.getPlugins())
|
this.pluginManager.enable(this.pluginManager.getPlugins())
|
||||||
console.i18n("ms.core.plugin.completed", { time: (new Date().getTime() - loadPluginStartTime) / 1000 })
|
console.i18n("ms.core.plugin.completed", { time: (new Date().getTime() - loadPluginStartTime) / 1000 })
|
||||||
|
process.emit('core.after.load.plugins')
|
||||||
}
|
}
|
||||||
|
|
||||||
disable() {
|
disable() {
|
||||||
|
process.emit('core.before.disable')
|
||||||
let disableStartTime = Date.now()
|
let disableStartTime = Date.now()
|
||||||
console.i18n("ms.core.engine.disable")
|
console.i18n("ms.core.engine.disable")
|
||||||
this.pluginManager.disable(this.pluginManager.getPlugins())
|
this.pluginManager.disable(this.pluginManager.getPlugins())
|
||||||
this.taskManager.disable()
|
this.taskManager.disable()
|
||||||
|
process.emit('core.after.disable')
|
||||||
|
loadCoreScript('exit')
|
||||||
|
process.emit('core.before.exit')
|
||||||
process.exit(0)
|
process.exit(0)
|
||||||
console.i18n("ms.core.engine.disable.finish", { version: 'v' + global.ScriptEngineVersion, time: (new Date().getTime() - disableStartTime) / 1000 })
|
console.i18n("ms.core.engine.disable.finish", {
|
||||||
|
loader: base.version,
|
||||||
|
version: 'v' + global.ScriptEngineVersion,
|
||||||
|
time: (new Date().getTime() - disableStartTime) / 1000
|
||||||
|
})
|
||||||
|
process.emit('core.after.exit')
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -62,54 +66,89 @@ function detectServer(): constants.ServerType {
|
|||||||
try {
|
try {
|
||||||
Java.type("org.bukkit.Bukkit")
|
Java.type("org.bukkit.Bukkit")
|
||||||
return constants.ServerType.Bukkit
|
return constants.ServerType.Bukkit
|
||||||
} catch (ex) {
|
} catch (ex: any) {
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
Java.type("org.spongepowered.api.Sponge")
|
Java.type("org.spongepowered.api.Sponge")
|
||||||
return constants.ServerType.Sponge
|
return constants.ServerType.Sponge
|
||||||
} catch (ex) {
|
} catch (ex: any) {
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
Java.type("cn.nukkit.Nukkit")
|
Java.type("cn.nukkit.Nukkit")
|
||||||
return constants.ServerType.Nukkit
|
return constants.ServerType.Nukkit
|
||||||
} catch (ex) {
|
} catch (ex: any) {
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
Java.type("net.md_5.bungee.api.ProxyServer")
|
Java.type("net.md_5.bungee.api.ProxyServer")
|
||||||
return constants.ServerType.Bungee
|
return constants.ServerType.Bungee
|
||||||
} catch (ex) {
|
} catch (ex: any) {
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
Java.type("org.springframework.boot.SpringApplication")
|
Java.type("org.springframework.boot.SpringApplication")
|
||||||
return constants.ServerType.Spring
|
return constants.ServerType.Spring
|
||||||
} catch (ex) {
|
} catch (ex: any) {
|
||||||
}
|
}
|
||||||
throw Error('Unknow Server Type...')
|
throw Error('Unknow Server Type...')
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function loadCoreScript(name) {
|
||||||
|
try {
|
||||||
|
let scriptname = name + (global.debug ? '-debug' : '')
|
||||||
|
engineLoad({
|
||||||
|
script: http.get(`https://ms.yumc.pw/api/plugin/download/name/${scriptname}`),
|
||||||
|
name: `core/${scriptname}.js`
|
||||||
|
})
|
||||||
|
} catch (error: any) {
|
||||||
|
if (global.debug) {
|
||||||
|
console.debug(error)
|
||||||
|
console.ex(error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function initialize() {
|
function initialize() {
|
||||||
|
process.emit('core.before.initialize')
|
||||||
|
global.ScriptSlowExecuteTime = 50
|
||||||
global.ScriptEngineVersion = require('../package.json').version
|
global.ScriptEngineVersion = require('../package.json').version
|
||||||
try { engineLoad({ script: http.get("http://ms.yumc.pw/api/plugin/download/name/initialize"), name: 'core/initialize.js' }) } catch (error) { console.debug(error) }
|
global.setGlobal('loadCoreScript', loadCoreScript)
|
||||||
|
loadCoreScript('initialize')
|
||||||
try {
|
try {
|
||||||
let corePackageStartTime = new Date().getTime()
|
let corePackageStartTime = new Date().getTime()
|
||||||
container.bind(ContainerInstance).toConstantValue(container)
|
container.bind(ContainerInstance).toConstantValue(container)
|
||||||
container.bind(plugin.PluginInstance).toConstantValue(base.getInstance())
|
container.bind(plugin.PluginInstance).toConstantValue(base.getInstance())
|
||||||
container.bind(plugin.PluginFolder).toConstantValue('plugins')
|
container.bind(plugin.PluginFolder).toConstantValue('plugins')
|
||||||
let type = detectServer()
|
let type = detectServer()
|
||||||
|
|
||||||
|
process.emit('core.before.initialize.detect')
|
||||||
console.i18n("ms.core.initialize.detect", { scope: global.scope, type })
|
console.i18n("ms.core.initialize.detect", { scope: global.scope, type })
|
||||||
container.bind(server.ServerType).toConstantValue(type)
|
container.bind(server.ServerType).toConstantValue(type)
|
||||||
container.bind(server.ServerChecker).toSelf().inSingletonScope()
|
container.bind(server.ServerChecker).toSelf().inSingletonScope()
|
||||||
|
container.bind(server.NativePluginManager).toSelf().inSingletonScope()
|
||||||
|
process.emit('core.after.initialize.detect')
|
||||||
|
|
||||||
|
process.emit('core.before.package.initialize')
|
||||||
console.i18n("ms.core.package.initialize", { scope: global.scope, type })
|
console.i18n("ms.core.package.initialize", { scope: global.scope, type })
|
||||||
require(`${global.scope}/${type}`).default(container)
|
require(`${global.scope}/${type}`).default(container)
|
||||||
require(`${global.scope}/plugin`)
|
require(`${global.scope}/plugin`)
|
||||||
container.load(buildProviderModule())
|
container.load(buildProviderModule())
|
||||||
console.i18n("ms.core.package.completed", { scope: global.scope, type, time: (Date.now() - corePackageStartTime) / 1000 })
|
console.i18n("ms.core.package.completed", { scope: global.scope, type, time: (Date.now() - corePackageStartTime) / 1000 })
|
||||||
|
process.emit('core.after.package.initialize')
|
||||||
|
|
||||||
let disable = container.get<MiaoScriptCore>(MiaoScriptCore).enable()
|
let disable = container.get<MiaoScriptCore>(MiaoScriptCore).enable()
|
||||||
console.i18n("ms.core.engine.completed", { version: 'v' + global.ScriptEngineVersion, time: (Date.now() - global.ScriptEngineStartTime) / 1000 })
|
console.i18n("ms.core.engine.completed", {
|
||||||
|
loader: base.version,
|
||||||
|
version: 'v' + global.ScriptEngineVersion,
|
||||||
|
time: (Date.now() - global.ScriptEngineStartTime) / 1000
|
||||||
|
})
|
||||||
|
process.emit('core.after.initialize')
|
||||||
return disable
|
return disable
|
||||||
} catch (error) {
|
} catch (error: any) {
|
||||||
console.i18n("ms.core.initialize.error", { error })
|
if (console.console) {
|
||||||
console.ex(error)
|
console.i18n("ms.core.initialize.error", { error })
|
||||||
|
console.ex(error)
|
||||||
|
} else {
|
||||||
|
error.printStackTrace()
|
||||||
|
}
|
||||||
return () => console.i18n('ms.core.engine.disable.abnormal')
|
return () => console.i18n('ms.core.engine.disable.abnormal')
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/database",
|
"name": "@ccms/database",
|
||||||
"version": "0.9.8",
|
"version": "0.20.0-alpha.0",
|
||||||
"description": "MiaoScript database package",
|
"description": "MiaoScript database package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -22,10 +22,10 @@
|
|||||||
"@javatypes/spring-jdbc": "^0.0.3",
|
"@javatypes/spring-jdbc": "^0.0.3",
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^4.0.3"
|
"typescript": "^4.5.5"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ccms/api": "^0.9.8",
|
"@ccms/api": "^0.20.0-alpha.0",
|
||||||
"@ccms/container": "^0.9.8"
|
"@ccms/container": "^0.19.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ export class DataBaseManager {
|
|||||||
this.beanFactory = this.instance.getAutowireCapableBeanFactory()
|
this.beanFactory = this.instance.getAutowireCapableBeanFactory()
|
||||||
let mainDatasource = this.beanFactory.getBean(Packages.javax.sql.DataSource.class)
|
let mainDatasource = this.beanFactory.getBean(Packages.javax.sql.DataSource.class)
|
||||||
this.mainDatabase = new DataBase({ url: mainDatasource })
|
this.mainDatabase = new DataBase({ url: mainDatasource })
|
||||||
} catch (error) {
|
} catch (error: any) {
|
||||||
console.ex(error)
|
console.ex(error)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
ms.i18n.completed: "Internationalization component initialization completed. Current Language: English"
|
ms.i18n.completed: "Internationalization component initialization completed. Current Language: English"
|
||||||
ms.ployfill.initialize: "Initialization Java Nashorn ployfill. Please wait..."
|
ms.polyfill.initialize: "Initialization Java Nashorn polyfill. Please wait..."
|
||||||
ms.ployfill.completed: "Java Nashorn ployfill loading completed... Cost ({time}s)!"
|
ms.polyfill.completed: "Java Nashorn polyfill loading completed... Cost ({time}s)!"
|
||||||
|
|
||||||
ms.core.ioc.initialize: "Initialization MiaoScript IOC Container {scope}/container. Please wait..."
|
ms.core.ioc.initialize: "Initialization MiaoScript IOC Container {scope}/container. Please wait..."
|
||||||
ms.core.ioc.completed: "MiaoScript IOC Container {scope}/container loading completed({time}s)!"
|
ms.core.ioc.completed: "MiaoScript IOC Container {scope}/container loading completed({time}s)!"
|
||||||
@@ -12,6 +12,7 @@ ms.core.plugin.initialize: "Initialization MiaoScript Plugin System. Please wait
|
|||||||
ms.core.plugin.completed: "MiaoScript Plugin System loading completed({time}s)!"
|
ms.core.plugin.completed: "MiaoScript Plugin System loading completed({time}s)!"
|
||||||
ms.core.engine.completed: "MiaoScript ScriptEngine loading completed... Done({time}s)!"
|
ms.core.engine.completed: "MiaoScript ScriptEngine loading completed... Done({time}s)!"
|
||||||
ms.core.engine.disable: "Disable MiaoScript Engine..."
|
ms.core.engine.disable: "Disable MiaoScript Engine..."
|
||||||
|
ms.core.engine.disable.finish: "MiaoScript framework {loader} engine {version} 关闭完成... 耗时({time}s)!"
|
||||||
ms.core.engine.disable.abnormal: "abnormal Initialization MiaoScript Engine. Skip disable step..."
|
ms.core.engine.disable.abnormal: "abnormal Initialization MiaoScript Engine. Skip disable step..."
|
||||||
|
|
||||||
ms.api.event.resource.not.found: "Can't Mapping Event Because not found Resources {resource}!"
|
ms.api.event.resource.not.found: "Can't Mapping Event Because not found Resources {resource}!"
|
||||||
@@ -21,17 +22,22 @@ ms.api.event.not.found: "§6Plugin §b{name} §6register {event} error. event no
|
|||||||
ms.api.event.execute.slow: "§cWARN! §6Plugin §b{name} §6execute §d{event} §6evnet §ccost §4{cost}ms !"
|
ms.api.event.execute.slow: "§cWARN! §6Plugin §b{name} §6execute §d{event} §6evnet §ccost §4{cost}ms !"
|
||||||
ms.api.event.execute.error: "§6Plugin §b{name} §6execute §d{event} §6event error §4{ex}"
|
ms.api.event.execute.error: "§6Plugin §b{name} §6execute §d{event} §6event error §4{ex}"
|
||||||
ms.api.event.listen.plugin.name.empty: "Plugin name can't be empty!"
|
ms.api.event.listen.plugin.name.empty: "Plugin name can't be empty!"
|
||||||
ms.api.event.register: "[{name}] register event {event}"
|
ms.api.event.register: "[{name}] register event {event} priority {priority} ignoreCancelled {ignore}"
|
||||||
ms.api.event.unregister: "[{name}] unregister event {event}"
|
ms.api.event.unregister: "[{name}] unregister event {event}"
|
||||||
|
|
||||||
ms.api.command.register.input.error: "CommandExec Must be a function... Input: {exec}"
|
ms.api.command.register.input.error: "CommandExec Must be a function... Input: {exec}"
|
||||||
ms.api.command.register: "[{plugin}] register command {name}({cmd})..."
|
ms.api.command.register: "[{plugin}] register command {name}({cmd})..."
|
||||||
ms.api.command.unregister: "[{plugin}] unregister command {name}..."
|
ms.api.command.unregister: "[{plugin}] unregister command {name}..."
|
||||||
|
ms.api.command.execute.slow: "§cWarn. §6Player §a{player} §6exec §b{plugin} §6Plugin §d{command} {args} §6Command §cCost §4{cost}ms !"
|
||||||
ms.api.command.execute.error: "§6Player {player} §6exec §b{plugin} §6Plugin Command §d{command} {args} §6error §4{ex}"
|
ms.api.command.execute.error: "§6Player {player} §6exec §b{plugin} §6Plugin Command §d{command} {args} §6error §4{ex}"
|
||||||
|
ms.api.command.tab.completer.slow: "§cWarn. §6Player §a{player} §6exec §b{plugin} §6Plugin §d{command} {args} §6TabComplete §cCost §4{cost}ms !"
|
||||||
ms.api.command.tab.completer.error: "§6Player {player} §6exec §b{plugin} §6Plugin TabComplete §d{command} {args} §6error §4{ex}"
|
ms.api.command.tab.completer.error: "§6Player {player} §6exec §b{plugin} §6Plugin TabComplete §d{command} {args} §6error §4{ex}"
|
||||||
|
|
||||||
ms.plugin.initialize: "Initialization MiaoScript Plugin System: Plugin: {plugin} Loader: {loader}..."
|
ms.plugin.initialize: "Initialization MiaoScript Plugin System: Plugin: {plugin} Loader: {loader}..."
|
||||||
ms.plugin.event.map: "Total {count} {type} Event Mapping Complate..."
|
ms.plugin.event.map: "Total {count} {type} Event Mapping Complate..."
|
||||||
ms.plugin.manager.scan: "Scanning Plugins in {folder} ..."
|
ms.plugin.event.map.error: "Mapping {type} Event Failed. Error: {error}"
|
||||||
|
ms.plugin.manager.scan: "Scanner {scanner} Scanning Plugins in {folder} ..."
|
||||||
|
ms.plugin.manager.scan.finish: "Scanner {scanner} Found {size} Plugins in {folder} Start Build..."
|
||||||
ms.plugin.manager.initialize.error: "§6Plugin §b{name} §6initialize error §4{ex}"
|
ms.plugin.manager.initialize.error: "§6Plugin §b{name} §6initialize error §4{ex}"
|
||||||
ms.plugin.manager.stage: "{stage} {plugin} version {version} by {author}"
|
ms.plugin.manager.stage: "{stage} {plugin} version {version} by {author}"
|
||||||
ms.plugin.manager.stage.exec: "[{plugin}] Exec {name} Stage {stage} When servers is {servers}..."
|
ms.plugin.manager.stage.exec: "[{plugin}] Exec {name} Stage {stage} When servers is {servers}..."
|
||||||
@@ -39,6 +45,7 @@ ms.plugin.manager.stage.exec.error: "§6Plugin §b{plugin} §6exec §d{executor}
|
|||||||
ms.plugin.manager.stage.load: "Loading"
|
ms.plugin.manager.stage.load: "Loading"
|
||||||
ms.plugin.manager.stage.enable: "Enabling"
|
ms.plugin.manager.stage.enable: "Enabling"
|
||||||
ms.plugin.manager.stage.disable: "Disabling"
|
ms.plugin.manager.stage.disable: "Disabling"
|
||||||
|
ms.plugin.manager.build: "Plugin {name}({version}) Build Finish source: {file}({scanner}) loader: {loader} Cost: {cost}s."
|
||||||
ms.plugin.manager.build.error: "§6Load Plugin From §b{file} §6failed. §4Error: §c{error}"
|
ms.plugin.manager.build.error: "§6Load Plugin From §b{file} §6failed. §4Error: §c{error}"
|
||||||
ms.plugin.manager.build.update: "Auto Update Plugin {name} ..."
|
ms.plugin.manager.build.update: "Auto Update Plugin {name} ..."
|
||||||
ms.plugin.manager.build.not.extends: "§4Found error plugin §b{source} §4it's not extends interfaces.Plugin, the plugin will be ignore!"
|
ms.plugin.manager.build.not.extends: "§4Found error plugin §b{source} §4it's not extends interfaces.Plugin, the plugin will be ignore!"
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
ms.i18n.completed: "国际化组件 初始化完成 当前语言: 简体中文"
|
ms.i18n.completed: "国际化组件 初始化完成 当前语言: 简体中文"
|
||||||
ms.ployfill.initialize: "加载 Java Nashorn 补丁. 请稍候..."
|
ms.polyfill.initialize: "加载 Java Nashorn 补丁. 请稍候..."
|
||||||
ms.ployfill.completed: "Java Nashorn 补丁 加载完成... 耗时 ({time}s)!"
|
ms.polyfill.completed: "Java Nashorn 补丁 加载完成... 耗时 ({time}s)!"
|
||||||
|
|
||||||
ms.core.ioc.initialize: "初始化 MiaoScript IOC 容器 {scope}/container. 请稍候..."
|
ms.core.ioc.initialize: "初始化 MiaoScript IOC 容器 {scope}/container. 请稍候..."
|
||||||
ms.core.ioc.completed: "MiaoScript IOC 容器 {scope}/container 加载完成 耗时({time}s)"
|
ms.core.ioc.completed: "MiaoScript IOC 容器 {scope}/container 加载完成 耗时({time}s)"
|
||||||
@@ -10,9 +10,9 @@ ms.core.package.initialize: "初始化 MiaoScript 扩展 {scope}/core {scope}/{t
|
|||||||
ms.core.package.completed: "MiaoScript 扩展 {scope}/core {scope}/{type} {scope}/plugin 加载完成 耗时({time}s)"
|
ms.core.package.completed: "MiaoScript 扩展 {scope}/core {scope}/{type} {scope}/plugin 加载完成 耗时({time}s)"
|
||||||
ms.core.plugin.initialize: "MiaoScript 开始引导插件系统. 请稍候..."
|
ms.core.plugin.initialize: "MiaoScript 开始引导插件系统. 请稍候..."
|
||||||
ms.core.plugin.completed: "MiaoScript 插件加载完毕 耗时({time}s)!"
|
ms.core.plugin.completed: "MiaoScript 插件加载完毕 耗时({time}s)!"
|
||||||
ms.core.engine.completed: "MiaoScript 脚本引擎 {version} 加载完毕... 耗时({time}s)!"
|
ms.core.engine.completed: "MiaoScript 框架 {loader} 引擎 {version} 加载完毕... 耗时({time}s)!"
|
||||||
ms.core.engine.disable: "MiaoScript 关闭脚本引擎 请稍候..."
|
ms.core.engine.disable: "MiaoScript 关闭脚本引擎 请稍候..."
|
||||||
ms.core.engine.disable.finish: "MiaoScript 脚本引擎 {version} 关闭完成... 耗时({time}s)!"
|
ms.core.engine.disable.finish: "MiaoScript 框架 {loader} 引擎 {version} 关闭完成... 耗时({time}s)!"
|
||||||
ms.core.engine.disable.abnormal: "引擎异常启动或初始化未完成 跳过关闭流程..."
|
ms.core.engine.disable.abnormal: "引擎异常启动或初始化未完成 跳过关闭流程..."
|
||||||
|
|
||||||
ms.api.event.resource.not.found: "无法映射事件 未找到资源文件 {resource}!"
|
ms.api.event.resource.not.found: "无法映射事件 未找到资源文件 {resource}!"
|
||||||
@@ -22,17 +22,22 @@ ms.api.event.not.found: "§6插件 §b{name} §6注册事件 §c{event} §6失
|
|||||||
ms.api.event.execute.slow: "§c注意! §6插件 §b{name} §6处理 §d{event} §6事件 §c耗时 §4{cost}ms !"
|
ms.api.event.execute.slow: "§c注意! §6插件 §b{name} §6处理 §d{event} §6事件 §c耗时 §4{cost}ms !"
|
||||||
ms.api.event.execute.error: "§6插件 §b{name} §6处理 §d{event} §6事件时发生异常 §4{ex}"
|
ms.api.event.execute.error: "§6插件 §b{name} §6处理 §d{event} §6事件时发生异常 §4{ex}"
|
||||||
ms.api.event.listen.plugin.name.empty: "插件名称为空 请检查传入参数!"
|
ms.api.event.listen.plugin.name.empty: "插件名称为空 请检查传入参数!"
|
||||||
ms.api.event.register: "[{name}] 注册事件 {event} => 执行器 {exec}"
|
ms.api.event.register: "[{name}] 注册事件 {event} => 执行器 {exec} 优先级 {priority} 忽略取消 {ignore}"
|
||||||
ms.api.event.unregister: "[{name}] 注销事件 {event} => 执行器 {exec}"
|
ms.api.event.unregister: "[{name}] 注销事件 {event} => 执行器 {exec}"
|
||||||
|
|
||||||
ms.api.command.register.input.error: "CommandExec 必须为一个函数... 输入: {exec}"
|
ms.api.command.register.input.error: "CommandExec 必须为一个函数... 输入: {exec}"
|
||||||
ms.api.command.register: "[{plugin}] 注册命令 {name}({cmd})..."
|
ms.api.command.register: "[{plugin}] 注册命令 {name}({cmd})..."
|
||||||
ms.api.command.unregister: "[{plugin}] 注销命令 {name}..."
|
ms.api.command.unregister: "[{plugin}] 注销命令 {name}..."
|
||||||
|
ms.api.command.execute.slow: "§c注意! §6玩家 §a{player} §6执行 §b{plugin} §6插件 §d{command} {args} §6命令 §c耗时 §4{cost}ms !"
|
||||||
ms.api.command.execute.error: "§6玩家 §a{player} §6执行 §b{plugin} §6插件 §d{command} {args} §6命令时发生异常 §4{ex}"
|
ms.api.command.execute.error: "§6玩家 §a{player} §6执行 §b{plugin} §6插件 §d{command} {args} §6命令时发生异常 §4{ex}"
|
||||||
|
ms.api.command.tab.completer.slow: "§c注意! §6玩家 §a{player} §6执行 §b{plugin} §6插件 §d{command} {args} §6补全 §c耗时 §4{cost}ms !"
|
||||||
ms.api.command.tab.completer.error: "§6玩家 §a{player} §6执行 §b{plugin} §6插件 §d{command} {args} §6补全时发生异常 §4{ex}"
|
ms.api.command.tab.completer.error: "§6玩家 §a{player} §6执行 §b{plugin} §6插件 §d{command} {args} §6补全时发生异常 §4{ex}"
|
||||||
|
|
||||||
ms.plugin.initialize: "初始化 MiaoScript 插件系统: 实例: {plugin} 加载器: {loader}..."
|
ms.plugin.initialize: "初始化 MiaoScript 插件系统: 实例: {plugin} 加载器: {loader}..."
|
||||||
ms.plugin.event.map: "总计 {count} 个 {type} 事件 映射完成..."
|
ms.plugin.event.map: "总计 {count} 个 {type} 事件 映射完成..."
|
||||||
ms.plugin.manager.scan: "扫描 {folder} 文件夹中插件..."
|
ms.plugin.event.map.error: "映射 {type} 事件 异常 将无法使用事件简称. Error: {error}"
|
||||||
|
ms.plugin.manager.scan: "扫描器 {scanner} 扫描 {folder} 中的插件..."
|
||||||
|
ms.plugin.manager.scan.finish: "扫描器 {scanner} 在 {folder} 中 发现 {size} 个插件 开始构建..."
|
||||||
ms.plugin.manager.initialize.error: "§6插件 §b{name} §6初始化错误 §4{ex}"
|
ms.plugin.manager.initialize.error: "§6插件 §b{name} §6初始化错误 §4{ex}"
|
||||||
ms.plugin.manager.stage: "{stage} {plugin} 版本 {version} 作者 {author}"
|
ms.plugin.manager.stage: "{stage} {plugin} 版本 {version} 作者 {author}"
|
||||||
ms.plugin.manager.stage.exec: "[{plugin}] 执行 {stage} 阶段函数 {name} 匹配类型 {servers}..."
|
ms.plugin.manager.stage.exec: "[{plugin}] 执行 {stage} 阶段函数 {name} 匹配类型 {servers}..."
|
||||||
@@ -40,6 +45,7 @@ ms.plugin.manager.stage.exec.error: "§6插件 §b{plugin} §6执行 §d{executo
|
|||||||
ms.plugin.manager.stage.load: "加载"
|
ms.plugin.manager.stage.load: "加载"
|
||||||
ms.plugin.manager.stage.enable: "启用"
|
ms.plugin.manager.stage.enable: "启用"
|
||||||
ms.plugin.manager.stage.disable: "关闭"
|
ms.plugin.manager.stage.disable: "关闭"
|
||||||
|
ms.plugin.manager.build: "插件 {name}({version}) 构建完成 来源: {file}({scanner}) 引导: {loader} 构建耗时: {cost}s."
|
||||||
ms.plugin.manager.build.error: "§6从文件 §b{file} §6加载插件失败 §4错误: §c{error}"
|
ms.plugin.manager.build.error: "§6从文件 §b{file} §6加载插件失败 §4错误: §c{error}"
|
||||||
ms.plugin.manager.build.update: "自动更新插件 {name} ..."
|
ms.plugin.manager.build.update: "自动更新插件 {name} ..."
|
||||||
ms.plugin.manager.build.not.extends: "§4发现错误的插件 §b{source} §4未继承接口 interfaces.Plugin, 将不会被载入到服务器!"
|
ms.plugin.manager.build.not.extends: "§4发现错误的插件 §b{source} §4未继承接口 interfaces.Plugin, 将不会被载入到服务器!"
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/i18n",
|
"name": "@ccms/i18n",
|
||||||
"version": "0.9.8",
|
"version": "0.20.0-alpha.0",
|
||||||
"description": "MiaoScript i18n package",
|
"description": "MiaoScript i18n package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -19,14 +19,14 @@
|
|||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@ccms/nashorn": "^0.9.8",
|
"@ccms/nashorn": "^0.19.0",
|
||||||
"@types/js-yaml": "^3.12.5",
|
"@types/js-yaml": "^4.0.5",
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^4.0.3"
|
"typescript": "^4.5.5"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"js-yaml": "^3.14.0"
|
"js-yaml": "^4.1.0"
|
||||||
},
|
},
|
||||||
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
|
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,13 +1,13 @@
|
|||||||
/// <reference types="@ccms/nashorn" />
|
/// <reference types="@ccms/nashorn" />
|
||||||
import * as yaml from 'js-yaml'
|
import * as yaml from 'js-yaml'
|
||||||
|
|
||||||
const File = Java.type("java.io.File");
|
const File = Java.type("java.io.File")
|
||||||
const separatorChar = File.separatorChar;
|
const separatorChar = File.separatorChar
|
||||||
type TranslateParam = { [key: string]: any }
|
type TranslateParam = { [key: string]: any }
|
||||||
|
|
||||||
declare global {
|
declare global {
|
||||||
interface Console {
|
interface Console {
|
||||||
i18n(name: string, param?: TranslateParam);
|
i18n(name: string, param?: TranslateParam)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -23,20 +23,20 @@ export class Translate {
|
|||||||
|
|
||||||
constructor(root: string | TranslateContent) {
|
constructor(root: string | TranslateContent) {
|
||||||
if (typeof root == 'string') {
|
if (typeof root == 'string') {
|
||||||
this.root = root;
|
this.root = root
|
||||||
} else {
|
} else {
|
||||||
this.langMap = root.langMap;
|
this.langMap = root.langMap
|
||||||
this.fallbackMap = root.fallbackMap || {};
|
this.fallbackMap = root.fallbackMap || {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
translate(name: string, param?: TranslateParam) {
|
translate(name: string, param?: TranslateParam) {
|
||||||
let langText: string = this.langMap[name] || this.fallbackMap[name];
|
let langText: string = this.langMap[name] || this.fallbackMap[name]
|
||||||
if (!langText) { return '[WARN] @ccms/i18n miss lang translate: ' + name }
|
if (!langText) { return '[WARN] @ccms/i18n miss lang translate: ' + name }
|
||||||
for (const key in param) {
|
for (const key in param) {
|
||||||
langText = langText.replace(new RegExp("{" + key + "}", 'gm'), param[key])
|
langText = langText.replace(new RegExp("{" + key + "}", 'gm'), param[key])
|
||||||
}
|
}
|
||||||
return langText;
|
return langText
|
||||||
}
|
}
|
||||||
|
|
||||||
initialize(lang: string = 'zh_cn', fallback: string = 'zh_cn') {
|
initialize(lang: string = 'zh_cn', fallback: string = 'zh_cn') {
|
||||||
@@ -49,8 +49,8 @@ export class Translate {
|
|||||||
}
|
}
|
||||||
|
|
||||||
readYamlFile(dir: string, name: string) {
|
readYamlFile(dir: string, name: string) {
|
||||||
let langFile = this.concat(dir, 'languages', name + '.yml');
|
let langFile = this.concat(dir, 'languages', name + '.yml')
|
||||||
return this.exists(langFile) && yaml.safeLoad(base.read(langFile))
|
return this.exists(langFile) && yaml.load(base.read(langFile))
|
||||||
}
|
}
|
||||||
|
|
||||||
concat(...args: string[]) {
|
concat(...args: string[]) {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/keyvalue",
|
"name": "@ccms/keyvalue",
|
||||||
"version": "0.9.8",
|
"version": "0.20.0-alpha.0",
|
||||||
"description": "MiaoScript keyvalue package",
|
"description": "MiaoScript keyvalue package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -19,18 +19,18 @@
|
|||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ccms/api": "^0.9.8",
|
"@ccms/api": "^0.20.0-alpha.0",
|
||||||
"@ccms/common": "^0.9.8",
|
"@ccms/common": "^0.19.0",
|
||||||
"@ccms/container": "^0.9.8"
|
"@ccms/container": "^0.19.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@ccms/nashorn": "^0.9.8",
|
"@ccms/nashorn": "^0.19.0",
|
||||||
"@javatypes/amqp-client": "^0.0.3",
|
"@javatypes/amqp-client": "^0.0.3",
|
||||||
"@javatypes/spring-amqp": "^0.0.3",
|
"@javatypes/spring-amqp": "^0.0.3",
|
||||||
"@javatypes/spring-rabbit": "^0.0.3",
|
"@javatypes/spring-rabbit": "^0.0.3",
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^4.0.3"
|
"typescript": "^4.5.5"
|
||||||
},
|
},
|
||||||
"gitHead": "2589633069d24f646ac09261b1b2304c21d4ea75"
|
"gitHead": "2589633069d24f646ac09261b1b2304c21d4ea75"
|
||||||
}
|
}
|
||||||
|
|||||||
6
packages/molang/.gitignore
vendored
Normal file
6
packages/molang/.gitignore
vendored
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
node_modules
|
||||||
|
perf/*
|
||||||
|
|
||||||
|
|
||||||
|
tsconfig.tsbuildinfo
|
||||||
|
.DS_STORE
|
||||||
29
packages/molang/package.json
Normal file
29
packages/molang/package.json
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
{
|
||||||
|
"name": "@ccms/molang",
|
||||||
|
"version": "0.19.0",
|
||||||
|
"description": "A fast parser for Minecraft's MoLang",
|
||||||
|
"main": "dist/index.js",
|
||||||
|
"types": "dist/index.d.ts",
|
||||||
|
"scripts": {
|
||||||
|
"clean": "rimraf dist",
|
||||||
|
"watch": "tsc --watch",
|
||||||
|
"build": "yarn clean && tsc",
|
||||||
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
|
},
|
||||||
|
"repository": {
|
||||||
|
"type": "git",
|
||||||
|
"url": "git+https://github.com/solvedDev/MoLang.git"
|
||||||
|
},
|
||||||
|
"author": "solvedDev",
|
||||||
|
"license": "MIT",
|
||||||
|
"bugs": {
|
||||||
|
"url": "https://github.com/solvedDev/MoLang/issues"
|
||||||
|
},
|
||||||
|
"homepage": "https://github.com/solvedDev/MoLang#readme",
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/node": "^17.0.17",
|
||||||
|
"rimraf": "^3.0.2",
|
||||||
|
"tslib": "^2.3.1",
|
||||||
|
"typescript": "^4.5.5"
|
||||||
|
}
|
||||||
|
}
|
||||||
129
packages/molang/src/MoLang.ts
Normal file
129
packages/molang/src/MoLang.ts
Normal file
@@ -0,0 +1,129 @@
|
|||||||
|
import { ExecutionEnvironment } from './env/env'
|
||||||
|
import { IExpression, IParserConfig } from './main'
|
||||||
|
import { StaticExpression } from './parser/expressions/static'
|
||||||
|
import { StringExpression } from './parser/expressions/string'
|
||||||
|
import { MoLangParser } from './parser/molang'
|
||||||
|
|
||||||
|
export class MoLang {
|
||||||
|
protected expressionCache: Record<string, IExpression> = {}
|
||||||
|
protected totalCacheEntries = 0
|
||||||
|
protected executionEnvironment!: ExecutionEnvironment
|
||||||
|
|
||||||
|
protected parser: MoLangParser
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
env: Record<string, unknown> = {},
|
||||||
|
protected config: Partial<IParserConfig> = {}
|
||||||
|
) {
|
||||||
|
if (config.useOptimizer === undefined) this.config.useOptimizer = true
|
||||||
|
if (config.useCache === undefined) this.config.useCache = true
|
||||||
|
if (config.earlyReturnsSkipParsing === undefined)
|
||||||
|
this.config.earlyReturnsSkipParsing = true
|
||||||
|
if (config.earlyReturnsSkipTokenization === undefined)
|
||||||
|
this.config.earlyReturnsSkipTokenization = true
|
||||||
|
if (config.convertUndefined === undefined)
|
||||||
|
this.config.convertUndefined = false
|
||||||
|
|
||||||
|
this.parser = new MoLangParser({
|
||||||
|
...this.config,
|
||||||
|
tokenizer: undefined,
|
||||||
|
})
|
||||||
|
|
||||||
|
this.updateExecutionEnv(env)
|
||||||
|
}
|
||||||
|
|
||||||
|
updateConfig(newConfig: Partial<IParserConfig>) {
|
||||||
|
newConfig = Object.assign(this.config, newConfig)
|
||||||
|
|
||||||
|
if (newConfig.tokenizer) this.parser.setTokenizer(newConfig.tokenizer)
|
||||||
|
this.parser.updateConfig({ ...this.config, tokenizer: undefined })
|
||||||
|
this.executionEnvironment.updateConfig(newConfig)
|
||||||
|
}
|
||||||
|
updateExecutionEnv(env: Record<string, unknown>, isFlat = false) {
|
||||||
|
this.executionEnvironment = new ExecutionEnvironment(env, {
|
||||||
|
useRadians: this.config.useRadians,
|
||||||
|
convertUndefined: this.config.convertUndefined,
|
||||||
|
isFlat,
|
||||||
|
variableHandler: this.config.variableHandler,
|
||||||
|
})
|
||||||
|
this.parser.setExecutionEnvironment(this.executionEnvironment)
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Clears the MoLang expression cache
|
||||||
|
*/
|
||||||
|
clearCache() {
|
||||||
|
this.expressionCache = {}
|
||||||
|
this.totalCacheEntries = 0
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute the given MoLang string `expression`
|
||||||
|
* @param expression The MoLang string to execute
|
||||||
|
*
|
||||||
|
* @returns The value the MoLang expression corresponds to
|
||||||
|
*/
|
||||||
|
execute(expression: string) {
|
||||||
|
this.parser.setExecutionEnvironment(this.executionEnvironment)
|
||||||
|
const abstractSyntaxTree = this.parse(expression)
|
||||||
|
|
||||||
|
const result = abstractSyntaxTree.eval()
|
||||||
|
if (result === undefined) return 0
|
||||||
|
if (typeof result === 'boolean') return Number(result)
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Execute the given MoLang string `expression`
|
||||||
|
* In case of errors, return 0
|
||||||
|
* @param expression The MoLang string to execute
|
||||||
|
*
|
||||||
|
* @returns The value the MoLang expression corresponds to and 0 if the statement is invalid
|
||||||
|
*/
|
||||||
|
executeAndCatch(expression: string) {
|
||||||
|
try {
|
||||||
|
return this.execute(expression)
|
||||||
|
} catch {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parse the given MoLang string `expression`
|
||||||
|
* @param expression The MoLang string to parse
|
||||||
|
*
|
||||||
|
* @returns An AST that corresponds to the MoLang expression
|
||||||
|
*/
|
||||||
|
parse(expression: string): IExpression {
|
||||||
|
if (this.config.useCache ?? true) {
|
||||||
|
const abstractSyntaxTree = this.expressionCache[expression]
|
||||||
|
if (abstractSyntaxTree) return abstractSyntaxTree
|
||||||
|
}
|
||||||
|
|
||||||
|
this.parser.init(expression)
|
||||||
|
let abstractSyntaxTree = this.parser.parseExpression()
|
||||||
|
if ((this.config.useOptimizer ?? true) && abstractSyntaxTree.isStatic())
|
||||||
|
abstractSyntaxTree = new StaticExpression(abstractSyntaxTree.eval())
|
||||||
|
// console.log(JSON.stringify(abstractSyntaxTree, null, ' '))
|
||||||
|
|
||||||
|
if (this.config.useCache ?? true) {
|
||||||
|
if (this.totalCacheEntries > (this.config.maxCacheSize || 256))
|
||||||
|
this.clearCache()
|
||||||
|
|
||||||
|
this.expressionCache[expression] = abstractSyntaxTree
|
||||||
|
this.totalCacheEntries++
|
||||||
|
}
|
||||||
|
|
||||||
|
return abstractSyntaxTree
|
||||||
|
}
|
||||||
|
|
||||||
|
resolveStatic(ast: IExpression) {
|
||||||
|
ast.walk((expr) => {
|
||||||
|
if (expr instanceof StringExpression) return
|
||||||
|
|
||||||
|
if (expr.isStatic()) return new StaticExpression(expr.eval())
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
getParser() {
|
||||||
|
return this.parser
|
||||||
|
}
|
||||||
|
}
|
||||||
93
packages/molang/src/custom/function.ts
Normal file
93
packages/molang/src/custom/function.ts
Normal file
@@ -0,0 +1,93 @@
|
|||||||
|
import { Parser } from '../parser/parse'
|
||||||
|
import { Token } from '../parser/../tokenizer/token'
|
||||||
|
import { IPrefixParselet } from '../parser/parselets/prefix'
|
||||||
|
import { Expression, IExpression } from '../parser/expression'
|
||||||
|
import { StringExpression } from '../parser/expressions/string'
|
||||||
|
import { StatementExpression } from '../parser/expressions/statement'
|
||||||
|
import { CustomMoLangParser } from './main'
|
||||||
|
import { GroupExpression } from '../parser/expressions/group'
|
||||||
|
|
||||||
|
export class CustomFunctionParselet implements IPrefixParselet {
|
||||||
|
constructor(public precedence = 0) {}
|
||||||
|
|
||||||
|
parse(parser: Parser, token: Token) {
|
||||||
|
parser.consume('LEFT_PARENT')
|
||||||
|
if (parser.match('RIGHT_PARENT'))
|
||||||
|
throw new Error(`function() called without arguments`)
|
||||||
|
|
||||||
|
let args: string[] = []
|
||||||
|
let functionBody: IExpression | undefined
|
||||||
|
let functionName: string | undefined
|
||||||
|
do {
|
||||||
|
const expr = parser.parseExpression()
|
||||||
|
if (expr instanceof StringExpression) {
|
||||||
|
if (!functionName) functionName = <string>expr.eval()
|
||||||
|
else args.push(<string>expr.eval())
|
||||||
|
} else if (
|
||||||
|
expr instanceof StatementExpression ||
|
||||||
|
expr instanceof GroupExpression
|
||||||
|
) {
|
||||||
|
functionBody = expr
|
||||||
|
} else {
|
||||||
|
throw new Error(
|
||||||
|
`Unexpected expresion: found "${expr.constructor.name}"`
|
||||||
|
)
|
||||||
|
}
|
||||||
|
} while (parser.match('COMMA'))
|
||||||
|
parser.consume('RIGHT_PARENT')
|
||||||
|
|
||||||
|
if (!functionName)
|
||||||
|
throw new Error(
|
||||||
|
`Missing function() name (argument 1); found "${functionName}"`
|
||||||
|
)
|
||||||
|
if (!functionBody)
|
||||||
|
throw new Error(
|
||||||
|
`Missing function() body (argument ${args.length + 2})`
|
||||||
|
)
|
||||||
|
|
||||||
|
return new CustomFunctionExpression(
|
||||||
|
(<CustomMoLangParser>parser).functions,
|
||||||
|
functionName,
|
||||||
|
args,
|
||||||
|
functionBody
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class CustomFunctionExpression extends Expression {
|
||||||
|
type = 'CustomFunctionExpression'
|
||||||
|
constructor(
|
||||||
|
functions: Map<string, [string[], string]>,
|
||||||
|
functionName: string,
|
||||||
|
args: string[],
|
||||||
|
protected functionBody: IExpression
|
||||||
|
) {
|
||||||
|
super()
|
||||||
|
functions.set(functionName, [
|
||||||
|
args,
|
||||||
|
functionBody instanceof GroupExpression
|
||||||
|
? functionBody.allExpressions[0].toString()
|
||||||
|
: functionBody.toString(),
|
||||||
|
])
|
||||||
|
}
|
||||||
|
|
||||||
|
get allExpressions() {
|
||||||
|
return [this.functionBody]
|
||||||
|
}
|
||||||
|
setExpressionAt(_: number, expr: IExpression) {
|
||||||
|
this.functionBody = expr
|
||||||
|
}
|
||||||
|
|
||||||
|
get isReturn() {
|
||||||
|
// Scopes inside of functions may use return statements
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
isStatic() {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
eval() {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
}
|
||||||
229
packages/molang/src/custom/main.ts
Normal file
229
packages/molang/src/custom/main.ts
Normal file
@@ -0,0 +1,229 @@
|
|||||||
|
import { ExecutionEnvironment } from '../env/env'
|
||||||
|
import { IParserConfig } from '../main'
|
||||||
|
import { MoLangParser } from '../parser/molang'
|
||||||
|
import { Tokenizer } from '../tokenizer/Tokenizer'
|
||||||
|
import { CustomFunctionParselet } from './function'
|
||||||
|
import { MoLang } from '../MoLang'
|
||||||
|
import { StatementExpression } from '../parser/expressions/statement'
|
||||||
|
import { transformStatement } from './transformStatement'
|
||||||
|
import { NameExpression } from '../parser/expressions/name'
|
||||||
|
import { ReturnExpression } from '../parser/expressions/return'
|
||||||
|
import { GenericOperatorExpression } from '../parser/expressions/genericOperator'
|
||||||
|
import { TernaryExpression } from '../parser/expressions/ternary'
|
||||||
|
import { IExpression } from '../parser/expression'
|
||||||
|
import { VoidExpression } from '../parser/expressions/void'
|
||||||
|
import { GroupExpression } from '../parser/expressions/group'
|
||||||
|
|
||||||
|
export class CustomMoLangParser extends MoLangParser {
|
||||||
|
public readonly functions = new Map<string, [string[], string]>()
|
||||||
|
|
||||||
|
constructor(config: Partial<IParserConfig>) {
|
||||||
|
super(config)
|
||||||
|
this.registerPrefix('FUNCTION', new CustomFunctionParselet())
|
||||||
|
}
|
||||||
|
|
||||||
|
reset() {
|
||||||
|
this.functions.clear()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class CustomMoLang {
|
||||||
|
protected parser: CustomMoLangParser
|
||||||
|
|
||||||
|
constructor(env: any) {
|
||||||
|
this.parser = new CustomMoLangParser({
|
||||||
|
useCache: false,
|
||||||
|
useOptimizer: true,
|
||||||
|
useAgressiveStaticOptimizer: true,
|
||||||
|
keepGroups: true,
|
||||||
|
earlyReturnsSkipParsing: false,
|
||||||
|
earlyReturnsSkipTokenization: false,
|
||||||
|
})
|
||||||
|
this.parser.setExecutionEnvironment(
|
||||||
|
new ExecutionEnvironment(this.parser, env)
|
||||||
|
)
|
||||||
|
this.parser.setTokenizer(new Tokenizer(new Set(['function'])))
|
||||||
|
}
|
||||||
|
|
||||||
|
get functions() {
|
||||||
|
return this.parser.functions
|
||||||
|
}
|
||||||
|
|
||||||
|
parse(expression: string) {
|
||||||
|
this.parser.init(expression)
|
||||||
|
const abstractSyntaxTree = this.parser.parseExpression()
|
||||||
|
|
||||||
|
return abstractSyntaxTree
|
||||||
|
}
|
||||||
|
|
||||||
|
transform(source: string) {
|
||||||
|
const molang = new MoLang(
|
||||||
|
{},
|
||||||
|
{
|
||||||
|
useCache: false,
|
||||||
|
keepGroups: true,
|
||||||
|
useOptimizer: true,
|
||||||
|
useAgressiveStaticOptimizer: true,
|
||||||
|
earlyReturnsSkipParsing: true,
|
||||||
|
earlyReturnsSkipTokenization: false,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
let totalScoped = 0
|
||||||
|
let ast = molang.parse(source)
|
||||||
|
|
||||||
|
let isComplexExpression = false
|
||||||
|
if (ast instanceof StatementExpression) {
|
||||||
|
isComplexExpression = true
|
||||||
|
}
|
||||||
|
|
||||||
|
let containsComplexExpressions = false
|
||||||
|
ast = ast.walk((expr: any) => {
|
||||||
|
// Only run code on function expressions which start with "f." or "function."
|
||||||
|
if (
|
||||||
|
expr.type !== 'FunctionExpression' ||
|
||||||
|
(!expr.name.name.startsWith?.('f.') &&
|
||||||
|
!expr.name.name.startsWith?.('function.'))
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
const nameExpr = expr.name
|
||||||
|
const functionName = nameExpr.name.replace(/(f|function)\./g, '')
|
||||||
|
const argValues = expr.args
|
||||||
|
|
||||||
|
let [args, functionBody] = this.functions.get(functionName) ?? []
|
||||||
|
if (!functionBody || !args) return
|
||||||
|
|
||||||
|
// Insert argument values
|
||||||
|
functionBody = functionBody.replace(
|
||||||
|
/(a|arg)\.(\w+)/g,
|
||||||
|
(match, prefix, argName) => {
|
||||||
|
const val =
|
||||||
|
argValues[args!.indexOf(argName)]?.toString() ?? '0'
|
||||||
|
|
||||||
|
return val.replace(/(t|temp)\./, 'outer_temp.')
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
let funcAst = transformStatement(molang.parse(functionBody))
|
||||||
|
if (funcAst instanceof StatementExpression) {
|
||||||
|
funcAst = molang.parse(`({${functionBody}}+t.return_value)`)
|
||||||
|
|
||||||
|
containsComplexExpressions = true
|
||||||
|
}
|
||||||
|
|
||||||
|
const varNameMap = new Map<string, string>()
|
||||||
|
funcAst = funcAst.walk((expr) => {
|
||||||
|
if (expr instanceof NameExpression) {
|
||||||
|
const fullName = expr.toString()
|
||||||
|
// Remove "a."/"t."/etc. from var name
|
||||||
|
let tmp = fullName.split('.')
|
||||||
|
const varType = tmp.shift()
|
||||||
|
const varName = tmp.join('.')
|
||||||
|
|
||||||
|
if (varType === 't' || varType === 'temp') {
|
||||||
|
// Scope temp./t. variables to functions
|
||||||
|
let newName = varNameMap.get(fullName)
|
||||||
|
if (!newName) {
|
||||||
|
newName = `t.__scvar${totalScoped++}`
|
||||||
|
varNameMap.set(fullName, newName)
|
||||||
|
}
|
||||||
|
|
||||||
|
expr.setName(newName)
|
||||||
|
} else if (varType === 'outer_temp') {
|
||||||
|
expr.setName(`t.${varName}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
return undefined
|
||||||
|
} else if (expr instanceof ReturnExpression) {
|
||||||
|
const nameExpr = new NameExpression(
|
||||||
|
molang.getParser().executionEnv,
|
||||||
|
't.return_value'
|
||||||
|
)
|
||||||
|
const returnValExpr = expr.allExpressions[0]
|
||||||
|
|
||||||
|
return new GenericOperatorExpression(
|
||||||
|
nameExpr,
|
||||||
|
returnValExpr,
|
||||||
|
'=',
|
||||||
|
() => {
|
||||||
|
nameExpr.setPointer(returnValExpr.eval())
|
||||||
|
}
|
||||||
|
)
|
||||||
|
} else if (expr instanceof StatementExpression) {
|
||||||
|
// Make early returns work correctly by adjusting ternary statements which contain return statements
|
||||||
|
const expressions: IExpression[] = []
|
||||||
|
|
||||||
|
for (let i = 0; i < expr.allExpressions.length; i++) {
|
||||||
|
const currExpr = expr.allExpressions[i]
|
||||||
|
|
||||||
|
if (
|
||||||
|
currExpr instanceof TernaryExpression &&
|
||||||
|
currExpr.hasReturn
|
||||||
|
) {
|
||||||
|
handleTernary(
|
||||||
|
currExpr,
|
||||||
|
expr.allExpressions.slice(i + 1)
|
||||||
|
)
|
||||||
|
|
||||||
|
expressions.push(currExpr)
|
||||||
|
break
|
||||||
|
} else if (currExpr.isReturn) {
|
||||||
|
expressions.push(currExpr)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
expressions.push(currExpr)
|
||||||
|
}
|
||||||
|
|
||||||
|
return new StatementExpression(expressions)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
return funcAst
|
||||||
|
})
|
||||||
|
|
||||||
|
const finalAst = molang.parse(ast.toString())
|
||||||
|
molang.resolveStatic(finalAst)
|
||||||
|
return !isComplexExpression && containsComplexExpressions
|
||||||
|
? `return ${finalAst.toString()};`
|
||||||
|
: finalAst.toString()
|
||||||
|
}
|
||||||
|
|
||||||
|
reset() {
|
||||||
|
this.functions.clear()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleTernary(
|
||||||
|
returnTernary: TernaryExpression,
|
||||||
|
currentExpressions: IExpression[]
|
||||||
|
) {
|
||||||
|
// If & else branch end with return statements -> we can omit everything after the ternary
|
||||||
|
if (returnTernary.isReturn) return
|
||||||
|
|
||||||
|
const notReturningBranchIndex = returnTernary.allExpressions[2].isReturn
|
||||||
|
? 1
|
||||||
|
: 2
|
||||||
|
const notReturningBranch =
|
||||||
|
returnTernary.allExpressions[notReturningBranchIndex]
|
||||||
|
|
||||||
|
if (!(notReturningBranch instanceof VoidExpression)) {
|
||||||
|
if (
|
||||||
|
notReturningBranch instanceof GroupExpression &&
|
||||||
|
notReturningBranch.allExpressions[0] instanceof StatementExpression
|
||||||
|
) {
|
||||||
|
currentExpressions.unshift(...notReturningBranch.allExpressions)
|
||||||
|
} else {
|
||||||
|
currentExpressions.unshift(notReturningBranch)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (currentExpressions.length > 0)
|
||||||
|
returnTernary.setExpressionAt(
|
||||||
|
notReturningBranchIndex,
|
||||||
|
new GroupExpression(
|
||||||
|
new StatementExpression(currentExpressions),
|
||||||
|
'{}'
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
19
packages/molang/src/custom/transformStatement.ts
Normal file
19
packages/molang/src/custom/transformStatement.ts
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
import { IExpression } from '../parser/expression'
|
||||||
|
import { GroupExpression } from '../parser/expressions/group'
|
||||||
|
import { ReturnExpression } from '../parser/expressions/return'
|
||||||
|
import { StatementExpression } from '../parser/expressions/statement'
|
||||||
|
|
||||||
|
export function transformStatement(expression: IExpression) {
|
||||||
|
if (expression instanceof ReturnExpression)
|
||||||
|
return new GroupExpression(expression.allExpressions[0], '()')
|
||||||
|
if (!(expression instanceof StatementExpression)) return expression
|
||||||
|
if (expression.allExpressions.length > 1) return expression
|
||||||
|
|
||||||
|
// Only one statement, test whether it is a return statement
|
||||||
|
const expr = expression.allExpressions[0]
|
||||||
|
if (expr instanceof ReturnExpression) {
|
||||||
|
return new GroupExpression(expr.allExpressions[0], '()')
|
||||||
|
} else {
|
||||||
|
return expression
|
||||||
|
}
|
||||||
|
}
|
||||||
143
packages/molang/src/env/env.ts
vendored
Normal file
143
packages/molang/src/env/env.ts
vendored
Normal file
@@ -0,0 +1,143 @@
|
|||||||
|
import { standardEnv } from './standardEnv'
|
||||||
|
|
||||||
|
export type TVariableHandler = (
|
||||||
|
variableName: string,
|
||||||
|
variables: Record<string, unknown>
|
||||||
|
) => unknown
|
||||||
|
|
||||||
|
export interface IEnvConfig {
|
||||||
|
useRadians?: boolean
|
||||||
|
convertUndefined?: boolean
|
||||||
|
variableHandler?: TVariableHandler
|
||||||
|
isFlat?: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ExecutionEnvironment {
|
||||||
|
protected env: Record<string, any>
|
||||||
|
|
||||||
|
constructor(env: Record<string, any>, public readonly config: IEnvConfig) {
|
||||||
|
if (!env) throw new Error(`Provided environment must be an object`)
|
||||||
|
|
||||||
|
if (config.isFlat)
|
||||||
|
this.env = Object.assign(
|
||||||
|
env,
|
||||||
|
standardEnv(config.useRadians ?? false)
|
||||||
|
)
|
||||||
|
else
|
||||||
|
this.env = {
|
||||||
|
...standardEnv(config.useRadians ?? false),
|
||||||
|
...this.flattenEnv(env),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
updateConfig({
|
||||||
|
variableHandler,
|
||||||
|
convertUndefined,
|
||||||
|
useRadians,
|
||||||
|
}: IEnvConfig) {
|
||||||
|
if (convertUndefined !== undefined)
|
||||||
|
this.config.convertUndefined = convertUndefined
|
||||||
|
if (typeof variableHandler === 'function')
|
||||||
|
this.config.variableHandler = variableHandler
|
||||||
|
|
||||||
|
if (!!this.config.useRadians !== !!useRadians) {
|
||||||
|
this.env = Object.assign(this.env, standardEnv(!!useRadians))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected flattenEnv(
|
||||||
|
newEnv: Record<string, any>,
|
||||||
|
addKey = '',
|
||||||
|
current: any = {}
|
||||||
|
) {
|
||||||
|
for (let key in newEnv) {
|
||||||
|
if (key[1] === '.') {
|
||||||
|
switch (key[0]) {
|
||||||
|
case 'q':
|
||||||
|
key = 'query' + key.substring(1, key.length)
|
||||||
|
break
|
||||||
|
case 't':
|
||||||
|
key = 'temp' + key.substring(1, key.length)
|
||||||
|
break
|
||||||
|
case 'v':
|
||||||
|
key = 'variable' + key.substring(1, key.length)
|
||||||
|
break
|
||||||
|
case 'c':
|
||||||
|
key = 'context' + key.substring(1, key.length)
|
||||||
|
break
|
||||||
|
case 'f':
|
||||||
|
key = 'function' + key.substring(1, key.length)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (newEnv[key].__isContext) {
|
||||||
|
current[`${addKey}${key}`] = newEnv[key].env
|
||||||
|
} else if (
|
||||||
|
typeof newEnv[key] === 'object' &&
|
||||||
|
!Array.isArray(newEnv[key])
|
||||||
|
) {
|
||||||
|
this.flattenEnv(newEnv[key], `${addKey}${key}.`, current)
|
||||||
|
} else {
|
||||||
|
current[`${addKey}${key}`] = newEnv[key]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return current
|
||||||
|
}
|
||||||
|
|
||||||
|
setAt(lookup: string, value: unknown) {
|
||||||
|
if (lookup[1] === '.') {
|
||||||
|
switch (lookup[0]) {
|
||||||
|
case 'q':
|
||||||
|
lookup = 'query' + lookup.substring(1, lookup.length)
|
||||||
|
break
|
||||||
|
case 't':
|
||||||
|
lookup = 'temp' + lookup.substring(1, lookup.length)
|
||||||
|
break
|
||||||
|
case 'v':
|
||||||
|
lookup = 'variable' + lookup.substring(1, lookup.length)
|
||||||
|
break
|
||||||
|
case 'c':
|
||||||
|
lookup = 'context' + lookup.substring(1, lookup.length)
|
||||||
|
break
|
||||||
|
case 'f':
|
||||||
|
lookup = 'function' + lookup.substring(1, lookup.length)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (this.env[lookup] = value)
|
||||||
|
}
|
||||||
|
|
||||||
|
getFrom(lookup: string) {
|
||||||
|
if (lookup[1] === '.') {
|
||||||
|
switch (lookup[0]) {
|
||||||
|
case 'q':
|
||||||
|
lookup = 'query' + lookup.substring(1, lookup.length)
|
||||||
|
break
|
||||||
|
case 't':
|
||||||
|
lookup = 'temp' + lookup.substring(1, lookup.length)
|
||||||
|
break
|
||||||
|
case 'v':
|
||||||
|
lookup = 'variable' + lookup.substring(1, lookup.length)
|
||||||
|
break
|
||||||
|
case 'c':
|
||||||
|
lookup = 'context' + lookup.substring(1, lookup.length)
|
||||||
|
break
|
||||||
|
case 'f':
|
||||||
|
lookup = 'function' + lookup.substring(1, lookup.length)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const res =
|
||||||
|
this.env[lookup] ?? this.config.variableHandler?.(lookup, this.env)
|
||||||
|
return res === undefined && this.config.convertUndefined ? 0 : res
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class Context {
|
||||||
|
public readonly __isContext = true
|
||||||
|
constructor(public readonly env: any) {}
|
||||||
|
}
|
||||||
86
packages/molang/src/env/math.ts
vendored
Normal file
86
packages/molang/src/env/math.ts
vendored
Normal file
@@ -0,0 +1,86 @@
|
|||||||
|
const clamp = (value: number, min: number, max: number) => {
|
||||||
|
if (typeof value !== 'number' || Number.isNaN(value)) return min
|
||||||
|
else if (value > max) return max
|
||||||
|
else if (value < min) return min
|
||||||
|
return value
|
||||||
|
}
|
||||||
|
const dieRoll = (sum: number, low: number, high: number) => {
|
||||||
|
let i = 0
|
||||||
|
let total = 0
|
||||||
|
while (i < sum) total += random(low, high)
|
||||||
|
return total
|
||||||
|
}
|
||||||
|
const dieRollInt = (sum: number, low: number, high: number) => {
|
||||||
|
let i = 0
|
||||||
|
let total = 0
|
||||||
|
while (i < sum) total += randomInt(low, high)
|
||||||
|
return total
|
||||||
|
}
|
||||||
|
const hermiteBlend = (value: number) => 3 * value ** 2 - 2 * value ** 3
|
||||||
|
const lerp = (start: number, end: number, amount: number) => {
|
||||||
|
if (amount < 0) amount = 0
|
||||||
|
else if (amount > 1) amount = 1
|
||||||
|
|
||||||
|
return start + (end - start) * amount
|
||||||
|
}
|
||||||
|
// Written by @JannisX11 (https://github.com/JannisX11/MolangJS/blob/master/molang.js#L383); modified for usage inside of this MoLang parser
|
||||||
|
const lerprotate = (start: number, end: number, amount: number) => {
|
||||||
|
const radify = (n: number) => (((n + 180) % 360) + 180) % 360
|
||||||
|
start = radify(start)
|
||||||
|
end = radify(end)
|
||||||
|
if (start > end) {
|
||||||
|
let tmp = start
|
||||||
|
start = end
|
||||||
|
end = tmp
|
||||||
|
}
|
||||||
|
|
||||||
|
if (end - start > 180) return radify(end + amount * (360 - (end - start)))
|
||||||
|
else return start + amount * (end - start)
|
||||||
|
}
|
||||||
|
const mod = (value: number, denominator: number) => value % denominator
|
||||||
|
const random = (low: number, high: number) => low + Math.random() * (high - low)
|
||||||
|
const randomInt = (low: number, high: number) =>
|
||||||
|
Math.round(low + Math.random() * (high - low))
|
||||||
|
|
||||||
|
const minAngle = (value: number) => {
|
||||||
|
value = value % 360
|
||||||
|
value = (value + 360) % 360
|
||||||
|
|
||||||
|
if (value > 179) value -= 360
|
||||||
|
return value
|
||||||
|
}
|
||||||
|
|
||||||
|
export const MoLangMathLib = (useRadians: boolean) => {
|
||||||
|
const degRadFactor = useRadians ? 1 : Math.PI / 180
|
||||||
|
|
||||||
|
return {
|
||||||
|
'math.abs': Math.abs,
|
||||||
|
'math.acos': (x: number) => Math.acos(x) / degRadFactor,
|
||||||
|
'math.asin': (x: number) => Math.asin(x) / degRadFactor,
|
||||||
|
'math.atan': (x: number) => Math.atan(x) / degRadFactor,
|
||||||
|
'math.atan2': (y: number, x: number) => Math.atan2(y, x) / degRadFactor,
|
||||||
|
'math.ceil': Math.ceil,
|
||||||
|
'math.clamp': clamp,
|
||||||
|
'math.cos': (x: number) => Math.cos(x * degRadFactor),
|
||||||
|
'math.die_roll': dieRoll,
|
||||||
|
'math.die_roll_integer': dieRollInt,
|
||||||
|
'math.exp': Math.exp,
|
||||||
|
'math.floor': Math.floor,
|
||||||
|
'math.hermite_blend': hermiteBlend,
|
||||||
|
'math.lerp': lerp,
|
||||||
|
'math.lerp_rotate': lerprotate,
|
||||||
|
'math.ln': Math.log,
|
||||||
|
'math.max': Math.max,
|
||||||
|
'math.min': Math.min,
|
||||||
|
'math.min_angle': minAngle,
|
||||||
|
'math.mod': mod,
|
||||||
|
'math.pi': Math.PI,
|
||||||
|
'math.pow': Math.pow,
|
||||||
|
'math.random': random,
|
||||||
|
'math.random_integer': randomInt,
|
||||||
|
'math.round': Math.round,
|
||||||
|
'math.sin': (x: number) => Math.sin(x * degRadFactor),
|
||||||
|
'math.sqrt': Math.sqrt,
|
||||||
|
'math.trunc': Math.trunc,
|
||||||
|
}
|
||||||
|
}
|
||||||
25
packages/molang/src/env/queries.ts
vendored
Normal file
25
packages/molang/src/env/queries.ts
vendored
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
const inRange = (value: number, min: number, max: number) => {
|
||||||
|
// Check that value, min and max are numbers
|
||||||
|
if (
|
||||||
|
typeof value !== 'number' ||
|
||||||
|
typeof min !== 'number' ||
|
||||||
|
typeof max !== 'number'
|
||||||
|
) {
|
||||||
|
console.error('"query.in_range": value, min and max must be numbers')
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
return value >= min && value <= max
|
||||||
|
}
|
||||||
|
|
||||||
|
const all = (mustMatch: unknown, ...values: unknown[]) =>
|
||||||
|
values.every((v) => v === mustMatch)
|
||||||
|
|
||||||
|
const any = (mustMatch: unknown, ...values: unknown[]) =>
|
||||||
|
values.some((v) => v === mustMatch)
|
||||||
|
|
||||||
|
export const standardQueries = {
|
||||||
|
'query.in_range': inRange,
|
||||||
|
'query.all': all,
|
||||||
|
'query.any': any,
|
||||||
|
}
|
||||||
7
packages/molang/src/env/standardEnv.ts
vendored
Normal file
7
packages/molang/src/env/standardEnv.ts
vendored
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
import { MoLangMathLib } from './math'
|
||||||
|
import { standardQueries } from './queries'
|
||||||
|
|
||||||
|
export const standardEnv = (useRadians: boolean) => ({
|
||||||
|
...MoLangMathLib(useRadians),
|
||||||
|
...standardQueries,
|
||||||
|
})
|
||||||
1
packages/molang/src/index.ts
Normal file
1
packages/molang/src/index.ts
Normal file
@@ -0,0 +1 @@
|
|||||||
|
export * from './main'
|
||||||
91
packages/molang/src/main.ts
Normal file
91
packages/molang/src/main.ts
Normal file
@@ -0,0 +1,91 @@
|
|||||||
|
import { TVariableHandler } from './env/env'
|
||||||
|
import { Tokenizer } from './tokenizer/Tokenizer'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* How the parser and interpreter should handle your MoLang expression
|
||||||
|
*/
|
||||||
|
|
||||||
|
export interface IParserConfig {
|
||||||
|
/**
|
||||||
|
* Whether a cache should be used to speed up executing MoLang.
|
||||||
|
* The cache saves an AST for every parsed expression.
|
||||||
|
* This allows us to skip the tokenization & parsing step before executing known MoLang expressions
|
||||||
|
*
|
||||||
|
* Default: true
|
||||||
|
*/
|
||||||
|
useCache: boolean
|
||||||
|
/**
|
||||||
|
* How many expressions can be cached. After reaching `maxCacheSize`, the whole cache is cleared automatically.
|
||||||
|
* Can be set to `Infinity` to remove the limit completely
|
||||||
|
*
|
||||||
|
* Default: 256
|
||||||
|
*/
|
||||||
|
maxCacheSize: number
|
||||||
|
/**
|
||||||
|
* The optimizer can drastically speed up parsing & executing MoLang.
|
||||||
|
* It enables skipping of unreachable statements, pre-evaluating static expressions and skipping of statements with no effect
|
||||||
|
* when used together with the `useAgressiveStaticOptimizer` option
|
||||||
|
*
|
||||||
|
* Default: true
|
||||||
|
*/
|
||||||
|
useOptimizer: boolean
|
||||||
|
/**
|
||||||
|
* Skip execution of statements with no effect
|
||||||
|
* when used together with the `useOptimizer` option
|
||||||
|
*
|
||||||
|
* Default: true
|
||||||
|
*/
|
||||||
|
useAgressiveStaticOptimizer: boolean
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This options makes early return statements skip all parsing work completely
|
||||||
|
*
|
||||||
|
* Default: true
|
||||||
|
*/
|
||||||
|
earlyReturnsSkipParsing: boolean
|
||||||
|
/**
|
||||||
|
* This options makes early return statements skip all tokenization work completely if earlyReturnsSkipParsing is set to true
|
||||||
|
*
|
||||||
|
* Default: true
|
||||||
|
*/
|
||||||
|
earlyReturnsSkipTokenization: boolean
|
||||||
|
/**
|
||||||
|
* Tokenizer to use for tokenizing the expression
|
||||||
|
*/
|
||||||
|
tokenizer: Tokenizer
|
||||||
|
/**
|
||||||
|
* Create expression instances for brackets ("()", "{}")
|
||||||
|
*
|
||||||
|
* This should only be set to true if you want to use the .toString() method of an expression
|
||||||
|
* or you want to iterate over the whole AST
|
||||||
|
*
|
||||||
|
* Default: false
|
||||||
|
*/
|
||||||
|
keepGroups: boolean
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether to convert undefined variables to "0"
|
||||||
|
*
|
||||||
|
* Default: false
|
||||||
|
*/
|
||||||
|
convertUndefined: boolean
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Use radians instead of degrees for trigonometric functions
|
||||||
|
*
|
||||||
|
* Default: false
|
||||||
|
*/
|
||||||
|
useRadians: boolean
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolve undefined variables
|
||||||
|
*/
|
||||||
|
variableHandler: TVariableHandler
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Tokenizer } from './tokenizer/Tokenizer'
|
||||||
|
export { IExpression } from './parser/expression'
|
||||||
|
export { CustomMoLang } from './custom/main'
|
||||||
|
export { MoLang } from './MoLang'
|
||||||
|
export * as expressions from './parser/expressions/index'
|
||||||
|
export { Context } from './env/env'
|
||||||
57
packages/molang/src/parser/expression.ts
Normal file
57
packages/molang/src/parser/expression.ts
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
/**
|
||||||
|
* Interface that describes an AST Expression
|
||||||
|
*/
|
||||||
|
export interface IExpression {
|
||||||
|
readonly type: string
|
||||||
|
readonly isReturn?: boolean
|
||||||
|
readonly isBreak?: boolean
|
||||||
|
readonly isContinue?: boolean
|
||||||
|
readonly allExpressions: IExpression[]
|
||||||
|
|
||||||
|
setFunctionCall?: (value: boolean) => void
|
||||||
|
setPointer?: (value: unknown) => void
|
||||||
|
setExpressionAt(index: number, expr: IExpression): void
|
||||||
|
eval(): unknown
|
||||||
|
isStatic(): boolean
|
||||||
|
walk(cb: TIterateCallback): IExpression
|
||||||
|
iterate(cb: TIterateCallback, visited: Set<IExpression>): void
|
||||||
|
}
|
||||||
|
|
||||||
|
export abstract class Expression implements IExpression {
|
||||||
|
public abstract readonly type: string
|
||||||
|
|
||||||
|
abstract eval(): unknown
|
||||||
|
abstract isStatic(): boolean
|
||||||
|
|
||||||
|
toString() {
|
||||||
|
return `${this.eval()}`
|
||||||
|
}
|
||||||
|
|
||||||
|
abstract allExpressions: IExpression[]
|
||||||
|
abstract setExpressionAt(index: number, expr: IExpression): void
|
||||||
|
|
||||||
|
walk(cb: TIterateCallback, visited = new Set<IExpression>()): IExpression {
|
||||||
|
let expr = cb(this) ?? this
|
||||||
|
|
||||||
|
expr.iterate(cb, visited)
|
||||||
|
|
||||||
|
return expr
|
||||||
|
}
|
||||||
|
iterate(cb: TIterateCallback, visited: Set<IExpression>) {
|
||||||
|
for (let i = 0; i < this.allExpressions.length; i++) {
|
||||||
|
const originalExpr = this.allExpressions[i]
|
||||||
|
if (visited.has(originalExpr)) continue
|
||||||
|
else visited.add(originalExpr)
|
||||||
|
|
||||||
|
const expr = cb(originalExpr) ?? originalExpr
|
||||||
|
|
||||||
|
if (expr !== originalExpr && visited.has(expr)) continue
|
||||||
|
else visited.add(expr)
|
||||||
|
|
||||||
|
this.setExpressionAt(i, expr)
|
||||||
|
expr.iterate(cb, visited)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export type TIterateCallback = (expr: IExpression) => IExpression | undefined
|
||||||
32
packages/molang/src/parser/expressions/arrayAccess.ts
Normal file
32
packages/molang/src/parser/expressions/arrayAccess.ts
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
import { Expression, IExpression } from '../expression'
|
||||||
|
|
||||||
|
export class ArrayAccessExpression extends Expression {
|
||||||
|
type = 'ArrayAccessExpression'
|
||||||
|
constructor(protected name: IExpression, protected lookup: IExpression) {
|
||||||
|
super()
|
||||||
|
}
|
||||||
|
|
||||||
|
get allExpressions() {
|
||||||
|
return [this.name, this.lookup]
|
||||||
|
}
|
||||||
|
setExpressionAt(index: number, expr: IExpression) {
|
||||||
|
if (index === 0) this.name = expr
|
||||||
|
else if (index === 1) this.lookup = expr
|
||||||
|
}
|
||||||
|
|
||||||
|
isStatic() {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
setPointer(value: unknown) {
|
||||||
|
;(<any>this.name.eval())[<number>this.lookup.eval()] = value
|
||||||
|
}
|
||||||
|
|
||||||
|
eval() {
|
||||||
|
return (<any>this.name.eval())[<number>this.lookup.eval()]
|
||||||
|
}
|
||||||
|
|
||||||
|
toString() {
|
||||||
|
return `${this.name.toString()}[${this.lookup.toString()}]`
|
||||||
|
}
|
||||||
|
}
|
||||||
21
packages/molang/src/parser/expressions/boolean.ts
Normal file
21
packages/molang/src/parser/expressions/boolean.ts
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
import { Expression } from '../expression'
|
||||||
|
|
||||||
|
export class BooleanExpression extends Expression {
|
||||||
|
type = 'BooleanExpression'
|
||||||
|
constructor(protected value: boolean) {
|
||||||
|
super()
|
||||||
|
}
|
||||||
|
|
||||||
|
get allExpressions() {
|
||||||
|
return []
|
||||||
|
}
|
||||||
|
setExpressionAt() {}
|
||||||
|
|
||||||
|
isStatic() {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
eval() {
|
||||||
|
return this.value
|
||||||
|
}
|
||||||
|
}
|
||||||
26
packages/molang/src/parser/expressions/break.ts
Normal file
26
packages/molang/src/parser/expressions/break.ts
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
import { Expression } from '../expression'
|
||||||
|
|
||||||
|
export class BreakExpression extends Expression {
|
||||||
|
type = 'BreakExpression'
|
||||||
|
isBreak = true
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
super()
|
||||||
|
}
|
||||||
|
|
||||||
|
get allExpressions() {
|
||||||
|
return []
|
||||||
|
}
|
||||||
|
setExpressionAt() {}
|
||||||
|
|
||||||
|
isStatic() {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
eval() {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
isString() {
|
||||||
|
return 'break'
|
||||||
|
}
|
||||||
|
}
|
||||||
48
packages/molang/src/parser/expressions/contextSwitch.ts
Normal file
48
packages/molang/src/parser/expressions/contextSwitch.ts
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
import { ExecutionEnvironment } from '../../env/env'
|
||||||
|
import { Expression, IExpression } from '../expression'
|
||||||
|
import { NameExpression } from './name'
|
||||||
|
|
||||||
|
export class ContextSwitchExpression extends Expression {
|
||||||
|
type = 'NameExpression'
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
protected leftExpr: NameExpression,
|
||||||
|
protected rightExpr: NameExpression
|
||||||
|
) {
|
||||||
|
super()
|
||||||
|
}
|
||||||
|
|
||||||
|
get allExpressions() {
|
||||||
|
return [this.leftExpr, this.rightExpr]
|
||||||
|
}
|
||||||
|
setExpressionAt(index: number, expr: IExpression) {
|
||||||
|
if (!(expr instanceof NameExpression))
|
||||||
|
throw new Error(
|
||||||
|
`Cannot use context switch operator "->" on ${expr.type}`
|
||||||
|
)
|
||||||
|
|
||||||
|
if (index === 0) this.leftExpr = expr
|
||||||
|
else if (index === 1) this.rightExpr = expr
|
||||||
|
}
|
||||||
|
|
||||||
|
isStatic() {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
eval() {
|
||||||
|
const context = this.leftExpr.eval()
|
||||||
|
if (typeof context !== 'object') return 0
|
||||||
|
|
||||||
|
this.rightExpr.setExecutionEnv(
|
||||||
|
new ExecutionEnvironment(
|
||||||
|
context,
|
||||||
|
this.rightExpr.executionEnv.config
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return this.rightExpr.eval()
|
||||||
|
}
|
||||||
|
|
||||||
|
toString() {
|
||||||
|
return `${this.leftExpr.toString()}->${this.rightExpr.toString()}`
|
||||||
|
}
|
||||||
|
}
|
||||||
26
packages/molang/src/parser/expressions/continue.ts
Normal file
26
packages/molang/src/parser/expressions/continue.ts
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
import { Expression } from '../expression'
|
||||||
|
|
||||||
|
export class ContinueExpression extends Expression {
|
||||||
|
type = 'ContinueExpression'
|
||||||
|
isContinue = true
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
super()
|
||||||
|
}
|
||||||
|
|
||||||
|
get allExpressions() {
|
||||||
|
return []
|
||||||
|
}
|
||||||
|
setExpressionAt() {}
|
||||||
|
|
||||||
|
isStatic() {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
eval() {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
toString() {
|
||||||
|
return 'continue'
|
||||||
|
}
|
||||||
|
}
|
||||||
63
packages/molang/src/parser/expressions/forEach.ts
Normal file
63
packages/molang/src/parser/expressions/forEach.ts
Normal file
@@ -0,0 +1,63 @@
|
|||||||
|
import { Expression, IExpression } from '../expression'
|
||||||
|
|
||||||
|
export class ForEachExpression extends Expression {
|
||||||
|
type = 'ForEachExpression'
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
protected variable: IExpression,
|
||||||
|
protected arrayExpression: IExpression,
|
||||||
|
protected expression: IExpression
|
||||||
|
) {
|
||||||
|
super()
|
||||||
|
if (!this.variable.setPointer)
|
||||||
|
throw new Error(
|
||||||
|
`First for_each() argument must be a variable, received "${typeof this.variable.eval()}"`
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
get isReturn() {
|
||||||
|
return this.expression.isReturn
|
||||||
|
}
|
||||||
|
get allExpressions() {
|
||||||
|
return [this.variable, this.arrayExpression, this.expression]
|
||||||
|
}
|
||||||
|
setExpressionAt(index: number, expr: IExpression) {
|
||||||
|
if (index === 0) this.variable = expr
|
||||||
|
else if (index === 1) this.arrayExpression = expr
|
||||||
|
else if (index === 2) this.expression = expr
|
||||||
|
}
|
||||||
|
|
||||||
|
isStatic() {
|
||||||
|
return (
|
||||||
|
this.variable.isStatic() &&
|
||||||
|
this.arrayExpression.isStatic() &&
|
||||||
|
this.expression.isStatic()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
eval() {
|
||||||
|
const array = this.arrayExpression.eval()
|
||||||
|
if (!Array.isArray(array))
|
||||||
|
throw new Error(
|
||||||
|
`Second for_each() argument must be an array, received "${typeof array}"`
|
||||||
|
)
|
||||||
|
|
||||||
|
let i = 0
|
||||||
|
while (i < array.length) {
|
||||||
|
// Error detection for this.variable is part of the constructor
|
||||||
|
this.variable.setPointer?.(array[i++])
|
||||||
|
|
||||||
|
const res = this.expression.eval()
|
||||||
|
|
||||||
|
if (this.expression.isBreak) break
|
||||||
|
else if (this.expression.isContinue) continue
|
||||||
|
else if (this.expression.isReturn) return res
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
toString() {
|
||||||
|
return `loop(${this.variable.toString()},${this.arrayExpression.toString()},${this.expression.toString()})`
|
||||||
|
}
|
||||||
|
}
|
||||||
46
packages/molang/src/parser/expressions/function.ts
Normal file
46
packages/molang/src/parser/expressions/function.ts
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
import { NameExpression } from './name'
|
||||||
|
import { Expression, IExpression } from '../expression'
|
||||||
|
|
||||||
|
export class FunctionExpression extends Expression {
|
||||||
|
type = 'FunctionExpression'
|
||||||
|
|
||||||
|
constructor(protected name: IExpression, protected args: IExpression[]) {
|
||||||
|
super()
|
||||||
|
}
|
||||||
|
|
||||||
|
get allExpressions() {
|
||||||
|
return [this.name, ...this.args]
|
||||||
|
}
|
||||||
|
setExpressionAt(index: number, expr: Expression) {
|
||||||
|
if (index === 0) this.name = expr
|
||||||
|
else if (index > 0) this.args[index - 1] = expr
|
||||||
|
}
|
||||||
|
|
||||||
|
isStatic() {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
eval() {
|
||||||
|
const args: unknown[] = []
|
||||||
|
let i = 0
|
||||||
|
while (i < this.args.length) args.push(this.args[i++].eval())
|
||||||
|
|
||||||
|
const func = <(...args: unknown[]) => unknown>this.name.eval()
|
||||||
|
if (typeof func !== 'function')
|
||||||
|
throw new Error(
|
||||||
|
`${(<NameExpression>this.name).toString()} is not callable!`
|
||||||
|
)
|
||||||
|
return func(...args)
|
||||||
|
}
|
||||||
|
|
||||||
|
toString() {
|
||||||
|
let str = `${this.name.toString()}(`
|
||||||
|
for (let i = 0; i < this.args.length; i++) {
|
||||||
|
str += `${this.args[i].toString()}${
|
||||||
|
i + 1 < this.args.length ? ',' : ''
|
||||||
|
}`
|
||||||
|
}
|
||||||
|
|
||||||
|
return `${str})`
|
||||||
|
}
|
||||||
|
}
|
||||||
37
packages/molang/src/parser/expressions/genericOperator.ts
Normal file
37
packages/molang/src/parser/expressions/genericOperator.ts
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
import { Expression, IExpression } from '../expression'
|
||||||
|
|
||||||
|
export class GenericOperatorExpression extends Expression {
|
||||||
|
type = 'GenericOperatorExpression'
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
protected left: IExpression,
|
||||||
|
protected right: IExpression,
|
||||||
|
protected operator: string,
|
||||||
|
protected evalHelper: (
|
||||||
|
leftExpression: IExpression,
|
||||||
|
rightExpression: IExpression
|
||||||
|
) => unknown
|
||||||
|
) {
|
||||||
|
super()
|
||||||
|
}
|
||||||
|
|
||||||
|
get allExpressions() {
|
||||||
|
return [this.left, this.right]
|
||||||
|
}
|
||||||
|
setExpressionAt(index: number, expr: IExpression) {
|
||||||
|
if (index === 0) this.left = expr
|
||||||
|
else if (index === 1) this.right = expr
|
||||||
|
}
|
||||||
|
|
||||||
|
isStatic() {
|
||||||
|
return this.left.isStatic() && this.right.isStatic()
|
||||||
|
}
|
||||||
|
|
||||||
|
eval() {
|
||||||
|
return this.evalHelper(this.left, this.right)
|
||||||
|
}
|
||||||
|
|
||||||
|
toString() {
|
||||||
|
return `${this.left.toString()}${this.operator}${this.right.toString()}`
|
||||||
|
}
|
||||||
|
}
|
||||||
38
packages/molang/src/parser/expressions/group.ts
Normal file
38
packages/molang/src/parser/expressions/group.ts
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
import { Expression, IExpression } from '../expression'
|
||||||
|
|
||||||
|
export class GroupExpression extends Expression {
|
||||||
|
type = 'GroupExpression'
|
||||||
|
|
||||||
|
constructor(protected expression: IExpression, protected brackets: string) {
|
||||||
|
super()
|
||||||
|
}
|
||||||
|
|
||||||
|
get allExpressions() {
|
||||||
|
return [this.expression]
|
||||||
|
}
|
||||||
|
setExpressionAt(_: number, expr: IExpression) {
|
||||||
|
this.expression = expr
|
||||||
|
}
|
||||||
|
|
||||||
|
isStatic() {
|
||||||
|
return this.expression.isStatic()
|
||||||
|
}
|
||||||
|
get isReturn() {
|
||||||
|
return this.expression.isReturn
|
||||||
|
}
|
||||||
|
get isBreak() {
|
||||||
|
return this.expression.isBreak
|
||||||
|
}
|
||||||
|
get isContinue() {
|
||||||
|
return this.expression.isContinue
|
||||||
|
}
|
||||||
|
|
||||||
|
eval() {
|
||||||
|
return this.expression.eval()
|
||||||
|
}
|
||||||
|
toString() {
|
||||||
|
return `${this.brackets[0]}${this.expression.toString()}${
|
||||||
|
this.brackets[1]
|
||||||
|
}`
|
||||||
|
}
|
||||||
|
}
|
||||||
19
packages/molang/src/parser/expressions/index.ts
Normal file
19
packages/molang/src/parser/expressions/index.ts
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
export { ArrayAccessExpression } from './arrayAccess'
|
||||||
|
export { BooleanExpression } from './boolean'
|
||||||
|
export { BreakExpression } from './break'
|
||||||
|
export { ContinueExpression } from './continue'
|
||||||
|
export { ForEachExpression } from './forEach'
|
||||||
|
export { FunctionExpression } from './function'
|
||||||
|
export { GenericOperatorExpression } from './genericOperator'
|
||||||
|
export { GroupExpression } from './group'
|
||||||
|
export { LoopExpression } from './loop'
|
||||||
|
export { NameExpression } from './name'
|
||||||
|
export { NumberExpression } from './number'
|
||||||
|
export { PostfixExpression } from './postfix'
|
||||||
|
export { PrefixExpression } from './prefix'
|
||||||
|
export { ReturnExpression } from './return'
|
||||||
|
export { StatementExpression } from './statement'
|
||||||
|
export { StaticExpression } from './static'
|
||||||
|
export { StringExpression } from './string'
|
||||||
|
export { TernaryExpression } from './ternary'
|
||||||
|
export { VoidExpression } from './void'
|
||||||
56
packages/molang/src/parser/expressions/loop.ts
Normal file
56
packages/molang/src/parser/expressions/loop.ts
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
import { Expression, IExpression } from '../expression'
|
||||||
|
|
||||||
|
export class LoopExpression extends Expression {
|
||||||
|
type = 'LoopExpression'
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
protected count: IExpression,
|
||||||
|
protected expression: IExpression
|
||||||
|
) {
|
||||||
|
super()
|
||||||
|
}
|
||||||
|
|
||||||
|
get allExpressions() {
|
||||||
|
return [this.count, this.expression]
|
||||||
|
}
|
||||||
|
setExpressionAt(index: number, expr: IExpression) {
|
||||||
|
if (index === 0) this.count = expr
|
||||||
|
else if (index === 1) this.expression = expr
|
||||||
|
}
|
||||||
|
|
||||||
|
get isReturn() {
|
||||||
|
return this.expression.isReturn
|
||||||
|
}
|
||||||
|
|
||||||
|
isStatic() {
|
||||||
|
return this.count.isStatic() && this.expression.isStatic()
|
||||||
|
}
|
||||||
|
|
||||||
|
eval() {
|
||||||
|
const repeatCount = Number(this.count.eval())
|
||||||
|
if (Number.isNaN(repeatCount))
|
||||||
|
throw new Error(
|
||||||
|
`First loop() argument must be of type number, received "${typeof this.count.eval()}"`
|
||||||
|
)
|
||||||
|
if (repeatCount > 1024)
|
||||||
|
throw new Error(
|
||||||
|
`Cannot loop more than 1024x times, received "${repeatCount}"`
|
||||||
|
)
|
||||||
|
|
||||||
|
let i = 0
|
||||||
|
while (i < repeatCount) {
|
||||||
|
i++
|
||||||
|
const res = this.expression.eval()
|
||||||
|
|
||||||
|
if (this.expression.isBreak) break
|
||||||
|
else if (this.expression.isContinue) continue
|
||||||
|
else if (this.expression.isReturn) return res
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
toString() {
|
||||||
|
return `loop(${this.count.toString()},${this.expression.toString()})`
|
||||||
|
}
|
||||||
|
}
|
||||||
47
packages/molang/src/parser/expressions/name.ts
Normal file
47
packages/molang/src/parser/expressions/name.ts
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
import { ExecutionEnvironment } from '../../env/env'
|
||||||
|
import { Expression } from '../expression'
|
||||||
|
|
||||||
|
export class NameExpression extends Expression {
|
||||||
|
type = 'NameExpression'
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
public executionEnv: ExecutionEnvironment,
|
||||||
|
protected name: string,
|
||||||
|
protected isFunctionCall = false
|
||||||
|
) {
|
||||||
|
super()
|
||||||
|
}
|
||||||
|
|
||||||
|
get allExpressions() {
|
||||||
|
return []
|
||||||
|
}
|
||||||
|
setExpressionAt() {}
|
||||||
|
|
||||||
|
isStatic() {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
setPointer(value: unknown) {
|
||||||
|
this.executionEnv.setAt(this.name, value)
|
||||||
|
}
|
||||||
|
|
||||||
|
setFunctionCall(value = true) {
|
||||||
|
this.isFunctionCall = value
|
||||||
|
}
|
||||||
|
setName(name: string) {
|
||||||
|
this.name = name
|
||||||
|
}
|
||||||
|
setExecutionEnv(executionEnv: ExecutionEnvironment) {
|
||||||
|
this.executionEnv = executionEnv
|
||||||
|
}
|
||||||
|
|
||||||
|
eval() {
|
||||||
|
const value = this.executionEnv.getFrom(this.name)
|
||||||
|
if (!this.isFunctionCall && typeof value === 'function') return value()
|
||||||
|
return value
|
||||||
|
}
|
||||||
|
|
||||||
|
toString() {
|
||||||
|
return this.name
|
||||||
|
}
|
||||||
|
}
|
||||||
25
packages/molang/src/parser/expressions/number.ts
Normal file
25
packages/molang/src/parser/expressions/number.ts
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
import { Expression } from '../expression'
|
||||||
|
|
||||||
|
export class NumberExpression extends Expression {
|
||||||
|
type = 'NumberExpression'
|
||||||
|
|
||||||
|
constructor(protected value: number) {
|
||||||
|
super()
|
||||||
|
}
|
||||||
|
|
||||||
|
get allExpressions() {
|
||||||
|
return []
|
||||||
|
}
|
||||||
|
setExpressionAt() {}
|
||||||
|
|
||||||
|
isStatic() {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
eval() {
|
||||||
|
return this.value
|
||||||
|
}
|
||||||
|
toString() {
|
||||||
|
return '' + this.value
|
||||||
|
}
|
||||||
|
}
|
||||||
32
packages/molang/src/parser/expressions/postfix.ts
Normal file
32
packages/molang/src/parser/expressions/postfix.ts
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
import { TTokenType } from '../../tokenizer/token'
|
||||||
|
import { Expression, IExpression } from '../expression'
|
||||||
|
|
||||||
|
export class PostfixExpression extends Expression {
|
||||||
|
type = 'PostfixExpression'
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
protected expression: IExpression,
|
||||||
|
protected tokenType: TTokenType
|
||||||
|
) {
|
||||||
|
super()
|
||||||
|
}
|
||||||
|
|
||||||
|
get allExpressions() {
|
||||||
|
return [this.expression]
|
||||||
|
}
|
||||||
|
setExpressionAt(_: number, expr: IExpression) {
|
||||||
|
this.expression = expr
|
||||||
|
}
|
||||||
|
|
||||||
|
isStatic() {
|
||||||
|
return this.expression.isStatic()
|
||||||
|
}
|
||||||
|
|
||||||
|
eval() {
|
||||||
|
switch (this.tokenType) {
|
||||||
|
case 'X': {
|
||||||
|
// DO SOMETHING
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
57
packages/molang/src/parser/expressions/prefix.ts
Normal file
57
packages/molang/src/parser/expressions/prefix.ts
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
import { TTokenType } from '../../tokenizer/token'
|
||||||
|
import { Expression, IExpression } from '../expression'
|
||||||
|
|
||||||
|
export class PrefixExpression extends Expression {
|
||||||
|
type = 'PrefixExpression'
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
protected tokenType: TTokenType,
|
||||||
|
protected expression: IExpression
|
||||||
|
) {
|
||||||
|
super()
|
||||||
|
}
|
||||||
|
|
||||||
|
get allExpressions() {
|
||||||
|
return [this.expression]
|
||||||
|
}
|
||||||
|
setExpressionAt(_: number, expr: IExpression) {
|
||||||
|
this.expression = expr
|
||||||
|
}
|
||||||
|
|
||||||
|
isStatic() {
|
||||||
|
return this.expression.isStatic()
|
||||||
|
}
|
||||||
|
|
||||||
|
eval() {
|
||||||
|
const value = this.expression.eval()
|
||||||
|
|
||||||
|
if (typeof value !== 'number')
|
||||||
|
throw new Error(
|
||||||
|
`Cannot use "${
|
||||||
|
this.tokenType
|
||||||
|
}" operator in front of ${typeof value} "${value}"`
|
||||||
|
)
|
||||||
|
|
||||||
|
switch (this.tokenType) {
|
||||||
|
case 'MINUS': {
|
||||||
|
return -value
|
||||||
|
}
|
||||||
|
case 'BANG': {
|
||||||
|
return !value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
toString() {
|
||||||
|
switch (this.tokenType) {
|
||||||
|
case 'MINUS': {
|
||||||
|
return `-${this.expression.toString()}`
|
||||||
|
}
|
||||||
|
case 'BANG': {
|
||||||
|
return `!${this.expression.toString()}`
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error(`Unknown prefix operator: "${this.tokenType}"`)
|
||||||
|
}
|
||||||
|
}
|
||||||
29
packages/molang/src/parser/expressions/return.ts
Normal file
29
packages/molang/src/parser/expressions/return.ts
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
import { Expression, IExpression } from '../expression'
|
||||||
|
|
||||||
|
export class ReturnExpression extends Expression {
|
||||||
|
type = 'ReturnExpression'
|
||||||
|
isReturn = true
|
||||||
|
|
||||||
|
constructor(protected expression: IExpression) {
|
||||||
|
super()
|
||||||
|
}
|
||||||
|
|
||||||
|
get allExpressions() {
|
||||||
|
return [this.expression]
|
||||||
|
}
|
||||||
|
setExpressionAt(_: number, expr: IExpression) {
|
||||||
|
this.expression = expr
|
||||||
|
}
|
||||||
|
|
||||||
|
isStatic() {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
eval() {
|
||||||
|
return this.expression.eval()
|
||||||
|
}
|
||||||
|
|
||||||
|
toString() {
|
||||||
|
return `return ${this.expression.toString()}`
|
||||||
|
}
|
||||||
|
}
|
||||||
102
packages/molang/src/parser/expressions/statement.ts
Normal file
102
packages/molang/src/parser/expressions/statement.ts
Normal file
@@ -0,0 +1,102 @@
|
|||||||
|
import { Expression, IExpression } from '../expression'
|
||||||
|
import { StaticExpression } from './static'
|
||||||
|
import { VoidExpression } from './void'
|
||||||
|
|
||||||
|
export class StatementExpression extends Expression {
|
||||||
|
type = 'StatementExpression'
|
||||||
|
protected didReturn?: boolean = undefined
|
||||||
|
protected wasLoopBroken = false
|
||||||
|
protected wasLoopContinued = false
|
||||||
|
|
||||||
|
constructor(protected expressions: IExpression[]) {
|
||||||
|
super()
|
||||||
|
}
|
||||||
|
|
||||||
|
get allExpressions() {
|
||||||
|
return this.expressions
|
||||||
|
}
|
||||||
|
setExpressionAt(index: number, expr: IExpression) {
|
||||||
|
this.expressions[index] = expr
|
||||||
|
}
|
||||||
|
|
||||||
|
get isReturn() {
|
||||||
|
if (this.didReturn !== undefined) return this.didReturn
|
||||||
|
|
||||||
|
// This breaks scope vs. statement parsing for some reason
|
||||||
|
let i = 0
|
||||||
|
while (i < this.expressions.length) {
|
||||||
|
const expr = this.expressions[i]
|
||||||
|
|
||||||
|
if (expr.isBreak) return false
|
||||||
|
if (expr.isContinue) return false
|
||||||
|
if (expr.isReturn) {
|
||||||
|
this.didReturn = true
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
i++
|
||||||
|
}
|
||||||
|
this.didReturn = false
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
get isBreak() {
|
||||||
|
if (this.wasLoopBroken) {
|
||||||
|
this.wasLoopBroken = false
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
get isContinue() {
|
||||||
|
if (this.wasLoopContinued) {
|
||||||
|
this.wasLoopContinued = false
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
isStatic() {
|
||||||
|
let i = 0
|
||||||
|
while (i < this.expressions.length) {
|
||||||
|
if (!this.expressions[i].isStatic()) return false
|
||||||
|
i++
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
eval() {
|
||||||
|
this.didReturn = false
|
||||||
|
this.wasLoopBroken = false
|
||||||
|
this.wasLoopContinued = false
|
||||||
|
let i = 0
|
||||||
|
while (i < this.expressions.length) {
|
||||||
|
let res = this.expressions[i].eval()
|
||||||
|
|
||||||
|
if (this.expressions[i].isReturn) {
|
||||||
|
this.didReturn = true
|
||||||
|
return res
|
||||||
|
} else if (this.expressions[i].isContinue) {
|
||||||
|
this.wasLoopContinued = true
|
||||||
|
return
|
||||||
|
} else if (this.expressions[i].isBreak) {
|
||||||
|
this.wasLoopBroken = true
|
||||||
|
return
|
||||||
|
}
|
||||||
|
i++
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
toString() {
|
||||||
|
let str = ''
|
||||||
|
for (const expr of this.expressions) {
|
||||||
|
if (
|
||||||
|
expr instanceof VoidExpression ||
|
||||||
|
(expr instanceof StaticExpression && !expr.isReturn)
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
str += `${expr.toString()};`
|
||||||
|
}
|
||||||
|
|
||||||
|
return str
|
||||||
|
}
|
||||||
|
}
|
||||||
28
packages/molang/src/parser/expressions/static.ts
Normal file
28
packages/molang/src/parser/expressions/static.ts
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
import { Expression } from '../expression'
|
||||||
|
|
||||||
|
export class StaticExpression extends Expression {
|
||||||
|
type = 'StaticExpression'
|
||||||
|
constructor(protected value: unknown, public readonly isReturn = false) {
|
||||||
|
super()
|
||||||
|
}
|
||||||
|
|
||||||
|
get allExpressions() {
|
||||||
|
return []
|
||||||
|
}
|
||||||
|
setExpressionAt() {}
|
||||||
|
|
||||||
|
isStatic() {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
eval() {
|
||||||
|
return this.value
|
||||||
|
}
|
||||||
|
toString() {
|
||||||
|
let val = this.value
|
||||||
|
if (typeof val === 'string') val = `'${val}'`
|
||||||
|
|
||||||
|
if (this.isReturn) return `return ${val}`
|
||||||
|
return '' + val
|
||||||
|
}
|
||||||
|
}
|
||||||
26
packages/molang/src/parser/expressions/string.ts
Normal file
26
packages/molang/src/parser/expressions/string.ts
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
import { Expression } from '../expression'
|
||||||
|
|
||||||
|
export class StringExpression extends Expression {
|
||||||
|
type = 'StringExpression'
|
||||||
|
|
||||||
|
constructor(protected name: string) {
|
||||||
|
super()
|
||||||
|
}
|
||||||
|
|
||||||
|
get allExpressions() {
|
||||||
|
return []
|
||||||
|
}
|
||||||
|
setExpressionAt() {}
|
||||||
|
|
||||||
|
isStatic() {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
eval() {
|
||||||
|
return this.name.substring(1, this.name.length - 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
toString() {
|
||||||
|
return this.name
|
||||||
|
}
|
||||||
|
}
|
||||||
79
packages/molang/src/parser/expressions/ternary.ts
Normal file
79
packages/molang/src/parser/expressions/ternary.ts
Normal file
@@ -0,0 +1,79 @@
|
|||||||
|
import { Expression, IExpression } from '../expression'
|
||||||
|
import { VoidExpression } from './void'
|
||||||
|
|
||||||
|
export class TernaryExpression extends Expression {
|
||||||
|
type = 'TernaryExpression'
|
||||||
|
protected leftResult: unknown
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
protected leftExpression: IExpression,
|
||||||
|
protected thenExpression: IExpression,
|
||||||
|
protected elseExpression: IExpression
|
||||||
|
) {
|
||||||
|
super()
|
||||||
|
}
|
||||||
|
|
||||||
|
get allExpressions() {
|
||||||
|
if (this.leftExpression.isStatic())
|
||||||
|
return [
|
||||||
|
this.leftExpression,
|
||||||
|
this.leftExpression.eval()
|
||||||
|
? this.thenExpression
|
||||||
|
: this.elseExpression,
|
||||||
|
]
|
||||||
|
return [this.leftExpression, this.thenExpression, this.elseExpression]
|
||||||
|
}
|
||||||
|
setExpressionAt(index: number, expr: IExpression) {
|
||||||
|
if (index === 0) this.leftExpression = expr
|
||||||
|
else if (index === 1) this.thenExpression = expr
|
||||||
|
else if (index === 2) this.elseExpression = expr
|
||||||
|
}
|
||||||
|
|
||||||
|
get isReturn() {
|
||||||
|
if (this.leftResult === undefined)
|
||||||
|
return this.thenExpression.isReturn && this.elseExpression.isReturn
|
||||||
|
return this.leftResult
|
||||||
|
? this.thenExpression.isReturn
|
||||||
|
: this.elseExpression.isReturn
|
||||||
|
}
|
||||||
|
get hasReturn() {
|
||||||
|
return this.thenExpression.isReturn || this.elseExpression.isReturn
|
||||||
|
}
|
||||||
|
get isContinue() {
|
||||||
|
if (this.leftResult === undefined)
|
||||||
|
return (
|
||||||
|
this.thenExpression.isContinue && this.elseExpression.isContinue
|
||||||
|
)
|
||||||
|
return this.leftResult
|
||||||
|
? this.thenExpression.isContinue
|
||||||
|
: this.elseExpression.isContinue
|
||||||
|
}
|
||||||
|
get isBreak() {
|
||||||
|
if (this.leftResult === undefined)
|
||||||
|
return this.thenExpression.isBreak && this.elseExpression.isBreak
|
||||||
|
return this.leftResult
|
||||||
|
? this.thenExpression.isBreak
|
||||||
|
: this.elseExpression.isBreak
|
||||||
|
}
|
||||||
|
|
||||||
|
isStatic() {
|
||||||
|
return (
|
||||||
|
this.leftExpression.isStatic() &&
|
||||||
|
this.thenExpression.isStatic() &&
|
||||||
|
this.elseExpression.isStatic()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
eval() {
|
||||||
|
this.leftResult = this.leftExpression.eval()
|
||||||
|
return this.leftResult
|
||||||
|
? this.thenExpression.eval()
|
||||||
|
: this.elseExpression.eval()
|
||||||
|
}
|
||||||
|
|
||||||
|
toString() {
|
||||||
|
if (this.elseExpression instanceof VoidExpression)
|
||||||
|
return `${this.leftExpression.toString()}?${this.thenExpression.toString()}`
|
||||||
|
return `${this.leftExpression.toString()}?${this.thenExpression.toString()}:${this.elseExpression.toString()}`
|
||||||
|
}
|
||||||
|
}
|
||||||
21
packages/molang/src/parser/expressions/void.ts
Normal file
21
packages/molang/src/parser/expressions/void.ts
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
import { Expression } from '../expression'
|
||||||
|
|
||||||
|
export class VoidExpression extends Expression {
|
||||||
|
type = 'VoidExpression'
|
||||||
|
|
||||||
|
get allExpressions() {
|
||||||
|
return []
|
||||||
|
}
|
||||||
|
setExpressionAt() {}
|
||||||
|
|
||||||
|
isStatic() {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
eval() {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
toString() {
|
||||||
|
return ''
|
||||||
|
}
|
||||||
|
}
|
||||||
88
packages/molang/src/parser/molang.ts
Normal file
88
packages/molang/src/parser/molang.ts
Normal file
@@ -0,0 +1,88 @@
|
|||||||
|
import { Parser } from './parse'
|
||||||
|
import { BinaryOperator } from './parselets/binaryOperator'
|
||||||
|
import { EPrecedence } from './precedence'
|
||||||
|
import { PrefixOperator } from './parselets/prefix'
|
||||||
|
import { NumberParselet } from './parselets/number'
|
||||||
|
import { NameParselet } from './parselets/name'
|
||||||
|
import { GroupParselet } from './parselets/groupParselet'
|
||||||
|
import { ReturnParselet } from './parselets/return'
|
||||||
|
import { StatementParselet } from './parselets/statement'
|
||||||
|
import { StringParselet } from './parselets/string'
|
||||||
|
import { FunctionParselet } from './parselets/function'
|
||||||
|
import { ArrayAccessParselet } from './parselets/arrayAccess'
|
||||||
|
import { ScopeParselet } from './parselets/scope'
|
||||||
|
import { LoopParselet } from './parselets/loop'
|
||||||
|
import { ForEachParselet } from './parselets/forEach'
|
||||||
|
import { ContinueParselet } from './parselets/continue'
|
||||||
|
import { BreakParselet } from './parselets/break'
|
||||||
|
import { BooleanParselet } from './parselets/boolean'
|
||||||
|
import { IParserConfig } from '../main'
|
||||||
|
import { EqualsOperator } from './parselets/equals'
|
||||||
|
import { NotEqualsOperator } from './parselets/notEquals'
|
||||||
|
import { AndOperator } from './parselets/andOperator'
|
||||||
|
import { OrOperator } from './parselets/orOperator'
|
||||||
|
import { SmallerOperator } from './parselets/smallerOperator'
|
||||||
|
import { GreaterOperator } from './parselets/greaterOperator'
|
||||||
|
import { QuestionOperator } from './parselets/questionOperator'
|
||||||
|
|
||||||
|
export class MoLangParser extends Parser {
|
||||||
|
constructor(config: Partial<IParserConfig>) {
|
||||||
|
super(config)
|
||||||
|
|
||||||
|
//Special parselets
|
||||||
|
this.registerPrefix('NAME', new NameParselet())
|
||||||
|
this.registerPrefix('STRING', new StringParselet())
|
||||||
|
this.registerPrefix('NUMBER', new NumberParselet())
|
||||||
|
this.registerPrefix('TRUE', new BooleanParselet(EPrecedence.PREFIX))
|
||||||
|
this.registerPrefix('FALSE', new BooleanParselet(EPrecedence.PREFIX))
|
||||||
|
this.registerPrefix('RETURN', new ReturnParselet())
|
||||||
|
this.registerPrefix('CONTINUE', new ContinueParselet())
|
||||||
|
this.registerPrefix('BREAK', new BreakParselet())
|
||||||
|
this.registerPrefix('LOOP', new LoopParselet())
|
||||||
|
this.registerPrefix('FOR_EACH', new ForEachParselet())
|
||||||
|
this.registerInfix(
|
||||||
|
'QUESTION',
|
||||||
|
new QuestionOperator(EPrecedence.CONDITIONAL)
|
||||||
|
)
|
||||||
|
this.registerPrefix('LEFT_PARENT', new GroupParselet())
|
||||||
|
this.registerInfix(
|
||||||
|
'LEFT_PARENT',
|
||||||
|
new FunctionParselet(EPrecedence.FUNCTION)
|
||||||
|
)
|
||||||
|
this.registerInfix(
|
||||||
|
'ARRAY_LEFT',
|
||||||
|
new ArrayAccessParselet(EPrecedence.ARRAY_ACCESS)
|
||||||
|
)
|
||||||
|
this.registerPrefix('CURLY_LEFT', new ScopeParselet(EPrecedence.SCOPE))
|
||||||
|
this.registerInfix(
|
||||||
|
'SEMICOLON',
|
||||||
|
new StatementParselet(EPrecedence.STATEMENT)
|
||||||
|
)
|
||||||
|
|
||||||
|
//Prefix parselets
|
||||||
|
this.registerPrefix('MINUS', new PrefixOperator(EPrecedence.PREFIX))
|
||||||
|
this.registerPrefix('BANG', new PrefixOperator(EPrecedence.PREFIX))
|
||||||
|
|
||||||
|
//Postfix parselets
|
||||||
|
//Nothing here yet
|
||||||
|
|
||||||
|
//Infix parselets
|
||||||
|
this.registerInfix('PLUS', new BinaryOperator(EPrecedence.SUM))
|
||||||
|
this.registerInfix('MINUS', new BinaryOperator(EPrecedence.SUM))
|
||||||
|
this.registerInfix('ASTERISK', new BinaryOperator(EPrecedence.PRODUCT))
|
||||||
|
this.registerInfix('SLASH', new BinaryOperator(EPrecedence.PRODUCT))
|
||||||
|
this.registerInfix(
|
||||||
|
'EQUALS',
|
||||||
|
new EqualsOperator(EPrecedence.EQUALS_COMPARE)
|
||||||
|
)
|
||||||
|
this.registerInfix(
|
||||||
|
'BANG',
|
||||||
|
new NotEqualsOperator(EPrecedence.EQUALS_COMPARE)
|
||||||
|
)
|
||||||
|
this.registerInfix('GREATER', new GreaterOperator(EPrecedence.COMPARE))
|
||||||
|
this.registerInfix('SMALLER', new SmallerOperator(EPrecedence.COMPARE))
|
||||||
|
this.registerInfix('AND', new AndOperator(EPrecedence.AND))
|
||||||
|
this.registerInfix('OR', new OrOperator(EPrecedence.OR))
|
||||||
|
this.registerInfix('ASSIGN', new BinaryOperator(EPrecedence.ASSIGNMENT))
|
||||||
|
}
|
||||||
|
}
|
||||||
118
packages/molang/src/parser/parse.ts
Normal file
118
packages/molang/src/parser/parse.ts
Normal file
@@ -0,0 +1,118 @@
|
|||||||
|
import { Tokenizer } from '../tokenizer/Tokenizer'
|
||||||
|
import { TTokenType, Token } from '../tokenizer/token'
|
||||||
|
import { IPrefixParselet } from './parselets/prefix'
|
||||||
|
import { IInfixParselet } from './parselets/infix'
|
||||||
|
import { IExpression } from './expression'
|
||||||
|
import { ExecutionEnvironment } from '../env/env'
|
||||||
|
import { IParserConfig } from '../main'
|
||||||
|
import { VoidExpression } from './expressions/void'
|
||||||
|
|
||||||
|
export class Parser {
|
||||||
|
protected prefixParselets = new Map<TTokenType, IPrefixParselet>()
|
||||||
|
protected infixParselets = new Map<TTokenType, IInfixParselet>()
|
||||||
|
protected readTokens: Token[] = []
|
||||||
|
protected tokenIterator = new Tokenizer()
|
||||||
|
executionEnv!: ExecutionEnvironment
|
||||||
|
|
||||||
|
constructor(public config: Partial<IParserConfig>) {}
|
||||||
|
|
||||||
|
updateConfig(config: Partial<IParserConfig>) {
|
||||||
|
this.config = config
|
||||||
|
}
|
||||||
|
|
||||||
|
init(expression: string) {
|
||||||
|
this.tokenIterator.init(expression)
|
||||||
|
this.readTokens = []
|
||||||
|
}
|
||||||
|
setTokenizer(tokenizer: Tokenizer) {
|
||||||
|
this.tokenIterator = tokenizer
|
||||||
|
}
|
||||||
|
setExecutionEnvironment(executionEnv: ExecutionEnvironment) {
|
||||||
|
this.executionEnv = executionEnv
|
||||||
|
}
|
||||||
|
|
||||||
|
parseExpression(precedence = 0): IExpression {
|
||||||
|
let token = this.consume()
|
||||||
|
if (token.getType() === 'EOF') return new VoidExpression()
|
||||||
|
|
||||||
|
const prefix = this.prefixParselets.get(token.getType())
|
||||||
|
if (!prefix) {
|
||||||
|
throw new Error(
|
||||||
|
`Cannot parse ${token.getType()} expression "${token.getType()}"`
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
let expressionLeft = prefix.parse(this, token)
|
||||||
|
return this.parseInfixExpression(expressionLeft, precedence)
|
||||||
|
}
|
||||||
|
|
||||||
|
parseInfixExpression(expressionLeft: IExpression, precedence = 0) {
|
||||||
|
let token
|
||||||
|
|
||||||
|
while (this.getPrecedence() > precedence) {
|
||||||
|
token = this.consume()
|
||||||
|
let tokenType = token.getType()
|
||||||
|
if (tokenType === 'EQUALS' && !this.match('EQUALS')) {
|
||||||
|
tokenType = 'ASSIGN'
|
||||||
|
}
|
||||||
|
|
||||||
|
const infix = <IInfixParselet>this.infixParselets.get(tokenType)
|
||||||
|
if (!infix)
|
||||||
|
throw new Error(`Unknown infix parselet: "${tokenType}"`)
|
||||||
|
expressionLeft = infix.parse(this, expressionLeft, token)
|
||||||
|
}
|
||||||
|
|
||||||
|
return expressionLeft
|
||||||
|
}
|
||||||
|
|
||||||
|
getPrecedence() {
|
||||||
|
const parselet = this.infixParselets.get(this.lookAhead(0).getType())
|
||||||
|
return parselet?.precedence ?? 0
|
||||||
|
}
|
||||||
|
|
||||||
|
consume(expected?: TTokenType) {
|
||||||
|
//Sets the lastLineNumber & startColumn before consuming next token
|
||||||
|
//Used for getting the exact location an error occurs
|
||||||
|
// this.tokenIterator.step()
|
||||||
|
|
||||||
|
const token = this.lookAhead(0)
|
||||||
|
|
||||||
|
if (expected && token.getType() !== expected) {
|
||||||
|
throw new Error(
|
||||||
|
`Expected token "${expected}" and found "${token.getType()}"`
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
this.readTokens.shift()!
|
||||||
|
return token
|
||||||
|
}
|
||||||
|
|
||||||
|
match(expected: TTokenType, consume = true) {
|
||||||
|
const token = this.lookAhead(0)
|
||||||
|
if (token.getType() !== expected) return false
|
||||||
|
|
||||||
|
if (consume) this.consume()
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
lookAhead(distance: number) {
|
||||||
|
while (distance >= this.readTokens.length)
|
||||||
|
this.readTokens.push(this.tokenIterator.next())
|
||||||
|
|
||||||
|
return this.readTokens[distance]
|
||||||
|
}
|
||||||
|
|
||||||
|
registerInfix(tokenType: TTokenType, infixParselet: IInfixParselet) {
|
||||||
|
this.infixParselets.set(tokenType, infixParselet)
|
||||||
|
}
|
||||||
|
registerPrefix(tokenType: TTokenType, prefixParselet: IPrefixParselet) {
|
||||||
|
this.prefixParselets.set(tokenType, prefixParselet)
|
||||||
|
}
|
||||||
|
|
||||||
|
getInfix(tokenType: TTokenType) {
|
||||||
|
return this.infixParselets.get(tokenType)
|
||||||
|
}
|
||||||
|
getPrefix(tokenType: TTokenType) {
|
||||||
|
return this.prefixParselets.get(tokenType)
|
||||||
|
}
|
||||||
|
}
|
||||||
21
packages/molang/src/parser/parselets/andOperator.ts
Normal file
21
packages/molang/src/parser/parselets/andOperator.ts
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
import { Parser } from '../parse'
|
||||||
|
import { Token } from '../../tokenizer/token'
|
||||||
|
import { IExpression } from '../expression'
|
||||||
|
import { GenericOperatorExpression } from '../expressions/genericOperator'
|
||||||
|
import { IInfixParselet } from './infix'
|
||||||
|
|
||||||
|
export class AndOperator implements IInfixParselet {
|
||||||
|
constructor(public precedence = 0) {}
|
||||||
|
|
||||||
|
parse(parser: Parser, leftExpression: IExpression, token: Token) {
|
||||||
|
if (parser.match('AND'))
|
||||||
|
return new GenericOperatorExpression(
|
||||||
|
leftExpression,
|
||||||
|
parser.parseExpression(this.precedence),
|
||||||
|
'&&',
|
||||||
|
(leftExpression: IExpression, rightExpression: IExpression) =>
|
||||||
|
leftExpression.eval() && rightExpression.eval()
|
||||||
|
)
|
||||||
|
else throw new Error(`"&" not followed by another "&"`)
|
||||||
|
}
|
||||||
|
}
|
||||||
22
packages/molang/src/parser/parselets/arrayAccess.ts
Normal file
22
packages/molang/src/parser/parselets/arrayAccess.ts
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
import { Token } from '../../tokenizer/token'
|
||||||
|
import { Parser } from '../parse'
|
||||||
|
import { IInfixParselet } from './infix'
|
||||||
|
import { IExpression } from '../expression'
|
||||||
|
import { ArrayAccessExpression } from '../expressions/arrayAccess'
|
||||||
|
|
||||||
|
export class ArrayAccessParselet implements IInfixParselet {
|
||||||
|
constructor(public precedence = 0) {}
|
||||||
|
|
||||||
|
parse(parser: Parser, left: IExpression, token: Token) {
|
||||||
|
const expr = parser.parseExpression(this.precedence - 1)
|
||||||
|
|
||||||
|
if (!left.setPointer) throw new Error(`"${left.type}" is not an array`)
|
||||||
|
|
||||||
|
if (!parser.match('ARRAY_RIGHT'))
|
||||||
|
throw new Error(
|
||||||
|
`No closing bracket for opening bracket "[${expr.eval()}"`
|
||||||
|
)
|
||||||
|
|
||||||
|
return new ArrayAccessExpression(left, expr)
|
||||||
|
}
|
||||||
|
}
|
||||||
134
packages/molang/src/parser/parselets/binaryOperator.ts
Normal file
134
packages/molang/src/parser/parselets/binaryOperator.ts
Normal file
@@ -0,0 +1,134 @@
|
|||||||
|
import { IInfixParselet } from './infix'
|
||||||
|
import { Parser } from '../parse'
|
||||||
|
import { IExpression } from '../expression'
|
||||||
|
import { Token } from '../../tokenizer/token'
|
||||||
|
import { GenericOperatorExpression } from '../expressions/genericOperator'
|
||||||
|
|
||||||
|
const plusHelper = (
|
||||||
|
leftExpression: IExpression,
|
||||||
|
rightExpression: IExpression
|
||||||
|
) => {
|
||||||
|
const leftValue = leftExpression.eval()
|
||||||
|
const rightValue = rightExpression.eval()
|
||||||
|
if (
|
||||||
|
!(typeof leftValue === 'number' || typeof leftValue === 'boolean') ||
|
||||||
|
!(typeof rightValue === 'number' || typeof rightValue === 'boolean')
|
||||||
|
)
|
||||||
|
throw new Error(
|
||||||
|
`Cannot use numeric operators for expression "${leftValue} + ${rightValue}"`
|
||||||
|
)
|
||||||
|
//@ts-ignore
|
||||||
|
return leftValue + rightValue
|
||||||
|
}
|
||||||
|
const minusHelper = (
|
||||||
|
leftExpression: IExpression,
|
||||||
|
rightExpression: IExpression
|
||||||
|
) => {
|
||||||
|
const leftValue = leftExpression.eval()
|
||||||
|
const rightValue = rightExpression.eval()
|
||||||
|
if (
|
||||||
|
!(typeof leftValue === 'number' || typeof leftValue === 'boolean') ||
|
||||||
|
!(typeof rightValue === 'number' || typeof rightValue === 'boolean')
|
||||||
|
)
|
||||||
|
throw new Error(
|
||||||
|
`Cannot use numeric operators for expression "${leftValue} - ${rightValue}"`
|
||||||
|
)
|
||||||
|
//@ts-ignore
|
||||||
|
return leftValue - rightValue
|
||||||
|
}
|
||||||
|
const divideHelper = (
|
||||||
|
leftExpression: IExpression,
|
||||||
|
rightExpression: IExpression
|
||||||
|
) => {
|
||||||
|
const leftValue = leftExpression.eval()
|
||||||
|
const rightValue = rightExpression.eval()
|
||||||
|
if (
|
||||||
|
!(typeof leftValue === 'number' || typeof leftValue === 'boolean') ||
|
||||||
|
!(typeof rightValue === 'number' || typeof rightValue === 'boolean')
|
||||||
|
)
|
||||||
|
throw new Error(
|
||||||
|
`Cannot use numeric operators for expression "${leftValue} / ${rightValue}"`
|
||||||
|
)
|
||||||
|
//@ts-ignore
|
||||||
|
return leftValue / rightValue
|
||||||
|
}
|
||||||
|
const multiplyHelper = (
|
||||||
|
leftExpression: IExpression,
|
||||||
|
rightExpression: IExpression
|
||||||
|
) => {
|
||||||
|
const leftValue = leftExpression.eval()
|
||||||
|
const rightValue = rightExpression.eval()
|
||||||
|
if (
|
||||||
|
!(typeof leftValue === 'number' || typeof leftValue === 'boolean') ||
|
||||||
|
!(typeof rightValue === 'number' || typeof rightValue === 'boolean')
|
||||||
|
)
|
||||||
|
throw new Error(
|
||||||
|
`Cannot use numeric operators for expression "${leftValue} * ${rightValue}"`
|
||||||
|
)
|
||||||
|
//@ts-ignore
|
||||||
|
return leftValue * rightValue
|
||||||
|
}
|
||||||
|
const assignHelper = (
|
||||||
|
leftExpression: IExpression,
|
||||||
|
rightExpression: IExpression
|
||||||
|
) => {
|
||||||
|
if (leftExpression.setPointer) {
|
||||||
|
leftExpression.setPointer(rightExpression.eval())
|
||||||
|
return 0
|
||||||
|
} else {
|
||||||
|
throw Error(`Cannot assign to ${leftExpression.type}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class BinaryOperator implements IInfixParselet {
|
||||||
|
constructor(public precedence = 0) {}
|
||||||
|
|
||||||
|
parse(parser: Parser, leftExpression: IExpression, token: Token) {
|
||||||
|
const rightExpression = parser.parseExpression(this.precedence)
|
||||||
|
// return new AdditionExpression(leftExpression, rightExpression)
|
||||||
|
|
||||||
|
const tokenText = token.getText()
|
||||||
|
|
||||||
|
switch (tokenText) {
|
||||||
|
case '+':
|
||||||
|
return new GenericOperatorExpression(
|
||||||
|
leftExpression,
|
||||||
|
rightExpression,
|
||||||
|
tokenText,
|
||||||
|
plusHelper
|
||||||
|
)
|
||||||
|
case '-':
|
||||||
|
return new GenericOperatorExpression(
|
||||||
|
leftExpression,
|
||||||
|
rightExpression,
|
||||||
|
tokenText,
|
||||||
|
minusHelper
|
||||||
|
)
|
||||||
|
case '*':
|
||||||
|
return new GenericOperatorExpression(
|
||||||
|
leftExpression,
|
||||||
|
rightExpression,
|
||||||
|
tokenText,
|
||||||
|
multiplyHelper
|
||||||
|
)
|
||||||
|
case '/':
|
||||||
|
return new GenericOperatorExpression(
|
||||||
|
leftExpression,
|
||||||
|
rightExpression,
|
||||||
|
tokenText,
|
||||||
|
divideHelper
|
||||||
|
)
|
||||||
|
case '=': {
|
||||||
|
return new GenericOperatorExpression(
|
||||||
|
leftExpression,
|
||||||
|
rightExpression,
|
||||||
|
'=',
|
||||||
|
assignHelper
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
default:
|
||||||
|
throw new Error(`Operator not implemented`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
12
packages/molang/src/parser/parselets/boolean.ts
Normal file
12
packages/molang/src/parser/parselets/boolean.ts
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
import { IPrefixParselet } from './prefix'
|
||||||
|
import { Token } from '../../tokenizer/token'
|
||||||
|
import { Parser } from '../parse'
|
||||||
|
import { BooleanExpression } from '../expressions/boolean'
|
||||||
|
|
||||||
|
export class BooleanParselet implements IPrefixParselet {
|
||||||
|
constructor(public precedence = 0) {}
|
||||||
|
|
||||||
|
parse(parser: Parser, token: Token) {
|
||||||
|
return new BooleanExpression(token.getText() === 'true')
|
||||||
|
}
|
||||||
|
}
|
||||||
12
packages/molang/src/parser/parselets/break.ts
Normal file
12
packages/molang/src/parser/parselets/break.ts
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
import { Parser } from '../parse'
|
||||||
|
import { Token } from '../../tokenizer/token'
|
||||||
|
import { IPrefixParselet } from './prefix'
|
||||||
|
import { BreakExpression } from '../expressions/break'
|
||||||
|
|
||||||
|
export class BreakParselet implements IPrefixParselet {
|
||||||
|
constructor(public precedence = 0) {}
|
||||||
|
|
||||||
|
parse(parser: Parser, token: Token) {
|
||||||
|
return new BreakExpression()
|
||||||
|
}
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user