diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0b0d6bf..8aae435 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -29,8 +29,6 @@ jobs: - "cargo test --features mlua,mlua_vendored,mlua_lua54,mlua_async,mlua_send" - "cargo test --features mlua,mlua_vendored,mlua_lua53,mlua_async --no-run" - "cargo test --features mlua,mlua_vendored,mlua_lua54,mlua_async --no-run" - - "cargo test --features rlua,rlua_builtin-lua54" - - "cargo test --features rlua,rlua_builtin-lua53" steps: - uses: actions/checkout@master - uses: hecrj/setup-rust-action@v1.3.4 @@ -52,8 +50,6 @@ jobs: - "cargo clippy --features mlua,mlua_vendored,mlua_lua54,mlua_async,mlua_send -- -D warnings" - "cargo clippy --features mlua,mlua_vendored,mlua_lua53,mlua_async,mlua_send -- -D warnings" - "cargo clippy --features mlua,mlua_vendored,mlua_luau,mlua_async,mlua_send -- -D warnings" - - "cargo clippy --features rlua,rlua_builtin-lua54 -- -D warnings" - - "cargo clippy --features rlua,rlua_builtin-lua53 -- -D warnings" steps: - uses: hecrj/setup-rust-action@v1.3.4 with: diff --git a/.vscode/settings.json b/.vscode/settings.json index 49f6792..bb52a91 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -10,7 +10,6 @@ "metamethod", "mlua", "multivalue", - "rlua", "str's", "struct", "tealr", diff --git a/Cargo.lock b/Cargo.lock index d4becbd..2050579 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3,16 +3,16 @@ version = 3 [[package]] -name = "adler" -version = "1.0.2" +name = "adler2" +version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" +checksum = "512761e0bb2578dd7380c6baaa0f4ce03e84f95e960231d1dec8bf4d7d6e2627" [[package]] name = "aes" -version = "0.8.3" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac1f845298e95f983ff1944b728ae08b8cebab80d684f0a832ed0fc74dfa27e2" +checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" dependencies = [ "cfg-if", "cipher", @@ -28,6 +28,15 @@ dependencies = [ "memchr", ] +[[package]] +name = "arbitrary" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d5a26814d8dcb93b0e5a0ff3c6d80a8843bafb21b39e8e18a6f05471870e110" +dependencies = [ + "derive_arbitrary", +] + [[package]] name = "autocfg" version = "1.1.0" @@ -40,18 +49,6 @@ version = "0.21.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "35636a1494ede3b646cc98f74f8e62c773a38a659ebc777a2cf26b9b74171df9" -[[package]] -name = "base64ct" -version = "1.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8c3c1a368f70d6cf7302d78f8f7093da241fb8e8807c05cc9e51a125895a6d5b" - -[[package]] -name = "bitflags" -version = "1.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" - [[package]] name = "bitflags" version = "2.4.1" @@ -69,22 +66,19 @@ dependencies = [ [[package]] name = "bstr" -version = "0.2.17" +version = "1.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba3569f383e8f1598449f1a423e72e99569137b47740b1da11ef19af3d5c3223" +checksum = "40723b8fb387abc38f4f4a37c09073622e41dd12327033091ef8950659e6dc0c" dependencies = [ "memchr", + "serde", ] [[package]] -name = "bstr" -version = "1.8.0" +name = "bumpalo" +version = "3.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "542f33a8835a0884b006a0c3df3dadd99c0c3f296ed26c2fdc8028e01ad6230c" -dependencies = [ - "memchr", - "serde", -] +checksum = "79296716171880943b8470b5f8d03aa55eb2e645a4874bdbb28adb49162e012c" [[package]] name = "byteorder" @@ -115,12 +109,13 @@ dependencies = [ [[package]] name = "cc" -version = "1.0.83" +version = "1.1.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1174fb0b6ec23863f8b971027804a42614e347eafb0a95bf0b12cdae21fc4d0" +checksum = "c2e7962b54006dcfcc61cb72735f4d89bb97061dd6a7ed882ec6b8ee53714c6f" dependencies = [ "jobserver", "libc", + "shlex", ] [[package]] @@ -141,9 +136,9 @@ dependencies = [ [[package]] name = "constant_time_eq" -version = "0.1.5" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "245097e9a4535ee1e3e3931fcfcd55a796a44c643e8596ff6566d68f09b87bbc" +checksum = "7c74b8349d32d297c9134b8c88677813a227df8f779daa29bfc29c183fe3dca6" [[package]] name = "cpufeatures" @@ -155,23 +150,35 @@ dependencies = [ ] [[package]] -name = "crc32fast" -version = "1.3.2" +name = "crc" +version = "3.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b540bd8bc810d3885c6ea91e2018302f68baba2129ab3e88f32389ee9370880d" +checksum = "69e6e4d7b33a94f0991c26729976b10ebde1d34c3ee82408fb536164fa10d636" dependencies = [ - "cfg-if", + "crc-catalog", ] [[package]] -name = "crossbeam-utils" -version = "0.8.17" +name = "crc-catalog" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19d374276b40fb8bbdee95aef7c7fa6b5316ec764510eb64b8dd0e2ed0d7e7f5" + +[[package]] +name = "crc32fast" +version = "1.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c06d96137f14f244c37f989d9fff8f95e6c18b918e71f36638f8c49112e4c78f" +checksum = "a97769d94ddab943e4510d138150169a2758b5ef3eb191a9ee688de3e23ef7b3" dependencies = [ "cfg-if", ] +[[package]] +name = "crossbeam-utils" +version = "0.8.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22ec99545bb0ed0ea7bb9b8e1e9122ea386ff8a48c0922e43f36d45ab09e0e80" + [[package]] name = "crypto-common" version = "0.1.6" @@ -182,6 +189,12 @@ dependencies = [ "typenum", ] +[[package]] +name = "deflate64" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da692b8d1080ea3045efaab14434d40468c3d8657e42abddfffca87b428f4c1b" + [[package]] name = "deranged" version = "0.3.10" @@ -191,6 +204,17 @@ dependencies = [ "powerfmt", ] +[[package]] +name = "derive_arbitrary" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67e77553c4162a157adbf834ebae5b415acbecbeafc7a74b0e886657506a7611" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.85", +] + [[package]] name = "digest" version = "0.10.7" @@ -202,19 +226,37 @@ dependencies = [ "subtle", ] +[[package]] +name = "displaydoc" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.85", +] + [[package]] name = "either" version = "1.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a26ae43d7bcc3b814de94796a5e736d4029efb0ee900c12e2d54c993ad1a1e07" +[[package]] +name = "equivalent" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5" + [[package]] name = "erased-serde" -version = "0.3.31" +version = "0.4.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c138974f9d5e7fe373eb04df7cae98833802ae4b11c24ac7039a21d5af4b26c" +checksum = "24e2389d65ab4fab27dc2a5de7b191e1f6617d1f1c8855c0dc569c94a4cbb18d" dependencies = [ "serde", + "typeid", ] [[package]] @@ -229,15 +271,15 @@ dependencies = [ [[package]] name = "fastrand" -version = "2.0.1" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25cbce373ec4653f1a01a31e8a5e5ec0c622dc27ff9c4e6606eefef5cbbed4a5" +checksum = "e8c02a5121d4ea3eb16a80748c74f5549a5665e4c21333c6098f283870fbdea6" [[package]] name = "flate2" -version = "1.0.28" +version = "1.0.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46303f565772937ffe1d394a4fac6f411c6013172fadde9dcdb1e147a086940e" +checksum = "a1b589b4dc103969ad3cf85c950899926ec64300a1a46d76c03a6072957036f0" dependencies = [ "crc32fast", "miniz_oxide", @@ -298,6 +340,12 @@ dependencies = [ "wasi", ] +[[package]] +name = "hashbrown" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e087f84d4f86bf4b218b927129862374b72199ae7d8657835f1e89000eea4fb" + [[package]] name = "hmac" version = "0.12.1" @@ -327,28 +375,29 @@ dependencies = [ ] [[package]] -name = "inout" -version = "0.1.3" +name = "indexmap" +version = "2.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a0c10553d664a4d0bcff9f4215d0aac67a639cc68ef660840afe309b807bc9f5" +checksum = "707907fe3c25f5424cce2cb7e1cbcafee6bdbe735ca90ef77c29e84591e5b9da" dependencies = [ - "generic-array", + "equivalent", + "hashbrown", ] [[package]] -name = "itertools" -version = "0.10.5" +name = "inout" +version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0fd2260e829bddf4cb6ea802289de2f86d6a7a690192fbe91b3f46e0f2c8473" +checksum = "a0c10553d664a4d0bcff9f4215d0aac67a639cc68ef660840afe309b807bc9f5" dependencies = [ - "either", + "generic-array", ] [[package]] name = "itertools" -version = "0.11.0" +version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1c173a5686ce8bfa551b3563d0c2170bf24ca44da99c7ca4bfdab5418c3fe57" +checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" dependencies = [ "either", ] @@ -361,18 +410,18 @@ checksum = "b1a46d1a171d865aa5f83f92695765caa047a9b4cbae2cbf37dbd613a793fd4c" [[package]] name = "jobserver" -version = "0.1.27" +version = "0.1.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8c37f63953c4c63420ed5fd3d6d398c719489b9f872b9fa683262f8edd363c7d" +checksum = "48d1dbcbbeb6a7fec7e059840aa538bd62aaccf972c7346c4d9d2059312853d0" dependencies = [ "libc", ] [[package]] name = "libc" -version = "0.2.151" +version = "0.2.161" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "302d7ab3130588088d277783b1e2d2e10c9e9e4a16dd9050e6ec93fb3e7048f4" +checksum = "8e9489c2807c139ffd9c1794f4af0ebe86a828db53ecdc7fea2111d0fed085d1" [[package]] name = "libloading" @@ -386,21 +435,37 @@ dependencies = [ [[package]] name = "linux-raw-sys" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78b3ae25bc7c8c38cec158d1f2757ee79e9b3740fbc7ccf0e59e4b08d793fa89" + +[[package]] +name = "lock_api" version = "0.4.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4cd1a83af159aa67994778be9070f0ae1bd732942279cabb14f86f986a21456" +checksum = "07af8b9cdd281b7915f413fa73f29ebd5d55d0d3f0155584dade1ff18cea1b17" +dependencies = [ + "autocfg", + "scopeguard", +] + +[[package]] +name = "lockfree-object-pool" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9374ef4228402d4b7e403e5838cb880d9ee663314b0a900d5a6aabf0c213552e" [[package]] name = "log" -version = "0.4.20" +version = "0.4.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5e6163cb8c49088c2c36f57875e58ccd8c87c7427f7fbd50ea6710b2f3f2e8f" +checksum = "a7a70ba024b9dc04c27ea2f0c0548feb474ec5c54bba33a7f72f873a39d07b24" [[package]] name = "lua-src" -version = "546.0.2" +version = "547.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2da0daa7eee611a4c30c8f5ee31af55266e26e573971ba9336d2993e2da129b2" +checksum = "1edaf29e3517b49b8b746701e5648ccb5785cde1c119062cbabbc5d5cd115e42" dependencies = [ "cc", ] @@ -417,42 +482,53 @@ dependencies = [ [[package]] name = "luau0-src" -version = "0.7.11+luau606" +version = "0.11.0+luau647" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07ffc4945ee953a33cb2b331e00b19e11275fc105c8ac8a977c810597d790f08" +checksum = "ca47356c40f9121e3b3d582bf7355e8b25751b2e8afdfda49cf05775dfbc6b0a" dependencies = [ "cc", ] +[[package]] +name = "lzma-rs" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "297e814c836ae64db86b36cf2a557ba54368d03f6afcd7d947c266692f71115e" +dependencies = [ + "byteorder", + "crc", +] + [[package]] name = "memchr" -version = "2.6.4" +version = "2.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f665ee40bc4a3c5590afb1e9677db74a508659dfd71e126420da8274909a0167" +checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" [[package]] name = "miniz_oxide" -version = "0.7.1" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7810e0be55b428ada41041c41f32c9f1a42817901b4ccf45fa3d4b6561e74c7" +checksum = "e2d80299ef12ff69b16a84bb182e3b9df68b5a91574d3d4fa6e41b65deec4df1" dependencies = [ - "adler", + "adler2", ] [[package]] name = "mlua" -version = "0.9.2" +version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7c81f8ac20188feb5461a73eabb22a34dd09d6d58513535eb587e46bff6ba250" +checksum = "0f6ddbd668297c46be4bdea6c599dcc1f001a129586272d53170b7ac0a62961e" dependencies = [ - "bstr 1.8.0", + "bstr", + "either", "erased-serde", "futures-util", "libloading", "mlua-sys", "mlua_derive", "num-traits", - "once_cell", + "parking_lot", "rustc-hash", "serde", "serde-value", @@ -460,9 +536,9 @@ dependencies = [ [[package]] name = "mlua-sys" -version = "0.4.0" +version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc29228347d6bdc9e613dc95c69df2817f755434ee0f7f3b27b57755fe238b7f" +checksum = "e9eebac25c35a13285456c88ee2fde93d9aee8bcfdaf03f9d6d12be3391351ec" dependencies = [ "cc", "cfg-if", @@ -474,19 +550,25 @@ dependencies = [ [[package]] name = "mlua_derive" -version = "0.9.0" +version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f359220f24e6452dd82a3f50d7242d4aab822b5594798048e953d7a9e0314c6" +checksum = "2cfc5faa2e0d044b3f5f0879be2920e0a711c97744c42cf1c295cb183668933e" dependencies = [ - "itertools 0.11.0", + "itertools", "once_cell", "proc-macro-error", "proc-macro2", "quote", "regex", - "syn 2.0.41", + "syn 2.0.85", ] +[[package]] +name = "num-conv" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51d515d32fb182ee37cda2ccdcb92950d6a3c2893aa280e540671c2cd0f3b1d9" + [[package]] name = "num-traits" version = "0.2.17" @@ -512,26 +594,36 @@ dependencies = [ ] [[package]] -name = "password-hash" -version = "0.4.2" +name = "parking_lot" +version = "0.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7676374caaee8a325c9e7a2ae557f216c5563a171d6997b0ef8a65af35147700" +checksum = "f1bf18183cf54e8d6059647fc3063646a1801cf30896933ec2311622cc4b9a27" dependencies = [ - "base64ct", - "rand_core", - "subtle", + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e401f977ab385c9e4e3ab30627d6f26d00e2c73eef317493c4ec6d468726cf8" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-targets 0.52.6", ] [[package]] name = "pbkdf2" -version = "0.11.0" +version = "0.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "83a0692ec44e4cf1ef28ca317f14f8f07da2d95ec3fa01f86e4467b725e60917" +checksum = "f8ed6a7761f76e3b9f92dfb0a60a6a6477c61024b775147ff0973a02653abaf2" dependencies = [ "digest", "hmac", - "password-hash", - "sha2", ] [[package]] @@ -564,6 +656,15 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" +[[package]] +name = "ppv-lite86" +version = "0.2.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77957b295656769bb8ad2b6a6b09d897d94f05c41b069aede1fcdaa675eaea04" +dependencies = [ + "zerocopy", +] + [[package]] name = "proc-macro-error" version = "1.0.4" @@ -590,35 +691,59 @@ dependencies = [ [[package]] name = "proc-macro2" -version = "1.0.70" +version = "1.0.89" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39278fbbf5fb4f646ce651690877f89d1c5811a3d4acb27700c1cb3cdb78fd3b" +checksum = "f139b0662de085916d1fb67d2b4169d1addddda1919e696f3252b740b629986e" dependencies = [ "unicode-ident", ] [[package]] name = "quote" -version = "1.0.33" +version = "1.0.37" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5267fca4496028628a95160fc423a33e8b2e6af8a5302579e322e4b520293cae" +checksum = "b5b9d34b8991d19d98081b46eacdd8eb58c6f2b201139f7c5f643cc155a633af" dependencies = [ "proc-macro2", ] +[[package]] +name = "rand" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" +dependencies = [ + "libc", + "rand_chacha", + "rand_core", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core", +] + [[package]] name = "rand_core" version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom", +] [[package]] name = "redox_syscall" -version = "0.4.1" +version = "0.5.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4722d768eff46b75989dd134e5c353f0d6296e5aaa3132e776cbdb56be7731aa" +checksum = "9b6dfecf2c74bce2466cabf93f6664d6998a69eb21e39f4207930065b27b771f" dependencies = [ - "bitflags 1.3.2", + "bitflags", ] [[package]] @@ -664,67 +789,19 @@ dependencies = [ "windows-sys 0.48.0", ] -[[package]] -name = "rlua" -version = "0.19.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d33e5ba15c3d43178f283ed5863d4531e292fc0e56fb773f3bea45f18e3a42a" -dependencies = [ - "bitflags 1.3.2", - "bstr 0.2.17", - "libc", - "num-traits", - "rlua-lua51-sys", - "rlua-lua53-sys", - "rlua-lua54-sys", -] - -[[package]] -name = "rlua-lua51-sys" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c8f4636b03fa54b5c154415f1d9333cec7a7e3bd6bc64c092a2196e488cfd52" -dependencies = [ - "cc", - "libc", - "pkg-config", -] - -[[package]] -name = "rlua-lua53-sys" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c930c9de241450277dec8617cfa540eaed711db7b0fd894316d7d7c0b6b8f4a4" -dependencies = [ - "cc", - "libc", - "pkg-config", -] - -[[package]] -name = "rlua-lua54-sys" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7aafabafe1895cb4a2be81a56d7ff3d46bf4b5d2f9cfdbea2ed404cdabe96474" -dependencies = [ - "cc", - "libc", - "pkg-config", -] - [[package]] name = "rustc-hash" -version = "1.1.0" +version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" +checksum = "583034fd73374156e66797ed8e5b0d5690409c9226b22d87cb7f19821c05d152" [[package]] name = "rustix" -version = "0.38.28" +version = "0.38.38" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72e572a5e8ca657d7366229cdde4bd14c4eb5499a9573d4d366fe1b599daa316" +checksum = "aa260229e6538e52293eeb577aabd09945a09d6d9cc0fc550ed7529056c2e32a" dependencies = [ - "bitflags 2.4.1", + "bitflags", "errno", "libc", "linux-raw-sys", @@ -759,6 +836,12 @@ version = "1.0.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f98d2aa92eebf49b69786be48e4477826b256916e84a57ff2a4f21923b48eb4c" +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + [[package]] name = "sct" version = "0.7.1" @@ -771,9 +854,9 @@ dependencies = [ [[package]] name = "serde" -version = "1.0.193" +version = "1.0.214" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25dd9975e68d0cb5aa1120c288333fc98731bd1dd12f561e468ea4728c042b89" +checksum = "f55c3193aca71c12ad7890f1785d2b73e1b9f63a0bbc353c08ef26fe03fc56b5" dependencies = [ "serde_derive", ] @@ -790,22 +873,23 @@ dependencies = [ [[package]] name = "serde_derive" -version = "1.0.193" +version = "1.0.214" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "43576ca501357b9b071ac53cdc7da8ef0cbd9493d8df094cd821777ea6e894d3" +checksum = "de523f781f095e28fa605cdce0f8307e451cc0fd14e2eb4cd2e98a355b147766" dependencies = [ "proc-macro2", "quote", - "syn 2.0.41", + "syn 2.0.85", ] [[package]] name = "serde_json" -version = "1.0.108" +version = "1.0.132" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d1c7e3eac408d115102c4c24ad393e0821bb3a5df4d506a80f85f7a742a526b" +checksum = "d726bfaff4b320266d395898905d0eba0345aae23b54aee3a737e260fd46db03" dependencies = [ "itoa", + "memchr", "ryu", "serde", ] @@ -822,15 +906,16 @@ dependencies = [ ] [[package]] -name = "sha2" -version = "0.10.8" +name = "shlex" +version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "793db75ad2bcafc3ffa7c68b215fee268f537982cd901d132f89c6343f3a3dc8" -dependencies = [ - "cfg-if", - "cpufeatures", - "digest", -] +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + +[[package]] +name = "simd-adler32" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d66dc143e6b11c1eddc06d5c423cfc97062865baf299914ab64caa38182078fe" [[package]] name = "slab" @@ -841,6 +926,12 @@ dependencies = [ "autocfg", ] +[[package]] +name = "smallvec" +version = "1.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67" + [[package]] name = "spin" version = "0.9.8" @@ -860,15 +951,14 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" dependencies = [ "proc-macro2", - "quote", "unicode-ident", ] [[package]] name = "syn" -version = "2.0.41" +version = "2.0.85" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "44c8b28c477cc3bf0e7966561e3460130e1255f7a1cf71931075f1c5e7a7e269" +checksum = "5023162dfcd14ef8f32034d8bcd4cc5ddc61ef7a247c024a33e24e1f24d21b56" dependencies = [ "proc-macro2", "quote", @@ -879,10 +969,9 @@ dependencies = [ name = "tealr" version = "0.9.1" dependencies = [ - "bstr 0.2.17", - "itertools 0.10.5", + "bstr", + "itertools", "mlua", - "rlua", "serde", "serde_json", "tealr_derive", @@ -894,7 +983,7 @@ version = "0.9.1" dependencies = [ "proc-macro2", "quote", - "syn 1.0.109", + "syn 2.0.85", "tempfile", "ureq", "venial", @@ -903,24 +992,45 @@ dependencies = [ [[package]] name = "tempfile" -version = "3.8.1" +version = "3.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ef1adac450ad7f4b3c28589471ade84f25f731a7a0fe30d71dfa9f60fd808e5" +checksum = "f0f2c9fc62d0beef6951ccffd757e241266a2c833136efbe35af6cd2567dca5b" dependencies = [ "cfg-if", "fastrand", - "redox_syscall", + "once_cell", "rustix", - "windows-sys 0.48.0", + "windows-sys 0.59.0", +] + +[[package]] +name = "thiserror" +version = "1.0.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d11abd9594d9b38965ef50805c5e469ca9cc6f197f883f717e0269a3057b3d5" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae71770322cbd277e69d762a16c444af02aa0575ac0d174f0b9562d3b37f8602" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.85", ] [[package]] name = "time" -version = "0.3.30" +version = "0.3.36" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4a34ab300f2dee6e562c10a046fc05e358b29f9bf92277f30c3c8d82275f6f5" +checksum = "5dfd88e563464686c916c7e46e623e520ddc6d79fa6641390f2e3fa86e83e885" dependencies = [ "deranged", + "num-conv", "powerfmt", "serde", "time-core", @@ -947,6 +1057,12 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" +[[package]] +name = "typeid" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e13db2e0ccd5e14a544e8a246ba2312cd25223f616442d7f2cb0e3db614236e" + [[package]] name = "typenum" version = "1.17.0" @@ -1009,9 +1125,9 @@ dependencies = [ [[package]] name = "venial" -version = "0.4.0" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3d723d4b0ebf523971bc63776095798272df2873910f16d53bb680aa2f4d609" +checksum = "6816bc32f30bf8dd1b3adb04de8406c7bf187d2f923bd9e4c0b99365d012613f" dependencies = [ "proc-macro2", "quote", @@ -1063,7 +1179,16 @@ version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" dependencies = [ - "windows-targets 0.52.0", + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets 0.52.6", ] [[package]] @@ -1083,17 +1208,18 @@ dependencies = [ [[package]] name = "windows-targets" -version = "0.52.0" +version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a18201040b24831fbb9e4eb208f8892e1f50a37feb53cc7ff887feb8f50e7cd" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" dependencies = [ - "windows_aarch64_gnullvm 0.52.0", - "windows_aarch64_msvc 0.52.0", - "windows_i686_gnu 0.52.0", - "windows_i686_msvc 0.52.0", - "windows_x86_64_gnu 0.52.0", - "windows_x86_64_gnullvm 0.52.0", - "windows_x86_64_msvc 0.52.0", + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", + "windows_i686_gnullvm", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", ] [[package]] @@ -1104,9 +1230,9 @@ checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" [[package]] name = "windows_aarch64_gnullvm" -version = "0.52.0" +version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb7764e35d4db8a7921e09562a0304bf2f93e0a51bfccee0bd0bb0b666b015ea" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" [[package]] name = "windows_aarch64_msvc" @@ -1116,9 +1242,9 @@ checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" [[package]] name = "windows_aarch64_msvc" -version = "0.52.0" +version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbaa0368d4f1d2aaefc55b6fcfee13f41544ddf36801e793edbbfd7d7df075ef" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" [[package]] name = "windows_i686_gnu" @@ -1128,9 +1254,15 @@ checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" [[package]] name = "windows_i686_gnu" -version = "0.52.0" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a28637cb1fa3560a16915793afb20081aba2c92ee8af57b4d5f28e4b3e7df313" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" [[package]] name = "windows_i686_msvc" @@ -1140,9 +1272,9 @@ checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" [[package]] name = "windows_i686_msvc" -version = "0.52.0" +version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ffe5e8e31046ce6230cc7215707b816e339ff4d4d67c65dffa206fd0f7aa7b9a" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" [[package]] name = "windows_x86_64_gnu" @@ -1152,9 +1284,9 @@ checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" [[package]] name = "windows_x86_64_gnu" -version = "0.52.0" +version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d6fa32db2bc4a2f5abeacf2b69f7992cd09dca97498da74a151a3132c26befd" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" [[package]] name = "windows_x86_64_gnullvm" @@ -1164,9 +1296,9 @@ checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" [[package]] name = "windows_x86_64_gnullvm" -version = "0.52.0" +version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a657e1e9d3f514745a572a6846d3c7aa7dbe1658c056ed9c3344c4109a6949e" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" [[package]] name = "windows_x86_64_msvc" @@ -1176,54 +1308,117 @@ checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" [[package]] name = "windows_x86_64_msvc" -version = "0.52.0" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "zerocopy" +version = "0.7.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b9b4fd18abc82b8136838da5d50bae7bdea537c574d8dc1a34ed098d6c166f0" +dependencies = [ + "byteorder", + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.7.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.85", +] + +[[package]] +name = "zeroize" +version = "1.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dff9641d1cd4be8d1a070daf9e3773c5f67e78b4d9d42263020c057706765c04" +checksum = "ced3678a2879b30306d323f4542626697a464a97c0a07c9aebf7ebca65cd4dde" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce36e65b0d2999d2aafac989fb249189a141aee1f53c612c1f37d72631959f69" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.85", +] [[package]] name = "zip" -version = "0.6.6" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "760394e246e4c28189f19d488c058bf16f564016aefac5d32bb1f3b51d5e9261" +checksum = "dc5e4288ea4057ae23afc69a4472434a87a2495cafce6632fd1c4ec9f5cf3494" dependencies = [ "aes", - "byteorder", + "arbitrary", "bzip2", "constant_time_eq", "crc32fast", "crossbeam-utils", + "deflate64", + "displaydoc", "flate2", "hmac", + "indexmap", + "lzma-rs", + "memchr", "pbkdf2", + "rand", "sha1", + "thiserror", "time", + "zeroize", + "zopfli", "zstd", ] +[[package]] +name = "zopfli" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5019f391bac5cf252e93bbcc53d039ffd62c7bfb7c150414d61369afe57e946" +dependencies = [ + "bumpalo", + "crc32fast", + "lockfree-object-pool", + "log", + "once_cell", + "simd-adler32", +] + [[package]] name = "zstd" -version = "0.11.2+zstd.1.5.2" +version = "0.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "20cc960326ece64f010d2d2107537f26dc589a6573a316bd5b1dba685fa5fde4" +checksum = "fcf2b778a664581e31e389454a7072dab1647606d44f7feea22cd5abb9c9f3f9" dependencies = [ "zstd-safe", ] [[package]] name = "zstd-safe" -version = "5.0.2+zstd.1.5.2" +version = "7.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d2a5585e04f9eea4b2a3d1eca508c4dee9592a89ef6f450c11719da0726f4db" +checksum = "54a3ab4db68cea366acc5c897c7b4d4d1b8994a9cd6e6f841f8964566a419059" dependencies = [ - "libc", "zstd-sys", ] [[package]] name = "zstd-sys" -version = "2.0.9+zstd.1.5.5" +version = "2.0.13+zstd.1.5.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e16efa8a874a0481a574084d34cc26fdb3b99627480f785888deb6386506656" +checksum = "38ff0f21cfee8f97d94cef41359e0c89aa6113028ab0291aa8ca0038995a95aa" dependencies = [ "cc", "pkg-config", diff --git a/Cargo.toml b/Cargo.toml index 4e5d2d0..04a2cdd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,7 @@ [package] authors = ["Lenscas "] categories = ["development-tools::ffi"] -description = "A crate to enhance the APIs provided by the rlua and mlua crates" +description = "A crate to enhance the APIs provided by the mlua crates" edition = "2021" keywords = ["teal", "lua", "type", "generation", "type-generation"] license = "MIT OR Apache-2.0" @@ -37,178 +37,100 @@ mlua_send = ["mlua/send"] mlua_serialize = ["mlua/serialize"] mlua_vendored = ["mlua/vendored"] -#rlua specific features -rlua_builtin-lua51 = ["rlua/builtin-lua51"] -rlua_builtin-lua53 = ["rlua/builtin-lua53"] -rlua_builtin-lua54 = ["rlua/builtin-lua54"] -rlua_system-lua51 = ["rlua/system-lua51"] -rlua_system-lua53 = ["rlua/system-lua53"] -rlua_system-lua54 = ["rlua/system-lua54"] - [dependencies] -bstr = { version = "0.2", default_features = false, features = ["std"] } -itertools = "0.10.3" -mlua = { version = "0.9.2", optional = true, default_features = false } -rlua = { version = "0.19.7", optional = true, default_features = false } +bstr = { version = "1.10.0", default-features = false, features = ["std"] } +itertools = "0.13.0" +mlua = { version = "0.10.0", optional = true, default-features = false } serde = { version = "1.0.136", features = ["derive"] } -serde_json = "1.0.91" +serde_json = "1.0.132" tealr_derive = { version = "0.9.1", optional = true, path = "./tealr_derive" } -# Rlua tests -[[test]] -name = "rlua_embed_teal" -path = "tests/rlua/embed_teal.rs" -required-features = ["rlua"] -[[test]] -name = "rlua_generics" -path = "tests/rlua/generics.rs" -required-features = ["rlua"] -[[test]] -name = "rlua_type_picker" -path = "tests/rlua/type_picker.rs" -required-features = ["rlua"] -[[test]] -name = "rlua_function_wrapper" -path = "tests/rlua/function_wrapper.rs" -required-features = ["rlua"] -[[test]] -name = "rlua_readme_pieces" -path = "tests/rlua/readme_pieces.rs" -required-features = ["rlua"] - -[[test]] -name = "rlua_meta_methods" -path = "tests/rlua/meta_methods.rs" -required-features = ["rlua"] -[[test]] -name = "rlua_to_from_derived" -path = "tests/rlua/to_from_derived.rs" -required-features = ["rlua"] - -[[test]] -name = "rlua_export_instances" -path = "tests/rlua/export_instances.rs" -required-features = ["rlua"] - -[[test]] -name = "rlua_named_parameters" -path = "tests/rlua/named_parameters.rs" -required-features = ["rlua"] - #Mlua tests [[test]] name = "mlua_embed_teal" -path = "tests/mlua/embed_teal.rs" +path = "tests/embed_teal.rs" required-features = ["mlua"] [[test]] name = "mlua_inlined_type" -path = "tests/mlua/inlined_type.rs" +path = "tests/inlined_type.rs" required-features = ["mlua"] [[test]] name = "mlua_generics" -path = "tests/mlua/generics.rs" +path = "tests/generics.rs" required-features = ["mlua"] [[test]] name = "mlua_type_picker" -path = "tests/mlua/type_picker.rs" +path = "tests/type_picker.rs" required-features = ["mlua"] [[test]] name = "mlua_async" -path = "tests/mlua/async.rs" +path = "tests/async.rs" required-features = ["mlua", "mlua_async"] [[test]] name = "mlua_function_wrapper" -path = "tests/mlua/function_wrapper.rs" +path = "tests/function_wrapper.rs" required-features = ["mlua"] [[test]] name = "mlua_readme_pieces" -path = "tests/mlua/readme_pieces.rs" +path = "tests/readme_pieces.rs" required-features = ["mlua"] [[test]] name = "mlua_meta_methods" -path = "tests/mlua/meta_methods.rs" +path = "tests/meta_methods.rs" required-features = ["mlua"] [[test]] name = "mlua_to_from_derived" -path = "tests/mlua/to_from_derived.rs" +path = "tests/to_from_derived.rs" required-features = ["mlua"] [[test]] name = "mlua_export_instances" -path = "tests/mlua/export_instances.rs" +path = "tests/export_instances.rs" required-features = ["mlua"] [[test]] name = "mlua_named_parameters" -path = "tests/mlua/named_parameters.rs" +path = "tests/named_parameters.rs" required-features = ["mlua"] -# Examples using rlua -[[example]] -name = "rlua_compile_inline_teal" -path = "examples/rlua/compile_inline_teal.rs" -required-features = ["rlua"] -[[example]] -name = "rlua_derive" -path = "examples/rlua/derive.rs" -required-features = ["rlua"] -[[example]] -name = "rlua_embed_teal" -path = "examples/rlua/embed_teal.rs" -required-features = ["rlua"] -[[example]] -name = "rlua_manual" -path = "examples/rlua/manual.rs" -required-features = ["rlua"] -[[example]] -name = "rlua_manual_documentation" -path = "examples/rlua/manual_documentation.rs" -required-features = ["rlua"] -[[example]] -name = "rlua_named_parameters" -path = "examples/rlua/named_parameters.rs" -required-features = ["rlua"] #examples using mlua [[example]] name = "mlua_compile_inline_teal" -path = "examples/mlua/compile_inline_teal.rs" +path = "examples/compile_inline_teal.rs" required-features = ["mlua"] [[example]] name = "mlua_derive" -path = "examples/mlua/derive.rs" +path = "examples/derive.rs" required-features = ["mlua"] [[example]] name = "mlua_embed_teal" -path = "examples/mlua/embed_teal.rs" +path = "examples/embed_teal.rs" required-features = ["mlua"] [[example]] name = "mlua_manual" -path = "examples/mlua/manual.rs" +path = "examples/manual.rs" required-features = ["mlua"] [[example]] name = "mlua_manual_documentation" -path = "examples/mlua/manual_documentation.rs" +path = "examples/manual_documentation.rs" required-features = ["mlua"] [[example]] name = "mlua_userdata_proxy" -path = "examples/mlua/userdata_proxy.rs" +path = "examples/userdata_proxy.rs" required-features = ["mlua"] [[example]] name = "mlua_named_parameters" -path = "examples/mlua/named_parameters.rs" +path = "examples/named_parameters.rs" required-features = ["mlua"] [package.metadata.docs.rs] features = [ - "mlua", - "rlua", - "rlua_builtin-lua54", "mlua_lua54", "mlua_vendored", "mlua_async", diff --git a/README.md b/README.md index 19ec23d..1410f72 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # tealr -A crate to enhance the APIs provided by the [rlua](https://crates.io/crates/rlua) and [mlua](https://crates.io/crates/mlua) crates +A crate to enhance the APIs provided by the [mlua](https://crates.io/crates/mlua) crates It aims to do this by improving the following: @@ -9,7 +9,7 @@ It aims to do this by improving the following: - To go along with the documentation, `tealr` also allow you to be more precise in the types your api works with. Think generic methods and typed lambdas. No more `Lua::Value` - Add macros to make it easier to work with teal, a statically typed dialect of lua. -It does this by adding new traits and replacing/extending the existing ones from [rlua](https://crates.io/crates/rlua) and [mlua](https://crates.io/crates/mlua). As a result, the api that tealr exposes is as similar as the api from those 2 crates as possible. +It does this by adding new traits and replacing/extending the existing ones from [mlua](https://crates.io/crates/mlua). As a result, the api that tealr exposes is as similar as the api from those 2 crates as possible. It also contains some macro's to easily generate new types to better express the API type wise. @@ -23,55 +23,19 @@ The library shown is Rendered html is also available at -## Note: - -Both `rlua` and `mlua` are behind the feature flags `rlua` and `mlua`. - -Tealr reexports these crates and allows you to set flags through it (the forwarded flags are the same with either the prefix `rlua_` or `mlua_`. For example if you want to enable `mlua/async` then you need to enable `tealr/mlua_async`). - -Please, do not set feature flags directly in mlua/rlua and instead set them through tealr. The API of these crates can change depending on what feature flags are set and tealr needs to be made aware of those changes. - ## Expose a value to lua/teal -Exposing types to lua as userdata is almost the same using tealr as it is using rlua and mlua +Exposing types to lua as userdata is almost the same using tealr as it is using mlua -#### Rlua: - -```rust ignore -use tealr::ToTypename; -#[derive(Clone, tealr::rlu::UserData, ToTypename)] -struct ExampleRlua {} -//now, implement rlu::TealData. -//This tells rlua what methods are available and tealr what the types are -impl tealr::rlu::TealData for ExampleRlua { - //implement your methods/functions - fn add_methods<'lua, T: tealr::rlu::TealDataMethods<'lua, Self>>(methods: &mut T) { - methods.document_type("This is documentation added to the type itself."); - - methods.document("This documentation gets added to the exposed function bellow."); - methods.add_method("example_method", |_, _, x: i8| Ok(x)); - methods.add_method_mut("example_method_mut", |_, _, x: (i8, String)| Ok(x.1)); - methods.add_function("example_function", |_, x: Vec| Ok((x, 8))); - methods.document("***You*** can also embed markdown to the documentation, which gets picked up by [tealr_doc_gen](https://github.com/lenscas/type_generator)`"); - methods.document("It is also possible to use this function multiple times. These are added as paragraphs."); - methods.add_function_mut("example_function_mut", |_, x: (bool, Option)| { - Ok(x) - }); - ///This creates the instance.help() function, which returns the documentation as a string. - methods.generate_help(); - } -} -``` - -Mlua: +#### Mlua: ```rust ignore use tealr::ToTypename; #[derive(Clone, tealr::mlu::UserData, ToTypename)] struct ExampleMlua {} -impl<'lua> FromLua<'lua> for ExampleMlua { - fn from_lua(value: mlua::prelude::LuaValue<'lua>, _: &'lua Lua) -> Result { +impl FromLua for ExampleMlua { + fn from_lua(value: mlua::prelude::LuaValue, _: &Lua) -> Result { value .as_userdata() .map(|x| x.take()) @@ -85,7 +49,7 @@ impl<'lua> FromLua<'lua> for ExampleMlua { impl tealr::mlu::TealData for ExampleMlua { //implement your methods/functions - fn add_methods<'lua, T: tealr::mlu::TealDataMethods<'lua, Self>>(methods: &mut T) { + fn add_methods>(methods: &mut T) { methods.document_type("This is documentation added to the type itself."); methods.document("This documentation gets added to the exposed function bellow."); methods.add_method("example_method", |_, _, x: i8| Ok(x)); @@ -104,7 +68,7 @@ impl tealr::mlu::TealData for ExampleMlua { ## Replacing lua::Value with better type information -Though it is perfectly possible to use the `lua::Value` from `rlua` and `mlua` they aren't the most descriptive type wise. Using them will hurt your documentation as a result. +Though it is perfectly possible to use the `lua::Value` from `mlua` it isn't the most descriptive type wise. Using it will hurt your documentation as a result. To help avoid `lua::Value` tealr comes with new types and macros that help you define your API better type wise. @@ -125,7 +89,7 @@ create_union_mlua!(enum YourTypeName = i32 | String); ### Typed functions: -Though the normal function type from both mlua and rlua is perfectly useable it doesn't contain contain any type information. To help add more type information to your api tealr comes with its own version of this function type that contains type information. +Though the normal function type from mlua is perfectly useable it doesn't contain contain any type information. To help add more type information to your api tealr comes with its own version of this function type that contains type information. ```rust ignore use tealr::{ @@ -162,7 +126,7 @@ create_generic_mlua!(X); struct Example {} impl TealData for Example { - fn add_methods<'lua, T: TealDataMethods<'lua, Self>>(methods: &mut T) { + fn add_methods>(methods: &mut T) { methods.add_method( "generic_function_callback", |lua, _, fun: TypedFunction| { @@ -172,8 +136,8 @@ impl TealData for Example { } } -impl<'lua> FromLua<'lua> for Example { - fn from_lua(value: mlua::prelude::LuaValue<'lua>, _: &'lua Lua) -> Result { +impl FromLua for Example { + fn from_lua(value: mlua::prelude::LuaValue, _: &Lua) -> Result { value .as_userdata() .map(|x| x.take()) @@ -188,8 +152,6 @@ impl<'lua> FromLua<'lua> for Example { ``` -For rlua, all you have to do is replace `mlua` for `rlua` - ## Teal integration The [teal](https://github.com/teal-language/tl) language is basically just a statically typed variant of lua and can even be made to run in the lua vm without compiling to lua first. @@ -198,9 +160,9 @@ As a result of this and `tealr`'s focus on enabling a richer typed api causes th ### Compile inline teal code into lua -Both rlua and mlua allow you to run lua code embedded in your application. +Mlua allow you to run lua code embedded in your application. -Similarly, tealr allows you to compile embedded teal code to lua while compiling your application. This can then be executed by rlua and mlua. +Similarly, tealr allows you to compile embedded teal code to lua while compiling your application. This can then be executed by mlua. This means that you can make use of teal's static type system even for small scripts inside your rust codebase. @@ -218,15 +180,7 @@ Tealr makes doing this from withing rust a bit easier, by exposing a macro that ```rust no_run use tealr::embed_compiler; let compiler = embed_compiler!("v0.13.1"); -#[cfg(feature = "rlua")] -{ - let res : u8 = tealr::rlu::rlua::Lua::new().context(|ctx| { - let code = compiler("example/basic_teal_file"); - ctx.load(&code).set_name("embedded_compiler")?.eval() - })?; -}; -#[cfg(feature = "mlua")] { let code = compiler("example/basic_teal_file"); let lua = tealr::mlu::mlua::Lua::new(); diff --git a/examples/mlua/basic_teal_file.tl b/examples/basic_teal_file.tl similarity index 100% rename from examples/mlua/basic_teal_file.tl rename to examples/basic_teal_file.tl diff --git a/examples/mlua/basic_type.d.tl b/examples/basic_type.d.tl similarity index 100% rename from examples/mlua/basic_type.d.tl rename to examples/basic_type.d.tl diff --git a/examples/mlua/basic_type.lua b/examples/basic_type.lua similarity index 100% rename from examples/mlua/basic_type.lua rename to examples/basic_type.lua diff --git a/examples/mlua/compile_inline_teal.rs b/examples/compile_inline_teal.rs similarity index 78% rename from examples/mlua/compile_inline_teal.rs rename to examples/compile_inline_teal.rs index 36ccca2..43914d3 100644 --- a/examples/mlua/compile_inline_teal.rs +++ b/examples/compile_inline_teal.rs @@ -1,14 +1,14 @@ //This example shows how to build inline teal code at compile time -//This is useful if you want to write a bit of teal/lua code directly in your application that gets passed to RLua. +//This is useful if you want to write a bit of teal/lua code directly in your application that gets passed to mlua. //NOTE: At this point it requires you to have teal installed and accessible as `tl` at compile time. use tealr::{ compile_inline_teal, - mlu::mlua::{Lua, Result}, + mlu::mlua::Lua, }; //This example using `compile_inline_teal` which takes in some teal code and compiles it. -fn main() -> Result<()> { +fn main() { let lua = Lua::new(); let code = compile_inline_teal!( @@ -16,7 +16,7 @@ fn main() -> Result<()> { local function add(param1 :number, param2:number):number return param1 + param2 end -local concat = require('examples/rlua/basic_type').concat +local concat = require('examples/basic_type').concat print(concat('a','b')) return add(1,2) " @@ -25,8 +25,6 @@ return add(1,2) let result: String = lua .load(code) .set_name("compile inline teal example") - .eval()?; + .eval().unwrap(); println!("output:{}", result); - - Ok(()) } diff --git a/examples/mlua/derive.rs b/examples/derive.rs similarity index 84% rename from examples/mlua/derive.rs rename to examples/derive.rs index 0c150eb..1949692 100644 --- a/examples/mlua/derive.rs +++ b/examples/derive.rs @@ -17,23 +17,23 @@ use tealr::{ //The clone is only needed because one of the example functions has it as a parameter #[derive(Clone, UserData, ToTypename)] struct Example {} -impl<'lua> FromLua<'lua> for Example { - fn from_lua(value: mlua::prelude::LuaValue<'lua>, _: &'lua Lua) -> Result { +impl FromLua for Example { + fn from_lua(value: mlua::prelude::LuaValue, _: &Lua) -> Result { value .as_userdata() .map(|x| x.take()) .unwrap_or(Err(mlua::Error::FromLuaConversionError { from: value.type_name(), - to: "Example", + to: "Example".to_string(), message: None, })) } } -//now, implement TealData. This tells rlua what methods are available and tealr what the types are +//now, implement TealData. This tells mlua what methods are available and tealr what the types are impl TealData for Example { //implement your methods/functions - fn add_methods<'lua, T: TealDataMethods<'lua, Self>>(methods: &mut T) { + fn add_methods>(methods: &mut T) { methods.add_method("example_method", |_, _, x: i8| Ok(x)); methods.add_method_mut("example_method_mut", |_, _, x: (i8, String)| Ok(x.1)); methods.add_function("example_function", |_, x: Vec| Ok((x, 8))); @@ -43,7 +43,7 @@ impl TealData for Example { } } -fn main() -> Result<()> { +fn main() { //we collect the documentation of our API in a json file so `tealr_doc_gen` can generate //the online documentation let file_contents = TypeWalker::new() @@ -60,13 +60,12 @@ fn main() -> Result<()> { //how you pass this type to lua hasn't changed: let lua = Lua::new(); let globals = lua.globals(); - globals.set("test", Example {})?; + globals.set("test", Example {}).unwrap(); let code = " print(test:example_method(1)) print(test:example_method_mut(2,\"test\")) print(test.example_function({})) print(test.example_function_mut(true)) "; - lua.load(code).set_name("test?").eval()?; - Ok(()) + lua.load(code).set_name("test?").eval::<()>().unwrap(); } diff --git a/examples/mlua/embed_teal.rs b/examples/embed_teal.rs similarity index 87% rename from examples/mlua/embed_teal.rs rename to examples/embed_teal.rs index dcef9d8..935da6b 100644 --- a/examples/mlua/embed_teal.rs +++ b/examples/embed_teal.rs @@ -2,11 +2,10 @@ use tealr::embed_compiler; -fn main() -> mlua::Result<()> { +fn main() { let compiler = embed_compiler!("v0.9.0"); let lua = mlua::Lua::new(); let code = compiler("examples/mlua/basic_teal_file"); - let res: u8 = lua.load(&code).set_name("embedded_compiler").eval()?; + let res: u8 = lua.load(&code).set_name("embedded_compiler").eval().unwrap(); println!("got:{}", res); - Ok(()) } diff --git a/examples/mlua/manual.rs b/examples/manual.rs similarity index 83% rename from examples/mlua/manual.rs rename to examples/manual.rs index 4fc1b64..7cbe619 100644 --- a/examples/mlua/manual.rs +++ b/examples/manual.rs @@ -13,23 +13,23 @@ use tealr::{ //First, create the struct you want to export to lua. #[derive(Clone, Copy)] struct Example(u32); -impl<'lua> FromLua<'lua> for Example { - fn from_lua(value: mlua::prelude::LuaValue<'lua>, _: &'lua Lua) -> Result { +impl FromLua for Example { + fn from_lua(value: mlua::prelude::LuaValue, _: &Lua) -> Result { value .as_userdata() .map(|x| x.take()) .unwrap_or(Err(mlua::Error::FromLuaConversionError { from: value.type_name(), - to: "Example", + to: "Example".to_string(), message: None, })) } } -//now, implement TealData. This tells rlua what methods are available and tealr what the types are +//now, implement TealData. This tells mlua what methods are available and tealr what the types are impl TealData for Example { //implement your methods/functions - fn add_methods<'lua, T: TealDataMethods<'lua, Self>>(methods: &mut T) { + fn add_methods>(methods: &mut T) { //methods.add_method("example_method", |_, _, x: i8| Ok(x)); methods.add_method( "example_method", @@ -41,7 +41,7 @@ impl TealData for Example { Ok(x) }) } - fn add_fields<'lua, F: tealr::mlu::TealDataFields<'lua, Self>>(fields: &mut F) { + fn add_fields>(fields: &mut F) { fields.add_field_method_get("example_field", |_, this| Ok(this.0)); fields.add_field_method_set("example_field", |_, this, value| { this.0 = value; @@ -58,14 +58,14 @@ impl ToTypename for Example { } impl UserData for Example { - fn add_methods<'lua, T: UserDataMethods<'lua, Self>>(methods: &mut T) { - let mut wrapper = UserDataWrapper::from_user_data_methods(methods); - ::add_methods(&mut wrapper) - } - fn add_fields<'lua, F: mlua::UserDataFields<'lua, Self>>(fields: &mut F) { + fn add_fields>(fields: &mut F) { let mut wrapper = UserDataWrapper::from_user_data_fields(fields); ::add_fields(&mut wrapper) } + fn add_methods>(methods: &mut T) { + let mut wrapper = UserDataWrapper::from_user_data_methods(methods); + ::add_methods(&mut wrapper) + } } impl TypeBody for Example { @@ -77,7 +77,7 @@ impl TypeBody for Example { gen.into() } } -fn main() -> Result<()> { +fn main() { let file_contents = TypeWalker::new() //tells it that you want to include the Example type //chain extra calls to include more types @@ -92,7 +92,7 @@ fn main() -> Result<()> { let lua = Lua::new(); let globals = lua.globals(); - globals.set("test", Example(1))?; + globals.set("test", Example(1)).unwrap(); let code = " print(test:example_method(function()return 1 end)) print(test:example_method_mut(2,\"test\")) @@ -102,6 +102,5 @@ print(\"Example field\", test.example_field) test.example_field = 2 print(\"After modifying\",test.example_field) "; - lua.load(code).set_name("test?").eval()?; - Ok(()) + lua.load(code).set_name("test?").eval::<()>().unwrap(); } diff --git a/examples/mlua/manual_documentation.rs b/examples/manual_documentation.rs similarity index 85% rename from examples/mlua/manual_documentation.rs rename to examples/manual_documentation.rs index 7574004..a64c7f0 100644 --- a/examples/mlua/manual_documentation.rs +++ b/examples/manual_documentation.rs @@ -13,23 +13,23 @@ use tealr::{ //First, create the struct you want to export to lua. #[derive(Clone, Copy)] struct Example(u32); -impl<'lua> FromLua<'lua> for Example { - fn from_lua(value: mlua::prelude::LuaValue<'lua>, _: &'lua Lua) -> Result { +impl FromLua for Example { + fn from_lua(value: mlua::prelude::LuaValue, _: &Lua) -> Result { value .as_userdata() .map(|x| x.take()) .unwrap_or(Err(mlua::Error::FromLuaConversionError { from: value.type_name(), - to: "Example", + to: "Example".to_string(), message: None, })) } } -//now, implement TealData. This tells rlua what methods are available and tealr what the types are +//now, implement TealData. This tells mlua what methods are available and tealr what the types are impl TealData for Example { //implement your methods/functions - fn add_methods<'lua, T: TealDataMethods<'lua, Self>>(methods: &mut T) { + fn add_methods>(methods: &mut T) { methods.document_type("This is just an example type"); methods.document_type("This part of the documentation is for the type itself"); methods.document_type( @@ -51,7 +51,7 @@ impl TealData for Example { }); methods.generate_help(); } - fn add_fields<'lua, F: tealr::mlu::TealDataFields<'lua, Self>>(fields: &mut F) { + fn add_fields>(fields: &mut F) { fields.document("This is an example field"); fields.add_field_method_get("example", |_, this| Ok(this.0)); fields.document("Documentation for fields with the same name get merged"); @@ -70,14 +70,14 @@ impl ToTypename for Example { } impl UserData for Example { - fn add_methods<'lua, T: UserDataMethods<'lua, Self>>(methods: &mut T) { - let mut wrapper = UserDataWrapper::from_user_data_methods(methods); - ::add_methods(&mut wrapper); - } - fn add_fields<'lua, F: mlua::UserDataFields<'lua, Self>>(fields: &mut F) { + fn add_fields>(fields: &mut F) { let mut wrapper = UserDataWrapper::from_user_data_fields(fields); ::add_fields(&mut wrapper); } + fn add_methods>(methods: &mut T) { + let mut wrapper = UserDataWrapper::from_user_data_methods(methods); + ::add_methods(&mut wrapper); + } } impl TypeBody for Example { @@ -89,7 +89,7 @@ impl TypeBody for Example { gen.into() } } -fn main() -> Result<()> { +fn main() { let file_contents = TypeWalker::new() //tells it that you want to include the Example type //chain extra calls to include more types @@ -105,7 +105,7 @@ fn main() -> Result<()> { let lua = Lua::new(); let globals = lua.globals(); - globals.set("test", Example(1))?; + globals.set("test", Example(1)).unwrap(); let code = " print(test.help()) print(\"----\") @@ -116,6 +116,5 @@ print(test.example_function({})) print(test.example_function_mut(true)) "; - lua.load(code).set_name("test?").eval()?; - Ok(()) + lua.load(code).set_name("test?").eval::<()>().unwrap(); } diff --git a/examples/mlua/named_parameters.rs b/examples/named_parameters.rs similarity index 86% rename from examples/mlua/named_parameters.rs rename to examples/named_parameters.rs index d4a36f1..b9642f7 100644 --- a/examples/mlua/named_parameters.rs +++ b/examples/named_parameters.rs @@ -1,6 +1,6 @@ use tealr::{ mlu::{ - mlua::{Lua, Result}, + mlua::Lua, TealData, TealDataMethods, UserData, }, ToTypename, TypeWalker, @@ -10,7 +10,7 @@ use tealr::{ struct Example {} impl TealData for Example { - fn add_methods<'lua, T: TealDataMethods<'lua, Self>>(methods: &mut T) { + fn add_methods>(methods: &mut T) { //this creates a new struct that will contain our parameters //it has a field with the name `field_1` of type `String` //and a field with the name `field_2` of type `i64` @@ -26,7 +26,7 @@ impl TealData for Example { } } -fn main() -> Result<()> { +fn main() { let file_contents = TypeWalker::new() //tells it that you want to include the Example type //chain extra calls to include more types @@ -41,8 +41,7 @@ fn main() -> Result<()> { //lua is still using position parameters as normal. let lua = Lua::new(); let globals = lua.globals(); - globals.set("test", Example {})?; + globals.set("test", Example {}).unwrap(); let code = "test:example_method(\"field_1 is a string\", 3)"; - lua.load(code).set_name("test?").eval()?; - Ok(()) + lua.load(code).set_name("test?").eval::<()>().unwrap(); } diff --git a/examples/rlua/basic_teal_file.tl b/examples/rlua/basic_teal_file.tl deleted file mode 100644 index e3a1b54..0000000 --- a/examples/rlua/basic_teal_file.tl +++ /dev/null @@ -1,7 +0,0 @@ -function add(a:number,b:number):number - return a + b -end - -print(add(1,2)) - -return add(3,4) \ No newline at end of file diff --git a/examples/rlua/basic_type.d.tl b/examples/rlua/basic_type.d.tl deleted file mode 100644 index 77e1005..0000000 --- a/examples/rlua/basic_type.d.tl +++ /dev/null @@ -1,4 +0,0 @@ -local record basicType - concat : function (string,string):string -end -return basicType \ No newline at end of file diff --git a/examples/rlua/basic_type.lua b/examples/rlua/basic_type.lua deleted file mode 100644 index 468e3f2..0000000 --- a/examples/rlua/basic_type.lua +++ /dev/null @@ -1,5 +0,0 @@ -return { - concat= function (a, b) - return a .. b - end -} \ No newline at end of file diff --git a/examples/rlua/compile_inline_teal.rs b/examples/rlua/compile_inline_teal.rs deleted file mode 100644 index 7167078..0000000 --- a/examples/rlua/compile_inline_teal.rs +++ /dev/null @@ -1,34 +0,0 @@ -//This example shows how to build inline teal code at compile time -//This is useful if you want to write a bit of teal/lua code directly in your application that gets passed to RLua. -//NOTE: At this point it requires you to have teal installed and accessible as `tl` at compile time. - -use tealr::{ - compile_inline_teal, - rlu::rlua::{Lua, Result}, -}; - -//This example using `compile_inline_teal` which takes in some teal code and compiles it. -fn main() -> Result<()> { - let lua = Lua::new(); - lua.context(|lua_ctx| { - let code = compile_inline_teal!( - " -local function add(param1 :number, param2:number):number - return param1 + param2 -end -local concat = require('examples/rlua/basic_type').concat -print(concat('a','b')) -return add(1,2) - " - ); - println!("generated code : {}", code); - let result: String = lua_ctx - .load(code) - .set_name("compile inline teal example")? - .eval()?; - println!("output:{}", result); - Ok(()) - })?; - - Ok(()) -} diff --git a/examples/rlua/derive.rs b/examples/rlua/derive.rs deleted file mode 100644 index 2724582..0000000 --- a/examples/rlua/derive.rs +++ /dev/null @@ -1,61 +0,0 @@ -use rlua::{Lua, Result}; -use tealr::{ - rlu::{TealData, TealDataMethods, TealDerive}, - TypeWalker, -}; -//this example shows how the new traits allow you to generate the .d.tl file -//and shows how to use them to share data with lua -//It also shows how to generate the file -//NOTE: All it does it generate the contents of the file. Storing it is left to the user. - -//First, create the struct you want to export to lua. -//instead of both deriving UserData and TypeName you can also -//derive TealDerive, which does both. However you will still need to import -//UserData and TypeName -//The clone is only needed because one of the example functions has it as a parameter -#[derive(Clone, TealDerive)] -struct Example {} - -//now, implement TealData. This tells rlua what methods are available and tealr what the types are -impl TealData for Example { - //implement your methods/functions - fn add_methods<'lua, T: TealDataMethods<'lua, Self>>(methods: &mut T) { - methods.add_method("example_method", |_, _, x: i8| Ok(x)); - methods.add_method_mut("example_method_mut", |_, _, x: (i8, String)| Ok(x.1)); - methods.add_function("example_function", |_, x: Vec| Ok((x, 8))); - methods.add_function_mut("example_function_mut", |_, x: (bool, Option)| { - Ok(x) - }) - } -} - -fn main() -> Result<()> { - //we collect the documentation of our API in a json file so `tealr_doc_gen` can generate - //the online documentation - let file_contents = TypeWalker::new() - //tells it that we want to include the `Example` type - //add more calls to process_type to generate more types in the same file - .process_type::() - //generate the file - .to_json() - .expect("serde_json failed to serialize our data"); - - //normally you would now save the file somewhere. - println!("{}\n ", file_contents); - - //how you pass this type to lua hasn't changed: - let lua = Lua::new(); - lua.context(|lua_ctx| { - let globals = lua_ctx.globals(); - globals.set("test", Example {})?; - let code = " -print(test:example_method(1)) -print(test:example_method_mut(2,\"test\")) -print(test.example_function({})) -print(test.example_function_mut(true)) - "; - lua_ctx.load(code).set_name("test?")?.eval()?; - Ok(()) - })?; - Ok(()) -} diff --git a/examples/rlua/embed_teal.rs b/examples/rlua/embed_teal.rs deleted file mode 100644 index 23a795a..0000000 --- a/examples/rlua/embed_teal.rs +++ /dev/null @@ -1,14 +0,0 @@ -//tealr is able to embed the compiler, allowing you to require external teal files as if they where normal lua files - -use tealr::embed_compiler; - -fn main() -> rlua::Result<()> { - let compiler = embed_compiler!("v0.13.1"); - let res = rlua::Lua::new().context(|ctx| { - let code = compiler("examples/basic_teal_file"); - let res: u8 = ctx.load(&code).set_name("embedded_compiler")?.eval()?; - Ok(res) - })?; - println!("got:{}", res); - Ok(()) -} diff --git a/examples/rlua/manual.rs b/examples/rlua/manual.rs deleted file mode 100644 index 52701f3..0000000 --- a/examples/rlua/manual.rs +++ /dev/null @@ -1,82 +0,0 @@ -use tealr::{ - rlu::{ - rlua::{Lua, Result, UserData, UserDataMethods}, - TealData, TealDataMethods, UserDataWrapper, - }, - RecordGenerator, ToTypename, TypeBody, TypeGenerator, TypeWalker, -}; -//This example shows how to manually implement UserData using TealData -//As you can see the amount of code is small and easy copy/paste able. -//Because of this it may make sense to do the implementation yourself -//instead of paying the compile time cost of the macro - -//First, create the struct you want to export to lua. -#[derive(Clone, Copy)] -struct Example {} - -//now, implement TealData. This tells rlua what methods are available and tealr what the types are -impl TealData for Example { - //implement your methods/functions - fn add_methods<'lua, T: TealDataMethods<'lua, Self>>(methods: &mut T) { - methods.add_method("example_method", |_, _, x: i8| Ok(x)); - methods.add_method( - "example_method2", - |_, _, x: tealr::rlu::TypedFunction| Ok(x), - ); - methods.add_method_mut("example_method_mut", |_, _, x: (i8, String)| Ok(x.1)); - methods.add_function("example_function", |_, x: Vec| Ok((x, 8))); - methods.add_function_mut("example_function_mut", |_, x: (bool, Option)| { - Ok(x) - }) - } -} - -impl ToTypename for Example { - //how the type should be called in lua. - fn to_typename() -> tealr::Type { - tealr::Type::new_single("Example", tealr::KindOfType::External) - } -} -impl UserData for Example { - fn add_methods<'lua, T: UserDataMethods<'lua, Self>>(methods: &mut T) { - let mut wrapper = UserDataWrapper::from_user_data_methods(methods); - ::add_methods(&mut wrapper) - } -} - -impl TypeBody for Example { - fn get_type_body() -> TypeGenerator { - let mut gen = RecordGenerator::new::(false); - gen.is_user_data = true; - ::add_methods(&mut gen); - gen.into() - } -} -fn main() -> Result<()> { - let file_contents = TypeWalker::new() - //tells it that you want to include the Example type - //chain extra calls to include more types - .process_type::() - //generate the file - .to_json() - .expect("serde_json failed to serialize our data"); - //normally you would now save the file somewhere. - //however for this example we just print it. - println!("{}\n ", file_contents); - - //how you pass this type to lua hasn't changed: - let lua = Lua::new(); - lua.context(|lua_ctx| { - let globals = lua_ctx.globals(); - globals.set("test", Example {})?; - let code = " -print(test:example_method(1)) -print(test:example_method_mut(2,\"test\")) -print(test.example_function({})) -print(test.example_function_mut(true)) - "; - lua_ctx.load(code).set_name("test?")?.eval()?; - Ok(()) - })?; - Ok(()) -} diff --git a/examples/rlua/manual_documentation.rs b/examples/rlua/manual_documentation.rs deleted file mode 100644 index 2ad5cfd..0000000 --- a/examples/rlua/manual_documentation.rs +++ /dev/null @@ -1,85 +0,0 @@ -use tealr::{ - rlu::{ - rlua::{Lua, Result, UserData, UserDataMethods}, - TealData, TealDataMethods, UserDataWrapper, - }, - ToTypename, TypeBody, TypeWalker, -}; -//This example shows how to manually implement UserData using TealData -//As you can see the amount of code is small and easy copy/paste able. -//Because of this it may make sense to do the implementation yourself -//instead of paying the compile time cost of the macro - -//First, create the struct you want to export to lua. -#[derive(Clone, Copy)] -struct Example {} - -//now, implement TealData. This tells rlua what methods are available and tealr what the types are -impl TealData for Example { - //implement your methods/functions - fn add_methods<'lua, T: TealDataMethods<'lua, Self>>(methods: &mut T) { - methods.document("This is an example method."); - methods.document("It just shows you how documentation gets added"); - methods.add_method("example_method", |_, _, x: i8| Ok(x)); - methods.add_method_mut("example_method_mut", |_, _, x: (i8, String)| Ok(x.1)); - methods.add_function("example_function", |_, x: Vec| Ok((x, 8))); - methods.add_function_mut("example_function_mut", |_, x: (bool, Option)| { - Ok(x) - }); - methods.generate_help(); - } -} - -impl ToTypename for Example { - //how the type should be called in lua. - fn to_typename() -> tealr::Type { - tealr::Type::new_single("Example", tealr::KindOfType::External) - } -} - -impl UserData for Example { - fn add_methods<'lua, T: UserDataMethods<'lua, Self>>(methods: &mut T) { - let mut wrapper = UserDataWrapper::from_user_data_methods(methods); - ::add_methods(&mut wrapper) - } -} - -impl TypeBody for Example { - fn get_type_body() -> tealr::TypeGenerator { - let mut gen = tealr::RecordGenerator::new::(false); - gen.is_user_data = true; - ::add_methods(&mut gen); - gen.into() - } -} -fn main() -> Result<()> { - let file_contents = TypeWalker::new() - //tells it that you want to include the Example type - //chain extra calls to include more types - .process_type::() - //generate the file - .to_json() - .expect("serde_json failed to serialize our data"); - //normally you would now save the file somewhere. - //however for this example we just print it. - println!("{}\n ", file_contents); - - //how you pass this type to lua hasn't changed: - let lua = Lua::new(); - lua.context(|lua_ctx| { - let globals = lua_ctx.globals(); - globals.set("test", Example {})?; - let code = " -print(test.help()) -print(\"----\") -print(test.help(\"example_method\")) -print(test:example_method(1)) -print(test:example_method_mut(2,\"test\")) -print(test.example_function({})) -print(test.example_function_mut(true)) - "; - lua_ctx.load(code).set_name("test?")?.eval()?; - Ok(()) - })?; - Ok(()) -} diff --git a/examples/rlua/named_parameters.rs b/examples/rlua/named_parameters.rs deleted file mode 100644 index dba9fcc..0000000 --- a/examples/rlua/named_parameters.rs +++ /dev/null @@ -1,47 +0,0 @@ -use tealr::{ - rlu::{rlua::Result, TealData, TealDataMethods, UserData}, - ToTypename, TypeWalker, -}; -//this example shows how to use the create_named_parameters! macro to create methods which has names for their parameters in the documentation -#[derive(Clone, UserData, ToTypename)] -struct Example {} - -impl TealData for Example { - fn add_methods<'lua, T: TealDataMethods<'lua, Self>>(methods: &mut T) { - //this creates a new struct that will contain our parameters - //it has a field with the name `field_1` of type `String` - //and a field with the name `field_2` of type `i64` - tealr::rlu::create_named_parameters!( - TestName with - field_1 : String, - field_2 : i64, - ); - methods.add_method("example_method", |_, _, a: TestName| { - println!("field_1 = {}; field_2 = {}", a.field_1, a.field_2); - Ok(()) - }); - } -} - -fn main() -> Result<()> { - let file_contents = TypeWalker::new() - //tells it that you want to include the Example type - //chain extra calls to include more types - .process_type::() - //generate the file - .to_json() - .expect("serde_json failed to serialize our data"); - - //normally you would now save the file somewhere. - println!("{}\n ", file_contents); - - //lua is still using position parameters as normal. - tealr::rlu::rlua::Lua::new().context(|ctx| { - let globals = ctx.globals(); - globals.set("test", Example {})?; - let code = "test:example_method(\"field_1 is a string\", 3)"; - ctx.load(code).set_name("test?")?.eval()?; - Ok(()) - })?; - Ok(()) -} diff --git a/examples/mlua/userdata_proxy.rs b/examples/userdata_proxy.rs similarity index 84% rename from examples/mlua/userdata_proxy.rs rename to examples/userdata_proxy.rs index d0513f4..db625d6 100644 --- a/examples/mlua/userdata_proxy.rs +++ b/examples/userdata_proxy.rs @@ -18,23 +18,23 @@ struct Example { float: f32, } -impl<'lua> FromLua<'lua> for Example { - fn from_lua(value: mlua::prelude::LuaValue<'lua>, _: &'lua Lua) -> Result { +impl FromLua for Example { + fn from_lua(value: mlua::prelude::LuaValue, _: &Lua) -> Result { value .as_userdata() .map(|x| x.take()) .unwrap_or(Err(mlua::Error::FromLuaConversionError { from: value.type_name(), - to: "Example", + to: "Example".to_string(), message: None, })) } } -//now, implement TealData. This tells rlua what methods are available and tealr what the types are +//now, implement TealData. This tells mlua what methods are available and tealr what the types are impl TealData for Example { //implement your methods/functions - fn add_methods<'lua, T: TealDataMethods<'lua, Self>>(methods: &mut T) { + fn add_methods>(methods: &mut T) { methods.add_method("example_method", |_, _, x: i8| Ok(x)); methods.add_method_mut("example_method_mut", |_, _, x: (i8, String)| Ok(x.1)); methods.add_function("example_function", |_, x: Vec| Ok((x, 8))); @@ -43,7 +43,7 @@ impl TealData for Example { }) } - fn add_fields<'lua, F: tealr::mlu::TealDataFields<'lua, Self>>(fields: &mut F) { + fn add_fields>(fields: &mut F) { fields.add_field_method_get("example_field", |_, s: &Example| Ok(s.float)); fields.add_field_method_set("example_field_set", |_, s: &mut Example, v: f32| { s.float = v; @@ -58,7 +58,7 @@ impl TealData for Example { #[derive(Default)] struct Export; impl tealr::mlu::ExportInstances for Export { - fn add_instances<'lua, T: tealr::mlu::InstanceCollector<'lua>>( + fn add_instances( self, instance_collector: &mut T, ) -> mlua::Result<()> { @@ -70,14 +70,15 @@ impl tealr::mlu::ExportInstances for Export { } } -fn main() -> Result<()> { +fn main() { let file_contents = TypeWalker::new() //tells it that we want to generate Example .process_type::() //generate the documentation for our proxy, allowing us to .process_type::>() // enable documenting the globals - .document_global_instance::()? + .document_global_instance::() + .unwrap() //generate the file .to_json() .expect("serde_json failed to serialize our data"); @@ -89,7 +90,7 @@ fn main() -> Result<()> { let lua = Lua::new(); tealr::mlu::set_global_env(Export {}, &lua).unwrap(); let globals = lua.globals(); - globals.set("test", Example { float: 42.0 })?; + globals.set("test", Example { float: 42.0 }).unwrap(); let code = " print(\" Calling from `test` :\") print(test:example_method(1)) @@ -102,6 +103,5 @@ print(\" Calling from global `Example` :\") print(Example.example_static_field) print(Example.example_function({})) "; - lua.load(code).set_name("test?").eval()?; - Ok(()) + lua.load(code).set_name("test?").eval::<()>().unwrap(); } diff --git a/src/export_instance.rs b/src/export_instance.rs index 036b32c..8e1ddfa 100644 --- a/src/export_instance.rs +++ b/src/export_instance.rs @@ -6,13 +6,13 @@ pub(crate) struct InstanceWalker { doc: String, pub(crate) instances: Vec, } -#[cfg(feature = "mlua")] -impl<'lua> crate::mlu::InstanceCollector<'lua> for InstanceWalker { + +impl crate::mlu::InstanceCollector for InstanceWalker { fn add_instance(&mut self, global_name: P, _: F) -> Result<&mut Self, mlua::Error> where P: Into>, T: ToTypename, - F: FnOnce(&'lua mlua::Lua) -> Result, + F: FnOnce(&mlua::Lua) -> Result, { self.add_instance::(global_name.into()); Ok(self) @@ -23,25 +23,6 @@ impl<'lua> crate::mlu::InstanceCollector<'lua> for InstanceWalker { } } -#[cfg(feature = "rlua")] -impl<'lua> crate::rlu::InstanceCollector<'lua> for InstanceWalker { - fn add_instance< - P: Into>, - T: ToTypename, - F: FnOnce(rlua::Context<'lua>) -> rlua::Result, - >( - &mut self, - global_name: P, - _: F, - ) -> Result<&mut Self, rlua::Error> { - self.add_instance::(global_name.into()); - Ok(self) - } - fn document_instance(&mut self, doc: &'static str) -> &mut Self { - self.document_instance(doc); - self - } -} impl InstanceWalker { pub(crate) fn new() -> Self { diff --git a/src/exported_function.rs b/src/exported_function.rs index fc4fdec..2a6c17c 100644 --- a/src/exported_function.rs +++ b/src/exported_function.rs @@ -11,15 +11,11 @@ type X = Vec; ///Contains the data needed to write down the type of a function #[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] #[cfg_attr( - all(feature = "mlua", feature = "derive", not(feature = "rlua")), + feature = "derive", derive(crate::mlu::FromToLua, crate::ToTypename) )] #[cfg_attr( - all(feature = "rlua", feature = "derive", not(feature = "mlua")), - derive(crate::rlu::FromToLua, crate::ToTypename) -)] -#[cfg_attr( - all(any(feature = "rlua", feature = "mlua"), feature = "derive",not(all(feature = "rlua", feature = "mlua"))), + feature = "derive", tealr(tealr_name = crate) )] pub struct ExportedFunction { @@ -28,7 +24,7 @@ pub struct ExportedFunction { ///The full layout of the function based on teal's syntax #[deprecated] #[cfg_attr( - all(any(feature = "rlua", feature = "mlua"), feature = "derive",not(all(feature = "rlua", feature = "mlua"))), + feature = "derive", tealr(remote = X) )] pub signature: Cow<'static, [crate::NamePart]>, @@ -45,7 +41,6 @@ impl ExportedFunction { ///# use tealr::ExportedFunction; ///ExportedFunction::new::<(String,String),String,_>("concat",false,None); ///``` - #[cfg(any(feature = "rlua", feature = "mlua"))] pub fn new>( name: S, is_meta_method: bool, diff --git a/src/lib.rs b/src/lib.rs index 7766980..eab3e2c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,12 +1,8 @@ #![warn(missing_docs)] #![doc = include_str!("../README.md")] -//mod expanded; -///traits and types specific to rlua -#[cfg(feature = "rlua")] -pub mod rlu; + ///traits and types specific to mlua -#[cfg(feature = "mlua")] pub mod mlu; mod export_instance; @@ -50,21 +46,17 @@ pub fn get_tealr_version() -> &'static str { #[derive(PartialEq, Eq, Hash, Clone, Debug, Serialize, Deserialize)] #[cfg_attr( - all(feature = "mlua", feature = "derive", not(feature = "rlua")), + feature = "derive", derive(crate::mlu::FromToLua, crate::ToTypename) )] #[cfg_attr( - all(feature = "rlua", feature = "derive", not(feature = "mlua")), - derive(crate::rlu::FromToLua, crate::ToTypename) -)] -#[cfg_attr( - all(any(feature = "rlua", feature = "mlua"), feature = "derive", not(all(feature = "rlua", feature = "mlua"))), + feature = "derive", tealr(tealr_name = crate) )] ///The name of a type pub struct Name( #[cfg_attr( - all(any(feature = "rlua", feature = "mlua"), feature = "derive",not(all(feature = "rlua", feature = "mlua"))), + feature = "derive", tealr(remote = String))] pub Cow<'static, str>, ); @@ -81,15 +73,11 @@ impl> From for Name { } #[derive(Clone, Debug, Serialize, Deserialize)] #[cfg_attr( - all(feature = "mlua", feature = "derive", not(feature = "rlua")), + feature = "derive", derive(crate::mlu::FromToLua, crate::ToTypename) )] #[cfg_attr( - all(feature = "rlua", feature = "derive", not(feature = "mlua")), - derive(crate::rlu::FromToLua, crate::ToTypename) -)] -#[cfg_attr( - all(any(feature = "rlua", feature = "mlua"), feature = "derive", not(all(feature = "rlua", feature = "mlua"))), + feature = "derive", tealr(tealr_name = crate) )] ///A singular type @@ -101,15 +89,11 @@ pub struct SingleType { } #[derive(Clone, Debug, Serialize, Deserialize)] #[cfg_attr( - all(feature = "mlua", feature = "derive", not(feature = "rlua")), + feature = "derive", derive(crate::mlu::FromToLua, crate::ToTypename) )] #[cfg_attr( - all(feature = "rlua", feature = "derive", not(feature = "mlua")), - derive(crate::rlu::FromToLua, crate::ToTypename) -)] -#[cfg_attr( - all(any(feature = "rlua", feature = "mlua"), feature = "derive", not(all(feature = "rlua", feature = "mlua"))), + feature = "derive", tealr(tealr_name = crate) )] ///A parameter for a function @@ -121,15 +105,11 @@ pub struct FunctionParam { } #[derive(Debug, Clone, Serialize, Deserialize)] #[cfg_attr( - all(feature = "mlua", feature = "derive", not(feature = "rlua")), + feature = "derive", derive(crate::mlu::FromToLua, crate::ToTypename) )] #[cfg_attr( - all(feature = "rlua", feature = "derive", not(feature = "mlua")), - derive(crate::rlu::FromToLua, crate::ToTypename) -)] -#[cfg_attr( - all(any(feature = "rlua", feature = "mlua"), feature = "derive", not(all(feature = "rlua", feature = "mlua"))), + feature = "derive", tealr(tealr_name = crate) )] ///The representation of a function type @@ -141,26 +121,22 @@ pub struct FunctionRepresentation { } #[derive(Debug, Clone, Serialize, Deserialize)] #[cfg_attr( - all(feature = "mlua", feature = "derive", not(feature = "rlua")), + feature = "derive", derive(crate::mlu::FromToLua, crate::ToTypename) )] #[cfg_attr( - all(feature = "rlua", feature = "derive", not(feature = "mlua")), - derive(crate::rlu::FromToLua, crate::ToTypename) -)] -#[cfg_attr( - all(any(feature = "rlua", feature = "mlua"), feature = "derive", not(all(feature = "rlua", feature = "mlua"))), + feature = "derive", tealr(tealr_name = crate) )] ///The representation of a Map type pub struct MapRepresentation { #[cfg_attr( - all(any(feature = "rlua", feature = "mlua"), feature = "derive",not(all(feature = "rlua", feature = "mlua"))), + feature = "derive", tealr(remote = Type))] ///The type of the key pub key: Box, #[cfg_attr( - all(any(feature = "rlua", feature = "mlua"), feature = "derive",not(all(feature = "rlua", feature = "mlua"))), + feature = "derive", tealr(remote = Type))] ///The type of the value pub value: Box, @@ -170,15 +146,11 @@ type NewTypeArray = Vec; #[derive(Debug, Clone, Serialize, Deserialize)] #[cfg_attr( - all(feature = "mlua", feature = "derive", not(feature = "rlua")), + feature = "derive", derive(crate::mlu::FromToLua, crate::ToTypename) )] #[cfg_attr( - all(feature = "rlua", feature = "derive", not(feature = "mlua")), - derive(crate::rlu::FromToLua, crate::ToTypename) -)] -#[cfg_attr( - all(any(feature = "rlua", feature = "mlua"), feature = "derive", not(all(feature = "rlua", feature = "mlua"))), + feature = "derive", tealr(tealr_name = crate) )] ///A type @@ -192,14 +164,14 @@ pub enum Type { ///The type is a union (A | B) Or( #[cfg_attr( - all(any(feature = "rlua", feature = "mlua"), feature = "derive",not(all(feature = "rlua", feature = "mlua"))), + feature = "derive", tealr(remote = NewTypeArray))] Vec, ), ///The type is an array Array( #[cfg_attr( - all(any(feature = "rlua", feature = "mlua"), feature = "derive",not(all(feature = "rlua", feature = "mlua"))), + feature = "derive", tealr(remote = Type))] Box, ), @@ -208,7 +180,7 @@ pub enum Type { ///As it can _easily_ break things Tuple( #[cfg_attr( - all(any(feature = "rlua", feature = "mlua"), feature = "derive",not(all(feature = "rlua", feature = "mlua"))), + feature = "derive", tealr(remote = NewTypeArray))] Vec, ), diff --git a/src/mlu/generics.rs b/src/mlu/generics.rs index b83c2d6..da22cbc 100644 --- a/src/mlu/generics.rs +++ b/src/mlu/generics.rs @@ -12,33 +12,33 @@ macro_rules! create_generic_mlua { ($visibility:vis $type_name:ident) => { #[derive(Clone,Debug)] #[allow(missing_docs)] - $visibility enum $type_name<'lua> { + $visibility enum $type_name { Nil, Boolean(bool), LightUserData($crate::mlu::mlua::LightUserData), Integer($crate::mlu::mlua::Integer), Number($crate::mlu::mlua::Number), - String($crate::mlu::mlua::String<'lua>), - Table($crate::mlu::mlua::Table<'lua>), - Function($crate::mlu::mlua::Function<'lua>), - Thread($crate::mlu::mlua::Thread<'lua>), - UserData($crate::mlu::mlua::AnyUserData<'lua>), - Error($crate::mlu::mlua::Error), + String($crate::mlu::mlua::String), + Table($crate::mlu::mlua::Table), + Function($crate::mlu::mlua::Function), + Thread($crate::mlu::mlua::Thread), + UserData($crate::mlu::mlua::AnyUserData), + Error(Box<$crate::mlu::mlua::Error>), #[cfg(feature = "mlua_luau")] Vector(f32,f32,f32) } - impl<'lua> $crate::mlu::mlua::FromLua<'lua> for $type_name<'lua> { - fn from_lua(value: $crate::mlu::mlua::Value<'lua>, _: &'lua $crate::mlu::mlua::Lua) -> ::std::result::Result { + impl $crate::mlu::mlua::FromLua for $type_name { + fn from_lua(value: $crate::mlu::mlua::Value, _: &$crate::mlu::mlua::Lua) -> ::std::result::Result { Ok(value.into()) } } - impl<'lua> $crate::mlu::mlua::IntoLua<'lua> for $type_name<'lua> { - fn into_lua(self, _: &'lua $crate::mlu::mlua::Lua) -> ::std::result::Result<$crate::mlu::mlua::Value<'lua>, $crate::mlu::mlua::Error> { + impl $crate::mlu::mlua::IntoLua for $type_name { + fn into_lua(self, _: &$crate::mlu::mlua::Lua) -> ::std::result::Result<$crate::mlu::mlua::Value, $crate::mlu::mlua::Error> { Ok(self.into()) } } - impl<'lua> From<$crate::mlu::mlua::Value<'lua>> for $type_name<'lua> { - fn from(value:$crate::mlu::mlua::Value<'lua>) -> $type_name { + impl From<$crate::mlu::mlua::Value> for $type_name { + fn from(value:$crate::mlu::mlua::Value) -> $type_name { use $crate::mlu::mlua::Value::*; match value { Nil => $type_name::Nil, @@ -53,12 +53,13 @@ macro_rules! create_generic_mlua { UserData(x) => $type_name::UserData(x), Error(x) => $type_name::Error(x), #[cfg(feature = "mlua_luau")] - Vector(vec) => $type_name::Vector(vec.x(),vec.y(),vec.z()) + Vector(vec) => $type_name::Vector(vec.x(),vec.y(),vec.z()), + _ => unimplemented!("Unsupported variant"), } } } - impl<'lua> From<$type_name<'lua>> for $crate::mlu::mlua::Value<'lua> { - fn from(value:$type_name<'lua>) -> $crate::mlu::mlua::Value<'lua> { + impl From<$type_name> for $crate::mlu::mlua::Value { + fn from(value:$type_name) -> $crate::mlu::mlua::Value { use $type_name::*; match value { Nil => $crate::mlu::mlua::Value::Nil, @@ -77,13 +78,13 @@ macro_rules! create_generic_mlua { } } } - impl<'lua> ::std::iter::FromIterator<$type_name<'lua>> for $crate::mlu::mlua::MultiValue<'lua> { - fn from_iter<__MacroIterGeneric: IntoIterator>>(iter: __MacroIterGeneric) -> Self { + impl ::std::iter::FromIterator<$type_name> for $crate::mlu::mlua::MultiValue { + fn from_iter<__MacroIterGeneric: IntoIterator>(iter: __MacroIterGeneric) -> Self { iter.into_iter().map($crate::mlu::mlua::Value::from).collect() } } - impl<'lua> ::core::cmp::PartialEq<$crate::mlu::mlua::Value<'lua>> for $type_name<'lua> { - fn eq(&self, other: &$crate::mlu::mlua::Value<'lua>) -> bool { + impl ::core::cmp::PartialEq<$crate::mlu::mlua::Value> for $type_name { + fn eq(&self, other: &$crate::mlu::mlua::Value) -> bool { match (self, other) { ($type_name::Nil, $crate::mlu::mlua::Value::Nil) => true, ($type_name::Boolean(a), $crate::mlu::mlua::Value::Boolean(b)) => a == b, @@ -103,7 +104,7 @@ macro_rules! create_generic_mlua { } } } - impl<'lua> ::core::cmp::PartialEq for $type_name<'lua> { + impl ::core::cmp::PartialEq for $type_name { fn eq(&self, other: &Self) -> bool { match (self, other) { ($type_name::Nil, $type_name::Nil) => true, @@ -124,7 +125,7 @@ macro_rules! create_generic_mlua { } } } - impl<'lua> $crate::ToTypename for $type_name<'lua> { + impl $crate::ToTypename for $type_name { fn to_typename() -> $crate::Type { $crate::Type::new_single(stringify!($type_name), $crate::KindOfType::Generic) } diff --git a/src/mlu/named_parameters.rs b/src/mlu/named_parameters.rs index 4e7d4e7..cae0f0b 100644 --- a/src/mlu/named_parameters.rs +++ b/src/mlu/named_parameters.rs @@ -47,10 +47,10 @@ macro_rules! mlua_create_named_parameters { x } } - impl<'lua> $crate::mlu::mlua::FromLuaMulti<'lua> for $type_name { + impl $crate::mlu::mlua::FromLuaMulti for $type_name { fn from_lua_multi( - mut values: $crate::mlu::mlua::MultiValue<'lua>, - lua: &'lua $crate::mlu::mlua::Lua, + mut values: $crate::mlu::mlua::MultiValue, + lua: &$crate::mlu::mlua::Lua, ) -> $crate::mlu::mlua::Result { Ok(Self { $($field_name: <_ as $crate::mlu::mlua::FromLua>::from_lua( diff --git a/src/mlu/picker_macro.rs b/src/mlu/picker_macro.rs index ba9ad61..6f3e058 100644 --- a/src/mlu/picker_macro.rs +++ b/src/mlu/picker_macro.rs @@ -3,14 +3,14 @@ use std::{ ffi::{CStr, CString}, num::TryFromIntError, }; - +use std::ops::Deref; use mlua::{Error, Function, Lua, Table, Value}; /// similar to [mlua::FromLua](mlua::FromLua). However, /// however going through this trait you promise that the conversion to a rust value prefers failing over converting/casting -pub trait FromLuaExact<'lua>: Sized { +pub trait FromLuaExact: Sized { ///Does the conversion, without any type conversion/casting - fn from_lua_exact(value: mlua::Value<'lua>, lua: &'lua mlua::Lua) -> mlua::Result; + fn from_lua_exact(value: Value, lua: &Lua) -> mlua::Result; } ///Creates a new type that is a union of the types you gave. @@ -42,22 +42,22 @@ macro_rules! create_union_mlua { $visibility enum $type_name { $($sub_types($sub_types) ,)* } - impl<'lua> $crate::mlu::mlua::IntoLua<'lua> for $type_name { - fn into_lua(self, lua: &'lua $crate::mlu::mlua::Lua) -> ::std::result::Result<$crate::mlu::mlua::Value<'lua>, $crate::mlu::mlua::Error> { + impl $crate::mlu::mlua::IntoLua for $type_name { + fn into_lua(self, lua: &$crate::mlu::mlua::Lua) -> ::std::result::Result<$crate::mlu::mlua::Value, $crate::mlu::mlua::Error> { match self { $($type_name::$sub_types(x) => x.into_lua(lua),)* } } } - impl<'lua> $crate::mlu::mlua::FromLua<'lua> for $type_name { - fn from_lua(value: $crate::mlu::mlua::Value<'lua>, lua: &'lua $crate::mlu::mlua::Lua) -> ::std::result::Result { + impl $crate::mlu::mlua::FromLua for $type_name { + fn from_lua(value: $crate::mlu::mlua::Value, lua: &$crate::mlu::mlua::Lua) -> ::std::result::Result { $(match <$sub_types as $crate::mlu::FromLuaExact>::from_lua_exact(value.clone(),lua) { Ok(x) => return Ok($type_name::$sub_types(x)), Err($crate::mlu::mlua::Error::FromLuaConversionError{from:_,to:_,message:_}) => {} Err(x) => return Err(x) };)* Err($crate::mlu::mlua::Error::FromLuaConversionError{ - to: stringify!( $($sub_types)|* ), + to: stringify!( $($sub_types)|* ).to_string(), from: value.type_name(), message: None }) @@ -76,28 +76,28 @@ macro_rules! create_union_mlua { }; } -impl<'lua> FromLuaExact<'lua> for String { - fn from_lua_exact(value: mlua::Value<'lua>, _: &'lua mlua::Lua) -> mlua::Result { +impl FromLuaExact for String { + fn from_lua_exact(value: Value, _: &Lua) -> mlua::Result { match value { - mlua::Value::String(x) => Ok(x.to_str()?.to_owned()), - x => Err(mlua::Error::FromLuaConversionError { + Value::String(x) => Ok(x.to_str()?.to_owned()), + x => Err(Error::FromLuaConversionError { from: x.type_name(), - to: "String", + to: "String".to_string(), message: None, }), } } } -impl<'lua> FromLuaExact<'lua> for CString { - fn from_lua_exact(value: mlua::Value<'lua>, lua: &'lua mlua::Lua) -> mlua::Result { +impl FromLuaExact for CString { + fn from_lua_exact(value: Value, lua: &Lua) -> mlua::Result { let ty = value.type_name(); let as_str = mlua::String::from_lua_exact(value, lua)?; - match CStr::from_bytes_with_nul(as_str.as_bytes_with_nul()) { + match CStr::from_bytes_with_nul(as_str.as_bytes_with_nul().deref()) { Ok(x) => Ok(x.to_owned()), - Err(_) => Err(mlua::Error::FromLuaConversionError { + Err(_) => Err(Error::FromLuaConversionError { from: ty, - to: "CString", + to: "CString".to_string(), message: None, }), } @@ -106,13 +106,13 @@ impl<'lua> FromLuaExact<'lua> for CString { macro_rules! impl_from_exact_non_failing { ($T:ty, $conv:pat, $bound_on:ident) => { - impl<'lua> FromLuaExact<'lua> for $T { - fn from_lua_exact(value: mlua::Value<'lua>, _: &'lua mlua::Lua) -> mlua::Result { + impl FromLuaExact for $T { + fn from_lua_exact(value: mlua::Value, _: &mlua::Lua) -> mlua::Result { match value { $conv => Ok($bound_on.into()), x => Err(mlua::Error::FromLuaConversionError { from: x.type_name(), - to: stringify!($T), + to: stringify!($T).to_string(), message: None, }), } @@ -123,20 +123,20 @@ macro_rules! impl_from_exact_non_failing { macro_rules! impl_from_exact { ($T:ty, $conv:pat, $bound_on:ident, $error:ident) => { - impl<'lua> FromLuaExact<'lua> for $T { - fn from_lua_exact(value: mlua::Value<'lua>, _: &'lua mlua::Lua) -> mlua::Result { + impl FromLuaExact for $T { + fn from_lua_exact(value: mlua::Value, _: &mlua::Lua) -> mlua::Result { let ty = value.type_name(); match value { $conv => $bound_on.try_into().map_err(|x: $error| { mlua::Error::FromLuaConversionError { from: ty, - to: stringify!($T), + to: stringify!($T).to_string(), message: Some(x.to_string()), } }), _ => Err(mlua::Error::FromLuaConversionError { from: ty, - to: stringify!($T), + to: stringify!($T).to_string(), message: None, }), } @@ -145,28 +145,28 @@ macro_rules! impl_from_exact { }; } -impl<'lua, T: FromLuaExact<'lua>> FromLuaExact<'lua> for Option { - fn from_lua_exact(value: mlua::Value<'lua>, lua: &'lua mlua::Lua) -> mlua::Result { +impl FromLuaExact for Option { + fn from_lua_exact(value: Value, lua: &Lua) -> mlua::Result { match value { - mlua::Value::Nil => Ok(None), + Value::Nil => Ok(None), x => T::from_lua_exact(x, lua).map(Some), } } } -impl<'lua, T: FromLuaExact<'lua>> FromLuaExact<'lua> for Vec { - fn from_lua_exact(value: mlua::Value<'lua>, lua: &'lua mlua::Lua) -> mlua::Result { +impl FromLuaExact for Vec { + fn from_lua_exact(value: Value, lua: &Lua) -> mlua::Result { match value { - mlua::Value::Table(x) => x + Value::Table(x) => x .sequence_values() .map(|x| match x { Ok(x) => T::from_lua_exact(x, lua), Err(x) => Err(x), }) .collect(), - x => Err(mlua::Error::FromLuaConversionError { + x => Err(Error::FromLuaConversionError { from: x.type_name(), - to: "Vec", + to: "Vec".to_string(), message: None, }), } @@ -174,14 +174,13 @@ impl<'lua, T: FromLuaExact<'lua>> FromLuaExact<'lua> for Vec { } impl< - 'lua, - K: Eq + std::hash::Hash + FromLuaExact<'lua>, - V: FromLuaExact<'lua>, + K: Eq + std::hash::Hash + FromLuaExact, + V: FromLuaExact, S: std::hash::BuildHasher + Default, - > FromLuaExact<'lua> for HashMap + > FromLuaExact for HashMap { - fn from_lua_exact(value: mlua::Value<'lua>, lua: &'lua mlua::Lua) -> mlua::Result { - if let mlua::Value::Table(table) = value { + fn from_lua_exact(value: Value, lua: &Lua) -> mlua::Result { + if let Value::Table(table) = value { table .pairs() .map(|x| match x { @@ -191,19 +190,19 @@ impl< }) .collect() } else { - Err(mlua::Error::FromLuaConversionError { + Err(Error::FromLuaConversionError { from: value.type_name(), - to: "HashMap", + to: "HashMap".to_string(), message: Some("expected table".to_string()), }) } } } -impl<'lua, K: Ord + FromLuaExact<'lua>, V: FromLuaExact<'lua>> FromLuaExact<'lua> +impl FromLuaExact for BTreeMap { - fn from_lua_exact(value: Value<'lua>, lua: &'lua Lua) -> mlua::Result { + fn from_lua_exact(value: Value, lua: &Lua) -> mlua::Result { if let Value::Table(table) = value { table .pairs() @@ -216,15 +215,15 @@ impl<'lua, K: Ord + FromLuaExact<'lua>, V: FromLuaExact<'lua>> FromLuaExact<'lua } else { Err(Error::FromLuaConversionError { from: value.type_name(), - to: "BTreeMap", + to: "BTreeMap".to_string(), message: Some("expected table".to_string()), }) } } } -impl<'lua, T: FromLuaExact<'lua>, const N: usize> FromLuaExact<'lua> for [T; N] { - fn from_lua_exact(value: Value<'lua>, lua: &'lua mlua::Lua) -> mlua::Result { +impl FromLuaExact for [T; N] { + fn from_lua_exact(value: Value, lua: &Lua) -> mlua::Result { let as_vec = Vec::::from_lua_exact(value, lua).map_err(|x| match x { Error::FromLuaConversionError { from, @@ -232,7 +231,7 @@ impl<'lua, T: FromLuaExact<'lua>, const N: usize> FromLuaExact<'lua> for [T; N] message: _, } => Error::FromLuaConversionError { from, - to: "Array", + to: "Array".to_string(), message: Some(format!("Expected array of exactly length {}", N)), }, x => x, @@ -241,7 +240,7 @@ impl<'lua, T: FromLuaExact<'lua>, const N: usize> FromLuaExact<'lua> for [T; N] if len != N { return Err(Error::FromLuaConversionError { from: "Table", - to: "Array", + to: "Array".to_string(), message: Some(format!( "Expected array of exactly length {}, got {}", N, len @@ -257,11 +256,11 @@ impl<'lua, T: FromLuaExact<'lua>, const N: usize> FromLuaExact<'lua> for [T; N] impl_from_exact_non_failing!(bool, mlua::Value::Boolean(x), x); -impl_from_exact_non_failing!(Function<'lua>, mlua::Value::Function(x), x); +impl_from_exact_non_failing!(Function, mlua::Value::Function(x), x); -impl_from_exact_non_failing!(Table<'lua>, mlua::Value::Table(x), x); +impl_from_exact_non_failing!(Table, mlua::Value::Table(x), x); -impl_from_exact_non_failing!(mlua::String<'lua>, mlua::Value::String(x), x); +impl_from_exact_non_failing!(mlua::String, mlua::Value::String(x), x); impl_from_exact!(i8, mlua::Value::Integer(x), x, TryFromIntError); impl_from_exact!(u8, mlua::Value::Integer(x), x, TryFromIntError); @@ -283,8 +282,8 @@ impl_from_exact!(usize, mlua::Value::Integer(x), x, TryFromIntError); impl_from_exact_non_failing!(f64, mlua::Value::Number(x), x); -impl<'lua> FromLuaExact<'lua> for f32 { - fn from_lua_exact(value: mlua::Value<'lua>, lua: &'lua mlua::Lua) -> mlua::Result { +impl FromLuaExact for f32 { + fn from_lua_exact(value: Value, lua: &Lua) -> mlua::Result { f64::from_lua_exact(value, lua).map(|x| x as f32) } } diff --git a/src/mlu/teal_data.rs b/src/mlu/teal_data.rs index b3d3880..ee21ec1 100644 --- a/src/mlu/teal_data.rs +++ b/src/mlu/teal_data.rs @@ -9,11 +9,11 @@ pub trait TealData: Sized + ToTypename { /// ///only difference is that it takes a [TealDataMethods](crate::mlu::TealDataMethods), ///which is the teal version of [UserDataMethods](mlua::UserDataMethods) - fn add_methods<'lua, T: TealDataMethods<'lua, Self>>(_methods: &mut T) {} + fn add_methods>(_methods: &mut T) {} ///same as [UserData::add_fields](mlua::UserData::add_fields). ///Refer to its documentation on how to use it. /// ///only difference is that it takes a [TealDataFields](crate::mlu::TealDataFields), ///which is the teal version of [UserDataFields](mlua::UserDataFields) - fn add_fields<'lua, F: TealDataFields<'lua, Self>>(_fields: &mut F) {} + fn add_fields>(_fields: &mut F) {} } diff --git a/src/mlu/teal_data_fields.rs b/src/mlu/teal_data_fields.rs index 0dd19ae..35591c8 100644 --- a/src/mlu/teal_data_fields.rs +++ b/src/mlu/teal_data_fields.rs @@ -11,36 +11,36 @@ use super::{MaybeSend, TealData}; /// ///The only 2 differences are that [TealDataFields](crate::mlu::TealDataFields) has an extra type bound on `R`. ///These are to get the type names when generating the `.d.tl` file. -pub trait TealDataFields<'lua, T: TealData> { +pub trait TealDataFields { ///Adds documentation to the next field that gets added fn document(&mut self, documentation: &str); /// the teal version of [UserDataFields](mlua::UserDataFields::add_field_method_get) - fn add_field_method_get(&mut self, name: &S, method: M) + fn add_field_method_get(&mut self, name: S, method: M) where - S: AsRef + ?Sized, - R: IntoLua<'lua> + ToTypename, - M: 'static + MaybeSend + Fn(&'lua Lua, &T) -> mlua::Result; + S: AsRef + ToString, + R: IntoLua + ToTypename, + M: 'static + MaybeSend + Fn(&Lua, &T) -> mlua::Result; /// the teal version of [UserDataFields](mlua::UserDataFields::add_field_method_set) - fn add_field_method_set(&mut self, name: &S, method: M) + fn add_field_method_set(&mut self, name: S, method: M) where - S: AsRef + ?Sized, - A: FromLua<'lua> + ToTypename, - M: 'static + MaybeSend + FnMut(&'lua Lua, &mut T, A) -> mlua::Result<()>; + S: AsRef + ToString, + A: FromLua + ToTypename, + M: 'static + MaybeSend + FnMut(&Lua, &mut T, A) -> mlua::Result<()>; /// the teal version of [UserDataFields](mlua::UserDataFields::add_field_function_get) - fn add_field_function_get(&mut self, name: &S, function: F) + fn add_field_function_get(&mut self, name: S, function: F) where - S: AsRef + ?Sized, - R: IntoLua<'lua> + ToTypename, - F: 'static + MaybeSend + Fn(&'lua Lua, AnyUserData<'lua>) -> mlua::Result; + S: ToString + AsRef, + R: IntoLua + ToTypename, + F: 'static + MaybeSend + Fn(&Lua, AnyUserData) -> mlua::Result; /// the teal version of [UserDataFields](mlua::UserDataFields::add_field_function_set) - fn add_field_function_set(&mut self, name: &S, function: F) + fn add_field_function_set(&mut self, name: S, function: F) where - S: AsRef + ?Sized, - A: FromLua<'lua> + ToTypename, - F: 'static + MaybeSend + FnMut(&'lua Lua, AnyUserData<'lua>, A) -> mlua::Result<()>; + S: ToString + AsRef, + A: FromLua + ToTypename, + F: 'static + MaybeSend + FnMut(&Lua, AnyUserData, A) -> mlua::Result<()>; /// the teal version of [UserDataFields](mlua::UserDataFields::add_meta_field_with) fn add_meta_field_with(&mut self, meta: MetaMethod, f: F) where - F: 'static + MaybeSend + Fn(&'lua Lua) -> mlua::Result, - R: IntoLua<'lua> + ToTypename; + F: 'static + MaybeSend + Fn(&Lua) -> mlua::Result, + R: IntoLua + ToTypename; } diff --git a/src/mlu/teal_data_methods.rs b/src/mlu/teal_data_methods.rs index c422909..d2665fe 100644 --- a/src/mlu/teal_data_methods.rs +++ b/src/mlu/teal_data_methods.rs @@ -1,6 +1,6 @@ use std::borrow::Cow; -use mlua::{FromLuaMulti, IntoLua as ToLua, IntoLuaMulti as ToLuaMulti, Lua, MetaMethod, Result}; +use mlua::{FromLuaMulti, IntoLua as ToLua, IntoLuaMulti as ToLuaMulti, Lua, MetaMethod, Result, UserDataRef}; use crate::{TealMultiValue, ToTypename}; @@ -14,83 +14,82 @@ use super::MaybeSend; ///The only 2 differences are that [TealDataMethods](crate::mlu::TealDataMethods) has an extra type bound on `A` and `R`. ///These are to get the type names when generating the `.d.tl` file. -pub trait TealDataMethods<'lua, T: ToTypename> { +pub trait TealDataMethods { ///Exposes a method to lua - fn add_method(&mut self, name: &S, method: M) + fn add_method(&mut self, name: S, method: M) where - S: ?Sized + AsRef, - A: FromLuaMulti<'lua> + TealMultiValue, - R: ToLuaMulti<'lua> + TealMultiValue, - M: 'static + MaybeSend + Fn(&'lua Lua, &T, A) -> Result; + S: ToString + AsRef, + A: FromLuaMulti + TealMultiValue, + R: ToLuaMulti + TealMultiValue, + M: 'static + MaybeSend + Fn(&Lua, &T, A) -> Result; ///Exposes a method to lua that has a mutable reference to Self - fn add_method_mut(&mut self, name: &S, method: M) + fn add_method_mut(&mut self, name: S, method: M) where - S: ?Sized + AsRef, - A: FromLuaMulti<'lua> + TealMultiValue, - R: ToLuaMulti<'lua> + TealMultiValue, - M: 'static + MaybeSend + FnMut(&'lua Lua, &mut T, A) -> Result; + S: ToString + AsRef, + A: FromLuaMulti + TealMultiValue, + R: ToLuaMulti + TealMultiValue, + M: 'static + MaybeSend + FnMut(&Lua, &mut T, A) -> Result; #[cfg(feature = "mlua_async")] ///exposes an async method to lua - fn add_async_method<'s, S: ?Sized + AsRef, A, R, M, MR>(&mut self, name: &S, method: M) + fn add_async_method, A, R, M, MR>(&mut self, name: S, method: M) where - 'lua: 's, T: 'static, - M: Fn(&'lua Lua, &'s T, A) -> MR + MaybeSend + 'static, - A: FromLuaMulti<'lua> + TealMultiValue, - MR: std::future::Future> + 's, - R: ToLuaMulti<'lua> + TealMultiValue; + M: Fn(Lua, UserDataRef, A) -> MR + MaybeSend + 'static, + A: FromLuaMulti + TealMultiValue, + MR: std::future::Future> + mlua::MaybeSend + 'static, + R: ToLuaMulti + TealMultiValue; ///Exposes a function to lua (its a method that does not take Self) - fn add_function(&mut self, name: &S, function: F) + fn add_function(&mut self, name: S, function: F) where - S: ?Sized + AsRef, - A: FromLuaMulti<'lua> + TealMultiValue, - R: ToLuaMulti<'lua> + TealMultiValue, - F: 'static + MaybeSend + Fn(&'lua Lua, A) -> Result; + S: ToString + AsRef, + A: FromLuaMulti + TealMultiValue, + R: ToLuaMulti + TealMultiValue, + F: 'static + MaybeSend + Fn(&Lua, A) -> Result; ///Exposes a mutable function to lua - fn add_function_mut(&mut self, name: &S, function: F) + fn add_function_mut(&mut self, name: S, function: F) where - S: ?Sized + AsRef, - A: FromLuaMulti<'lua> + TealMultiValue, - R: ToLuaMulti<'lua> + TealMultiValue, - F: 'static + MaybeSend + FnMut(&'lua Lua, A) -> Result; + S: ToString + AsRef, + A: FromLuaMulti + TealMultiValue, + R: ToLuaMulti + TealMultiValue, + F: 'static + MaybeSend + FnMut(&Lua, A) -> Result; #[cfg(feature = "mlua_async")] ///exposes an async function to lua - fn add_async_function(&mut self, name: &S, function: F) + fn add_async_function(&mut self, name: S, function: F) where - S: AsRef + ?Sized, - A: FromLuaMulti<'lua> + TealMultiValue, - R: ToLuaMulti<'lua> + TealMultiValue, - F: 'static + MaybeSend + Fn(&'lua Lua, A) -> FR, - FR: 'lua + std::future::Future>; + S: AsRef + ToString, + A: FromLuaMulti + TealMultiValue, + R: ToLuaMulti + TealMultiValue, + F: Fn(Lua, A) -> FR + mlua::MaybeSend + 'static, + FR: std::future::Future> + mlua::MaybeSend + 'static; ///Exposes a meta method to lua [http://lua-users.org/wiki/MetatableEvents](http://lua-users.org/wiki/MetatableEvents) fn add_meta_method(&mut self, meta: MetaMethod, method: M) where - A: FromLuaMulti<'lua> + TealMultiValue, - R: ToLuaMulti<'lua> + TealMultiValue, - M: 'static + MaybeSend + Fn(&'lua Lua, &T, A) -> Result; + A: FromLuaMulti + TealMultiValue, + R: ToLuaMulti + TealMultiValue, + M: 'static + MaybeSend + Fn(&Lua, &T, A) -> Result; ///Exposes a meta and mutable method to lua [http://lua-users.org/wiki/MetatableEvents](http://lua-users.org/wiki/MetatableEvents) fn add_meta_method_mut(&mut self, meta: MetaMethod, method: M) where - A: FromLuaMulti<'lua> + TealMultiValue, - R: ToLuaMulti<'lua> + TealMultiValue, - M: 'static + MaybeSend + FnMut(&'lua Lua, &mut T, A) -> Result; + A: FromLuaMulti + TealMultiValue, + R: ToLuaMulti + TealMultiValue, + M: 'static + MaybeSend + FnMut(&Lua, &mut T, A) -> Result; ///Exposes a meta function to lua [http://lua-users.org/wiki/MetatableEvents](http://lua-users.org/wiki/MetatableEvents) fn add_meta_function(&mut self, meta: MetaMethod, function: F) where - A: FromLuaMulti<'lua> + TealMultiValue, - R: ToLuaMulti<'lua> + TealMultiValue, - F: 'static + MaybeSend + Fn(&'lua Lua, A) -> Result; + A: FromLuaMulti + TealMultiValue, + R: ToLuaMulti + TealMultiValue, + F: 'static + MaybeSend + Fn(&Lua, A) -> Result; ///Exposes a meta and mutable function to lua [http://lua-users.org/wiki/MetatableEvents](http://lua-users.org/wiki/MetatableEvents) fn add_meta_function_mut(&mut self, meta: MetaMethod, function: F) where - A: FromLuaMulti<'lua> + TealMultiValue, - R: ToLuaMulti<'lua> + TealMultiValue, - F: 'static + MaybeSend + FnMut(&'lua Lua, A) -> Result; + A: FromLuaMulti + TealMultiValue, + R: ToLuaMulti + TealMultiValue, + F: 'static + MaybeSend + FnMut(&Lua, A) -> Result; ///Adds documentation to the next method/function that gets added fn document(&mut self, documentation: &str) -> &mut Self; ///Adds documentation for this type itself. They will be written right above the record in the .d.tl file @@ -100,30 +99,30 @@ pub trait TealDataMethods<'lua, T: ToTypename> { } ///collects every instance that a type has -pub trait InstanceCollector<'lua> { +pub trait InstanceCollector { ///adds an instance fn add_instance(&mut self, global_name: P, instance: F) -> Result<&mut Self> where P: Into>, - T: ToTypename + ToLua<'lua>, - F: FnOnce(&'lua mlua::Lua) -> mlua::Result; + T: ToTypename + ToLua, + F: FnOnce(&Lua) -> mlua::Result; ///Adds documentation to the next global instance fn document_instance(&mut self, doc: &'static str) -> &mut Self; } ///used to export instances to lua -pub fn set_global_env(env: T, lua: &mlua::Lua) -> Result<()> { +pub fn set_global_env(env: T, lua: &Lua) -> Result<()> { let globals = lua.globals(); env.add_instances(&mut (globals, lua))?; Ok(()) } -impl<'lua> InstanceCollector<'lua> for (mlua::Table<'lua>, &'lua mlua::Lua) { +impl InstanceCollector for (mlua::Table, &Lua) { fn add_instance(&mut self, global_name: P, instance: F) -> Result<&mut Self> where P: Into>, - T: ToTypename + ToLua<'lua>, - F: FnOnce(&'lua mlua::Lua) -> Result, + T: ToTypename + ToLua, + F: FnOnce(&Lua) -> Result, { let instance = instance(self.1)?; self.0.set(global_name.into(), instance)?; @@ -137,7 +136,7 @@ impl<'lua> InstanceCollector<'lua> for (mlua::Table<'lua>, &'lua mlua::Lua) { ///implement this to easily document what global instances are exposed to lua pub trait ExportInstances: Default { ///adds the instances - fn add_instances<'lua, T: InstanceCollector<'lua>>( + fn add_instances( self, instance_collector: &mut T, ) -> Result<()>; diff --git a/src/mlu/to_from_macro_doc.md b/src/mlu/to_from_macro_doc.md index 0dd1a57..9d1096a 100644 --- a/src/mlu/to_from_macro_doc.md +++ b/src/mlu/to_from_macro_doc.md @@ -167,10 +167,10 @@ enum Example { ), DoubleInnerValue(String,u8) } -fn field_extension<'lua,B:ToTypename + TealData,A: tealr::mlu::TealDataFields<'lua,B>>(fields: &mut A) { +fn field_extension>(fields: &mut A) { //set fields as usual } -fn method_extension<'lua,B:ToTypename,A: tealr::mlu::TealDataMethods<'lua,B>>(fields: &mut A) { +fn method_extension>(fields: &mut A) { //set methods as usual } let instance = Example::SingularInnerValue("SomeValue".into()); diff --git a/src/mlu/typed_function.rs b/src/mlu/typed_function.rs index 8c3ea6d..70e580f 100644 --- a/src/mlu/typed_function.rs +++ b/src/mlu/typed_function.rs @@ -6,22 +6,22 @@ use crate::{TealMultiValue, ToTypename}; ///A typed wrapper around [mlua::Function] #[derive(Debug)] -pub struct TypedFunction<'lua, Params, Response> +pub struct TypedFunction where Params: TealMultiValue, Response: TealMultiValue, { - inner_function: mlua::Function<'lua>, + inner_function: mlua::Function, _p: PhantomData, _r: PhantomData, } -impl<'lua, Params, Response> mlua::FromLua<'lua> for TypedFunction<'lua, Params, Response> +impl mlua::FromLua for TypedFunction where Params: TealMultiValue, Response: TealMultiValue, { - fn from_lua(lua_value: mlua::Value<'lua>, lua: &'lua Lua) -> mlua::Result { + fn from_lua(lua_value: mlua::Value, lua: &Lua) -> mlua::Result { Ok(Self { inner_function: FromLua::from_lua(lua_value, lua)?, _p: PhantomData, @@ -30,17 +30,17 @@ where } } -impl<'lua, Params, Response> IntoLua<'lua> for TypedFunction<'lua, Params, Response> +impl IntoLua for TypedFunction where Params: TealMultiValue, Response: TealMultiValue, { #[allow(clippy::wrong_self_convention)] - fn into_lua(self, _: &'lua Lua) -> mlua::Result> { + fn into_lua(self, _: &Lua) -> mlua::Result { Ok(Value::Function(self.inner_function)) } } -impl<'lua, Params, Response> ToTypename for TypedFunction<'lua, Params, Response> +impl ToTypename for TypedFunction where Params: TealMultiValue, Response: TealMultiValue, @@ -52,10 +52,10 @@ where }) } } -impl<'lua, Params, Response> TypedFunction<'lua, Params, Response> +impl TypedFunction where - Params: IntoLuaMulti<'lua> + TealMultiValue, - Response: FromLuaMulti<'lua> + TealMultiValue, + Params: IntoLuaMulti + TealMultiValue, + Response: FromLuaMulti + TealMultiValue, { ///Same as [mlua::Function::call](mlua::Function#method.call). Calls the function with the given parameters. pub fn call(&self, params: Params) -> mlua::Result { @@ -66,7 +66,7 @@ where self.inner_function.call(params).unwrap() } } -impl<'lua, Params, Response> Clone for TypedFunction<'lua, Params, Response> +impl Clone for TypedFunction where Params: TealMultiValue, Response: TealMultiValue, @@ -79,26 +79,26 @@ where } } } -impl<'lua, Params, Response> From> for Function<'lua> +impl From> for Function where Params: TealMultiValue, Response: TealMultiValue, { - fn from(fun: TypedFunction<'lua, Params, Response>) -> Self { + fn from(fun: TypedFunction) -> Self { fun.inner_function } } -impl<'lua, Params, Response> TypedFunction<'lua, Params, Response> +impl TypedFunction where - Params: FromLuaMulti<'lua> + TealMultiValue, - Response: IntoLuaMulti<'lua> + TealMultiValue, + Params: FromLuaMulti + TealMultiValue, + Response: IntoLuaMulti + TealMultiValue, { ///make a typed function directly from a Rust one. pub fn from_rust< - Func: 'static + crate::mlu::MaybeSend + Fn(&'lua Lua, Params) -> mlua::Result, + Func: 'static + crate::mlu::MaybeSend + Fn(&Lua, Params) -> mlua::Result, >( func: Func, - lua: &'lua Lua, + lua: &Lua, ) -> mlua::Result { Ok(Self { inner_function: lua.create_function(func)?, @@ -108,10 +108,10 @@ where } ///make a typed function directly from a Rust one. pub fn from_rust_mut< - Func: 'static + crate::mlu::MaybeSend + FnMut(&'lua Lua, Params) -> mlua::Result, + Func: 'static + crate::mlu::MaybeSend + FnMut(&Lua, Params) -> mlua::Result, >( func: Func, - lua: &'lua Lua, + lua: &Lua, ) -> mlua::Result { Ok(Self { inner_function: lua.create_function_mut(func)?, @@ -120,13 +120,13 @@ where }) } } -impl<'lua, Params, Response> TypedFunction<'lua, Params, Response> +impl TypedFunction where - Params: IntoLuaMulti<'lua> + TealMultiValue, + Params: IntoLuaMulti + TealMultiValue, Response: TealMultiValue, { ///call a function without trying to convert it to a rust type. - pub fn call_as_lua(&self, params: Params) -> mlua::Result> { + pub fn call_as_lua(&self, params: Params) -> mlua::Result { self.inner_function.call(params) } } diff --git a/src/mlu/user_data_proxy.rs b/src/mlu/user_data_proxy.rs index 441fc37..1d1e01a 100644 --- a/src/mlu/user_data_proxy.rs +++ b/src/mlu/user_data_proxy.rs @@ -24,14 +24,14 @@ impl StaticUserdata for T {} /// - `TealDataFields::add_meta_field_with` /// /// The type documentation is overriden as well. -pub struct UserDataProxy<'lua, T: StaticUserdata> { - user_data: AnyUserData<'lua>, +pub struct UserDataProxy { + user_data: AnyUserData, ph_: PhantomData, } -impl<'lua, T: StaticUserdata> UserDataProxy<'lua, T> { +impl UserDataProxy { /// Creates a new UserDataProxy - pub fn new(lua: &'lua Lua) -> Result { + pub fn new(lua: &Lua) -> Result { Ok(Self { user_data: lua.create_proxy::()?, ph_: Default::default(), @@ -39,7 +39,7 @@ impl<'lua, T: StaticUserdata> UserDataProxy<'lua, T> { } } -impl ToTypename for UserDataProxy<'_, T> { +impl ToTypename for UserDataProxy { fn to_typename() -> crate::Type { let mut x = T::to_typename(); if let Type::Single(x) = &mut x { @@ -49,7 +49,7 @@ impl ToTypename for UserDataProxy<'_, T> { } } -impl TypeBody for UserDataProxy<'_, T> { +impl TypeBody for UserDataProxy { fn get_type_body() -> crate::TypeGenerator { let generator = T::get_type_body(); // extract only "functions" @@ -83,8 +83,8 @@ impl TypeBody for UserDataProxy<'_, T } } -impl<'lua, T: StaticUserdata> IntoLua<'lua> for UserDataProxy<'lua, T> { - fn into_lua(self, lua: &'lua Lua) -> mlua::Result> { +impl IntoLua for UserDataProxy { + fn into_lua(self, lua: &Lua) -> mlua::Result { self.user_data.into_lua(lua) } } diff --git a/src/mlu/user_data_wrapper.rs b/src/mlu/user_data_wrapper.rs index fad4e51..aebf7f2 100644 --- a/src/mlu/user_data_wrapper.rs +++ b/src/mlu/user_data_wrapper.rs @@ -1,8 +1,5 @@ -use bstr::ByteVec; -use mlua::{ - FromLuaMulti, IntoLuaMulti as ToLuaMulti, Lua, MetaMethod, Result, UserData, UserDataFields, - UserDataMethods, -}; +use bstr::{ByteSlice, ByteVec}; +use mlua::{FromLuaMulti, IntoLuaMulti as ToLuaMulti, Lua, MetaMethod, Result, UserData, UserDataFields, UserDataMethods, UserDataRef}; use std::{collections::HashMap, marker::PhantomData}; use super::{MaybeSend, TealData, TealDataFields, TealDataMethods}; @@ -13,20 +10,19 @@ use crate::{type_generator::get_method_data, TealMultiValue, ToTypename, TypeNam ///This allows you to easily implement [UserData](mlua::UserData) by wrapping the [UserDataMethods](mlua::UserDataMethods) in this struct ///and then passing it to the TealData implementation /// -pub struct UserDataWrapper<'a, 'lua, Container, T> +pub struct UserDataWrapper<'a, Container, T> where T: UserData, { cont: &'a mut Container, - _t: std::marker::PhantomData<(&'a (), T)>, - _x: &'lua std::marker::PhantomData<()>, + _t: PhantomData, documentation: HashMap, String>, type_doc: String, next_docs: Option, } -impl<'a, 'lua, Container, T> UserDataWrapper<'a, 'lua, Container, T> +impl<'a, Container, T> UserDataWrapper<'a, Container, T> where - Container: UserDataMethods<'lua, T> + 'a, + Container: UserDataMethods, T: UserData, { ///wraps the [UserDataMethods](mlua::UserDataMethods) so it can be used by [TealData](crate::mlu::TealData) to set methods. @@ -42,7 +38,7 @@ where /// } /// } /// impl UserData for Example { - /// fn add_methods<'lua, T: UserDataMethods<'lua, Self>>(methods: &mut T) { + /// fn add_methods>(methods: &mut T) { /// let mut x = UserDataWrapper::from_user_data_methods(methods); /// ::add_methods(&mut x); /// } @@ -53,16 +49,15 @@ where Self { cont, _t: PhantomData, - _x: &PhantomData, documentation: Default::default(), next_docs: Default::default(), type_doc: Default::default(), } } } -impl<'a, 'lua, Container, T> UserDataWrapper<'a, 'lua, Container, T> +impl<'a, Container, T> UserDataWrapper<'a, Container, T> where - Container: UserDataFields<'lua, T> + 'a, + Container: UserDataFields, T: UserData, { ///wraps the [UserDataMethods](mlua::UserDataFields) so it can be used by [TealData](crate::mlu::TealData) to set fields. @@ -78,7 +73,7 @@ where /// } /// } /// impl UserData for Example { - /// fn add_fields<'lua, T: UserDataFields<'lua, Self>>(methods: &mut T) { + /// fn add_fields>(methods: &mut T) { /// let mut x = UserDataWrapper::from_user_data_fields(methods); /// ::add_fields(&mut x); /// } @@ -89,22 +84,21 @@ where Self { cont, _t: PhantomData, - _x: &PhantomData, documentation: Default::default(), next_docs: Default::default(), type_doc: Default::default(), } } } -impl<'a, 'lua, Container, T: ToTypename> UserDataWrapper<'a, 'lua, Container, T> +impl UserDataWrapper<'_, Container, T> where T: UserData, - //Container: UserDataMethods<'lua, T>, + //Container: UserDataMethods, { fn copy_method_docs(&mut self, to: &str, self_type: bool) where - A: FromLuaMulti<'lua> + TealMultiValue, - R: ToLuaMulti<'lua> + TealMultiValue, + A: FromLuaMulti + TealMultiValue, + R: ToLuaMulti + TealMultiValue, { let type_def = get_method_data::(to, false, self_type.then(|| T::to_typename())); let generated = type_def @@ -118,14 +112,11 @@ where fn copy_field_docs(&mut self, name: &str) { let name = name.as_bytes().to_vec(); let documentation = &mut self.documentation; - let mut current_doc = match documentation.remove(&name) { - Some(x) => x, - None => { - let mut str = crate::type_parts_to_str(F::get_type_parts()).into_owned(); - str.push_str("\n\n docs:\n"); - str - } - }; + let mut current_doc = documentation.remove(&name).unwrap_or_else(|| { + let mut str = crate::type_parts_to_str(F::get_type_parts()).into_owned(); + str.push_str("\n\n docs:\n"); + str + }); current_doc.push_str(&self.next_docs.take().unwrap_or_default()); documentation.insert(name, current_doc); } @@ -140,62 +131,88 @@ where } } -impl<'a, 'lua, Container, T: ToTypename> TealDataMethods<'lua, T> - for UserDataWrapper<'a, 'lua, Container, T> +impl TealDataMethods + for UserDataWrapper<'_, Container, T> where T: UserData, - Container: UserDataMethods<'lua, T>, + Container: UserDataMethods, { #[inline(always)] - fn add_method(&mut self, name: &S, method: M) + fn add_method(&mut self, name: S, method: M) where - S: ?Sized + AsRef, - A: FromLuaMulti<'lua> + TealMultiValue, - R: ToLuaMulti<'lua> + TealMultiValue, - M: 'static + MaybeSend + Fn(&'lua Lua, &T, A) -> Result, + S: ToString + AsRef, + A: FromLuaMulti + TealMultiValue, + R: ToLuaMulti + TealMultiValue, + M: 'static + MaybeSend + Fn(&Lua, &T, A) -> Result, { self.copy_method_docs::(name.as_ref(), true); self.cont.add_method(name, method) } #[inline(always)] - fn add_method_mut(&mut self, name: &S, method: M) + fn add_method_mut(&mut self, name: S, method: M) where - S: ?Sized + AsRef, - A: FromLuaMulti<'lua> + TealMultiValue, - R: ToLuaMulti<'lua> + TealMultiValue, - M: 'static + MaybeSend + FnMut(&'lua Lua, &mut T, A) -> Result, + S: ToString + AsRef, + A: FromLuaMulti + TealMultiValue, + R: ToLuaMulti + TealMultiValue, + M: 'static + MaybeSend + FnMut(&Lua, &mut T, A) -> Result, { self.copy_method_docs::(name.as_ref(), true); self.cont.add_method_mut(name, method) } + #[cfg(feature = "mlua_async")] + #[inline(always)] + fn add_async_method, A, R, M, MR>(&mut self, name: S, method: M) + where + T: 'static, + M: Fn(Lua, UserDataRef, A) -> MR + MaybeSend + 'static, + A: FromLuaMulti + TealMultiValue, + MR: std::future::Future> + mlua::MaybeSend + 'static, + R: ToLuaMulti + TealMultiValue, + { + self.copy_method_docs::(name.as_ref(), true); + self.cont.add_async_method(name, method) + } #[inline(always)] - fn add_function(&mut self, name: &S, function: F) + fn add_function(&mut self, name: S, function: F) where - S: ?Sized + AsRef, - A: FromLuaMulti<'lua> + TealMultiValue, - R: ToLuaMulti<'lua> + TealMultiValue, - F: 'static + MaybeSend + Fn(&'lua Lua, A) -> Result, + S: ToString + AsRef, + A: FromLuaMulti + TealMultiValue, + R: ToLuaMulti + TealMultiValue, + F: 'static + MaybeSend + Fn(&Lua, A) -> Result, { self.copy_method_docs::(name.as_ref(), false); self.cont.add_function(name, function) } #[inline(always)] - fn add_function_mut(&mut self, name: &S, function: F) + fn add_function_mut(&mut self, name: S, function: F) where - S: ?Sized + AsRef, - A: FromLuaMulti<'lua> + TealMultiValue, - R: ToLuaMulti<'lua> + TealMultiValue, - F: 'static + MaybeSend + FnMut(&'lua Lua, A) -> Result, + S: ToString + AsRef, + A: FromLuaMulti + TealMultiValue, + R: ToLuaMulti + TealMultiValue, + F: 'static + MaybeSend + FnMut(&Lua, A) -> Result, { self.copy_method_docs::(name.as_ref(), false); self.cont.add_function_mut(name, function) } + #[cfg(feature = "mlua_async")] + #[inline(always)] + fn add_async_function(&mut self, name: S, function: F) + where + S: AsRef + ToString, + A: FromLuaMulti + TealMultiValue, + R: ToLuaMulti + TealMultiValue, + F: Fn(Lua, A) -> FR + mlua::MaybeSend + 'static, + FR: std::future::Future> + mlua::MaybeSend + 'static, + { + self.copy_method_docs::(name.as_ref(), false); + self.cont.add_async_function(name, function) + } #[inline(always)] fn add_meta_method(&mut self, meta: MetaMethod, method: M) where - A: FromLuaMulti<'lua> + TealMultiValue, - R: ToLuaMulti<'lua> + TealMultiValue, - M: 'static + MaybeSend + Fn(&'lua Lua, &T, A) -> Result, + A: FromLuaMulti + TealMultiValue, + R: ToLuaMulti + TealMultiValue, + M: 'static + MaybeSend + Fn(&Lua, &T, A) -> Result, { self.copy_method_docs::(meta.name(), true); self.cont.add_meta_method(meta, method) @@ -203,74 +220,53 @@ where #[inline(always)] fn add_meta_method_mut(&mut self, meta: MetaMethod, method: M) where - A: FromLuaMulti<'lua> + TealMultiValue, - R: ToLuaMulti<'lua> + TealMultiValue, - M: 'static + MaybeSend + FnMut(&'lua Lua, &mut T, A) -> Result, + A: FromLuaMulti + TealMultiValue, + R: ToLuaMulti + TealMultiValue, + M: 'static + MaybeSend + FnMut(&Lua, &mut T, A) -> Result, { self.copy_method_docs::(meta.name(), true); self.cont.add_meta_method_mut(meta, method) } + #[inline(always)] fn add_meta_function(&mut self, meta: MetaMethod, function: F) where - A: FromLuaMulti<'lua> + TealMultiValue, - R: ToLuaMulti<'lua> + TealMultiValue, - F: 'static + MaybeSend + Fn(&'lua Lua, A) -> Result, + A: FromLuaMulti + TealMultiValue, + R: ToLuaMulti + TealMultiValue, + F: 'static + MaybeSend + Fn(&Lua, A) -> Result, { self.copy_method_docs::(meta.name(), false); self.cont.add_meta_function(meta, function) } + #[inline(always)] fn add_meta_function_mut(&mut self, meta: MetaMethod, function: F) where - A: FromLuaMulti<'lua> + TealMultiValue, - R: ToLuaMulti<'lua> + TealMultiValue, - F: 'static + MaybeSend + FnMut(&'lua Lua, A) -> Result, + A: FromLuaMulti + TealMultiValue, + R: ToLuaMulti + TealMultiValue, + F: 'static + MaybeSend + FnMut(&Lua, A) -> Result, { self.copy_method_docs::(meta.name(), false); self.cont.add_meta_function_mut(meta, function) } - #[cfg(feature = "mlua_async")] - #[inline(always)] - fn add_async_method<'s, S: ?Sized + AsRef, A, R, M, MR>(&mut self, name: &S, method: M) - where - 'lua: 's, - T: 'static, - M: Fn(&'lua Lua, &'s T, A) -> MR + MaybeSend + 'static, - A: FromLuaMulti<'lua> + TealMultiValue, - MR: std::future::Future> + 's, - R: ToLuaMulti<'lua> + TealMultiValue, - { - self.copy_method_docs::(name.as_ref(), true); - self.cont.add_async_method(name, method) - } - - #[cfg(feature = "mlua_async")] - #[inline(always)] - fn add_async_function(&mut self, name: &S, function: F) - where - S: AsRef + ?Sized, - A: FromLuaMulti<'lua> + TealMultiValue, - R: ToLuaMulti<'lua> + TealMultiValue, - F: 'static + MaybeSend + Fn(&'lua Lua, A) -> FR, - FR: 'lua + std::future::Future>, - { - self.copy_method_docs::(name.as_ref(), false); - self.cont.add_async_function(name, function) - } - fn document(&mut self, documentation: &str) -> &mut Self { self.document(documentation); self } + fn document_type(&mut self, documentation: &str) -> &mut Self { + self.type_doc.push_str(documentation); + self.type_doc.push('\n'); + self + } + fn generate_help(&mut self) { let help = self.documentation.clone(); let type_doc = self.type_doc.clone(); self.add_function("help", move |lua, key: Option| { let doc = match key { Some(x) => help - .get(x.as_bytes()) + .get(x.as_bytes().as_bytes()) .map(|v| v.as_bytes()) .map(ToOwned::to_owned) .unwrap_or_else(|| { @@ -295,55 +291,53 @@ where lua.create_string(doc) }) } - - fn document_type(&mut self, documentation: &str) -> &mut Self { - self.type_doc.push_str(documentation); - self.type_doc.push('\n'); - self - } } -impl<'a, 'lua, Container, T: ToTypename + TealData> TealDataFields<'lua, T> - for UserDataWrapper<'a, 'lua, Container, T> +impl TealDataFields + for UserDataWrapper<'_, Container, T> where T: UserData, - Container: UserDataFields<'lua, T>, + Container: UserDataFields, { - fn add_field_method_get(&mut self, name: &S, method: M) + fn document(&mut self, documentation: &str) { + self.document(documentation) + } + + fn add_field_method_get(&mut self, name: S, method: M) where - S: AsRef + ?Sized, - R: mlua::IntoLua<'lua> + ToTypename, - M: 'static + MaybeSend + Fn(&'lua Lua, &T) -> mlua::Result, + S: AsRef + ToString, + R: mlua::IntoLua + ToTypename, + M: 'static + MaybeSend + Fn(&Lua, &T) -> mlua::Result, { self.copy_field_docs::(name.as_ref()); self.cont.add_field_method_get(name, method) } - fn add_field_method_set(&mut self, name: &S, method: M) + fn add_field_method_set(&mut self, name: S, method: M) where - S: AsRef + ?Sized, - A: mlua::FromLua<'lua> + ToTypename, - M: 'static + MaybeSend + FnMut(&'lua Lua, &mut T, A) -> mlua::Result<()>, + S: AsRef + ToString, + A: mlua::FromLua + ToTypename, + M: 'static + MaybeSend + FnMut(&Lua, &mut T, A) -> mlua::Result<()>, { self.copy_field_docs::(name.as_ref()); self.cont.add_field_method_set(name, method) } - fn add_field_function_get(&mut self, name: &S, function: F) + fn add_field_function_get(&mut self, name: S, function: F) where - S: AsRef + ?Sized, - R: mlua::IntoLua<'lua> + ToTypename, - F: 'static + MaybeSend + Fn(&'lua Lua, mlua::AnyUserData<'lua>) -> mlua::Result, + S: AsRef + ToString, + R: mlua::IntoLua + ToTypename, + F: 'static + MaybeSend + Fn(&Lua, mlua::AnyUserData) -> mlua::Result, { self.copy_field_docs::(name.as_ref()); self.cont.add_field_function_get(name, function) } - fn add_field_function_set(&mut self, name: &S, function: F) + fn add_field_function_set(&mut self, name: S, function: F) where - S: AsRef + ?Sized, - A: mlua::FromLua<'lua> + ToTypename, - F: 'static + MaybeSend + FnMut(&'lua Lua, mlua::AnyUserData<'lua>, A) -> mlua::Result<()>, + S: AsRef + ToString, + A: mlua::FromLua + ToTypename, + F: 'static + MaybeSend + FnMut(&Lua, mlua::AnyUserData, A) -> mlua::Result<()>, { self.copy_field_docs::(name.as_ref()); self.cont.add_field_function_set(name, function) @@ -351,14 +345,10 @@ where fn add_meta_field_with(&mut self, meta: MetaMethod, f: F) where - F: 'static + MaybeSend + Fn(&'lua Lua) -> mlua::Result, - R: mlua::IntoLua<'lua> + ToTypename, + F: 'static + MaybeSend + Fn(&Lua) -> mlua::Result, + R: mlua::IntoLua + ToTypename, { self.copy_field_docs::(meta.name()); self.cont.add_meta_field_with(meta, f) } - - fn document(&mut self, documentation: &str) { - self.document(documentation) - } } diff --git a/src/rlu.rs b/src/rlu.rs deleted file mode 100644 index ff1fa69..0000000 --- a/src/rlu.rs +++ /dev/null @@ -1,106 +0,0 @@ -///this module holds some pre made types that can be used to create generics. -pub mod generics; -mod named_parameters; -mod picker_macro; -pub(crate) mod teal_data; -pub(crate) mod teal_data_methods; -mod typed_function; -pub(crate) mod user_data_wrapper; -use std::borrow::Cow; - -pub use rlua; - -pub use self::{ - picker_macro::FromLuaExact, - teal_data::TealData, - teal_data_methods::{set_global_env, ExportInstances, InstanceCollector, TealDataMethods}, - typed_function::TypedFunction, - user_data_wrapper::UserDataWrapper, -}; - -pub use crate::{ - create_generic_rlua as create_generic, create_union_rlua as create_union, - rlua_create_named_parameters as create_named_parameters, -}; - -pub(crate) fn get_meta_name(name: rlua::MetaMethod) -> &'static str { - use rlua::MetaMethod; - match name { - MetaMethod::Add => "__add", - MetaMethod::Sub => "__sub", - MetaMethod::Mul => "__mul", - MetaMethod::Div => "__div", - MetaMethod::Mod => "__mod", - MetaMethod::Pow => "__pow", - MetaMethod::Unm => "__unm", - MetaMethod::IDiv => "__idiv", - MetaMethod::BAnd => "__band", - MetaMethod::BOr => "__bor", - MetaMethod::BXor => "__bxor", - MetaMethod::BNot => "__bnot", - MetaMethod::Shl => "__shl", - MetaMethod::Shr => "__shr", - MetaMethod::Concat => "__concat", - MetaMethod::Len => "__len", - MetaMethod::Eq => "__eq", - MetaMethod::Lt => "__lt", - MetaMethod::Le => "__le", - MetaMethod::Index => "__index", - MetaMethod::NewIndex => "__newindex", - MetaMethod::Call => "__call", - MetaMethod::ToString => "__tostring", - MetaMethod::Pairs => "__pairs", - } -} -use crate::ToTypename; -///Gets the type of a function that is useful for the FromLuaConversion/ToLuaConversion error. -/// -///it should NOT be used to get the real typename. -/// -///# WARNING! -/// -///The plan is to remove it if/when `rlua::Value::type_name` becomes public. Use at your own risk. -pub fn get_type_name(value: &rlua::Value) -> &'static str { - #[allow(deprecated)] - let x = match value { - rlua::Value::Nil => return "Nil", - rlua::Value::Boolean(_) => bool::to_old_type_parts(), - rlua::Value::LightUserData(_) => return "LightUserData", - #[cfg(all( - not(feature = "rlua_builtin-lua51"), - not(feature = "rlua_system-lua51") - ))] - rlua::Value::Integer(_) => rlua::Integer::to_old_type_parts(), - rlua::Value::Number(_) => rlua::Number::to_old_type_parts(), - rlua::Value::String(_) => String::to_old_type_parts(), - rlua::Value::Table(_) => rlua::Table::to_old_type_parts(), - rlua::Value::Function(_) => rlua::Table::to_old_type_parts(), - rlua::Value::Thread(_) => rlua::Thread::to_old_type_parts(), - rlua::Value::UserData(_) => return "userdata", - rlua::Value::Error(_) => return "any", - }; - match crate::type_parts_to_str(x) { - Cow::Borrowed(x) => x, - Cow::Owned(_) => "any", - } -} - -///Implements [rlua::UserData](rlua::UserData) and `tealr::TypeBody` -/// -///It wraps the [rlua::UserDataMethods](rlua::UserDataMethods) into `tealr::rlu::UserDataWrapper` -///and then passes it to `tealr::rlu::TealData::add_methods`. -/// -///Type body is implemented in a similar way, where it uses the `tealr::TealData` implementation to get the types -#[cfg(feature = "derive")] -pub use tealr_derive::RluaUserData as UserData; - -///Implement both [rlua::UserData](rlua::UserData) and `[TypeName](tealr::TypeName]`. -/// -///Look at [tealr_derive::RluaUserData](tealr_derive::RluaUserData) and [tealr_derive::TypeName](tealr_derive::TypeName) -///for more information on how the implemented traits will behave. -#[cfg(feature = "derive")] -pub use tealr_derive::RluaTealDerive as TealDerive; - -#[doc = include_str!("rlu/to_from_macro_doc.md")] -#[cfg(feature = "derive")] -pub use tealr_derive::RluaFromToLua as FromToLua; diff --git a/src/rlu/generics.rs b/src/rlu/generics.rs deleted file mode 100644 index d26e031..0000000 --- a/src/rlu/generics.rs +++ /dev/null @@ -1,123 +0,0 @@ -///This macro creates a new type that acts as similar as possible to [rlua::Value](rlua::Value) -///however, it acts as a generic type instead of being translated as `any`. -/// -///This makes it easy to expose a generic function/method to teal. -///##Example -///``` -///tealr::create_generic_rlua!(pub YourPublicType); -///tealr::create_generic_rlua!(YourPrivateType); -///``` -#[macro_export] -macro_rules! create_generic_rlua { - ($visibility:vis $type_name:ident) => { - #[derive(Clone,Debug)] - #[allow(missing_docs)] - $visibility enum $type_name<'lua> { - Nil, - Boolean(bool), - LightUserData($crate::rlu::rlua::LightUserData), - #[cfg(all( - not(feature = "rlua_builtin-lua51"), - not(feature = "rlua_system-lua51") - ))] - Integer($crate::rlu::rlua::Integer), - Number($crate::rlu::rlua::Number), - String($crate::rlu::rlua::String<'lua>), - Table($crate::rlu::rlua::Table<'lua>), - Function($crate::rlu::rlua::Function<'lua>), - Thread($crate::rlu::rlua::Thread<'lua>), - UserData($crate::rlu::rlua::AnyUserData<'lua>), - Error($crate::rlu::rlua::Error), - } - impl<'lua> $crate::rlu::rlua::FromLua<'lua> for $type_name<'lua> { - fn from_lua(value: $crate::rlu::rlua::Value<'lua>, _: $crate::rlu::rlua::Context<'lua>) -> ::std::result::Result { - Ok(value.into()) - } - } - impl<'lua> $crate::rlu::rlua::ToLua<'lua> for $type_name<'lua> { - fn to_lua(self, _: $crate::rlu::rlua::Context<'lua>) -> ::std::result::Result<$crate::rlu::rlua::Value<'lua>, $crate::rlu::rlua::Error> { - Ok(self.into()) - } - } - impl<'lua> From<$crate::rlu::rlua::Value<'lua>> for $type_name<'lua> { - fn from(value:$crate::rlu::rlua::Value<'lua>) -> $type_name { - use $crate::rlu::rlua::Value::*; - match value { - Nil => $type_name::Nil, - Boolean(x) => $type_name::Boolean(x), - LightUserData(x) => $type_name::LightUserData(x), - #[cfg(all( - not(feature = "rlua_builtin-lua51"), - not(feature = "rlua_system-lua51") - ))] - Integer(x) => $type_name::Integer(x), - Number(x) => $type_name::Number(x), - String(x) => $type_name::String(x), - Table(x) => $type_name::Table(x), - Function(x) => $type_name::Function(x), - Thread(x) => $type_name::Thread(x), - UserData(x) => $type_name::UserData(x), - Error(x) => $type_name::Error(x), - } - } - } - impl<'lua> From<$type_name<'lua>> for $crate::rlu::rlua::Value<'lua> { - fn from(value:$type_name<'lua>) -> $crate::rlu::rlua::Value<'lua> { - use $type_name::*; - match value { - Nil => $crate::rlu::rlua::Value::Nil, - Boolean(x) => $crate::rlu::rlua::Value::Boolean(x), - LightUserData(x) => $crate::rlu::rlua::Value::LightUserData(x), - #[cfg(all( - not(feature = "rlua_builtin-lua51"), - not(feature = "rlua_system-lua51") - ))] - Integer(x) => $crate::rlu::rlua::Value::Integer(x), - Number(x) => $crate::rlu::rlua::Value::Number(x), - String(x) => $crate::rlu::rlua::Value::String(x), - Table(x) => $crate::rlu::rlua::Value::Table(x), - Function(x) => $crate::rlu::rlua::Value::Function(x), - Thread(x) => $crate::rlu::rlua::Value::Thread(x), - UserData(x) => $crate::rlu::rlua::Value::UserData(x), - Error(x) => $crate::rlu::rlua::Value::Error(x), - } - } - } - impl<'lua> ::std::iter::FromIterator<$type_name<'lua>> for $crate::rlu::rlua::MultiValue<'lua> { - fn from_iter<__MacroIterGeneric: IntoIterator>>(iter: __MacroIterGeneric) -> Self { - iter.into_iter().map($crate::rlu::rlua::Value::from).collect() - } - } - impl<'lua> $crate::ToTypename for $type_name<'lua> { - fn to_typename() -> $crate::Type { - $crate::Type::new_single(stringify!($type_name), $crate::KindOfType::Generic) - } - } - }; -} -create_generic_rlua!(pub A); -create_generic_rlua!(pub B); -create_generic_rlua!(pub C); -create_generic_rlua!(pub D); -create_generic_rlua!(pub E); -create_generic_rlua!(pub F); -create_generic_rlua!(pub G); -create_generic_rlua!(pub H); -create_generic_rlua!(pub I); -create_generic_rlua!(pub J); -create_generic_rlua!(pub K); -create_generic_rlua!(pub L); -create_generic_rlua!(pub M); -create_generic_rlua!(pub N); -create_generic_rlua!(pub O); -create_generic_rlua!(pub P); -create_generic_rlua!(pub Q); -create_generic_rlua!(pub R); -create_generic_rlua!(pub S); -create_generic_rlua!(pub T); -create_generic_rlua!(pub U); -create_generic_rlua!(pub V); -create_generic_rlua!(pub W); -create_generic_rlua!(pub X); -create_generic_rlua!(pub Y); -create_generic_rlua!(pub Z); diff --git a/src/rlu/named_parameters.rs b/src/rlu/named_parameters.rs deleted file mode 100644 index c79f623..0000000 --- a/src/rlu/named_parameters.rs +++ /dev/null @@ -1,70 +0,0 @@ -/// Creates a type that allows you to give names to the positional parameters. -/// The names only show up in the documentation and definition files. Making them great to add just a bit more of documentation in the function signature itself -/// -/// Syntax is `create_named_parameters!(YourTypeName with first_field_name : TypeFirstField, second_field_name : TypeSecondField,);` -/// ## Example -/// ``` -/// tealr::rlua_create_named_parameters!( -/// Example with -/// field_1 : String, -/// field_2 : i64, -/// ); -/// tealr::rlu::rlua::Lua::new() -/// .context(|ctx| { -/// let example_func = tealr::rlu::TypedFunction::from_rust(|_, example: Example| { -/// Ok((example.field_1,example.field_2)) -/// },ctx)?; -/// ctx.globals().set("example_func", example_func)?; -/// //Lua still calls the method as normal -/// let (param1,param2) : (String,i64) = ctx.load("return example_func(\"hello, named parameters\", 2)").eval()?; -/// assert_eq!(param1,"hello, named parameters".to_string()); -/// assert_eq!(param2, 2); -/// Ok(()) -/// })?; -/// # Result::<_, tealr::rlu::rlua::Error>::Ok(()) -/// ``` -#[macro_export] -macro_rules! rlua_create_named_parameters { - ($type_name:ident with $($field_name:ident : $field_type_name:ty, )*) => { - pub struct $type_name { - $(pub $field_name : $field_type_name,)* - } - impl $crate::ToTypename for $type_name { - #[allow(clippy::vec_init_then_push)] - fn to_typename() -> $crate::Type { - let mut x = Vec::new(); - $( - x.push(<$field_type_name as $crate::ToTypename>::to_typename()); - )* - std::convert::From::from($crate::Type::Tuple(x)) - } - #[allow(clippy::vec_init_then_push)] - fn to_function_param() -> Vec<$crate::FunctionParam> { - let mut x = Vec::new(); - $( - x.push($crate::FunctionParam { - param_name: Some(stringify!($field_name).into()), - ty: <$field_type_name as $crate::ToTypename>::to_typename() - }); - )* - x - } - } - impl<'lua> $crate::rlu::rlua::FromLuaMulti<'lua> for $type_name { - fn from_lua_multi( - values: $crate::rlu::rlua::MultiValue<'lua>, - lua: $crate::rlu::rlua::Context<'lua>, - ) -> rlua::Result { - let mut as_vec = values.into_vec().into_iter(); - Ok(Self { - $($field_name: <_ as $crate::rlu::rlua::FromLua>::from_lua( - as_vec - .next() - .unwrap_or_else(|| $crate::rlu::rlua::Value::Nil), - lua, - )?,)* - }) - } - } - }; -} diff --git a/src/rlu/picker_macro.rs b/src/rlu/picker_macro.rs deleted file mode 100644 index cc30e4a..0000000 --- a/src/rlu/picker_macro.rs +++ /dev/null @@ -1,353 +0,0 @@ -use std::{ - collections::{BTreeMap, HashMap}, - convert::TryInto, - ffi::{CStr, CString}, - num::TryFromIntError, -}; - -use rlua::{Context, Error, Function, Table, Value}; - -/// similar to [rlua::FromLua](rlua::FromLua). However, -/// however going through this trait you promise that the conversion to a rust value prefers failing over converting/casting -pub trait FromLuaExact<'lua>: Sized { - ///Does the conversion, without any type conversion/casting - fn from_lua_exact(value: rlua::Value<'lua>, lua: rlua::Context<'lua>) -> rlua::Result; -} - -///Creates a new type that is a union of the types you gave. -/// -///It gets translated to a [union](https://github.com/teal-language/tl/blob/master/docs/tutorial.md#union-types) type in `teal` -///and an enum on Rust. -/// -///# Warning: -///`teal` has a few restrictions on what it finds a valid union types. `tealr` does ***NOT*** check if the types you put in are a valid combination -/// -///# Example -///```no_run -///# use tealr::create_union_rlua; -///create_union_rlua!(pub enum YourPublicType = String | f64 | bool); -///create_union_rlua!(enum YourType = String | f64 | bool); -///``` -/// -/// It does the conversion by going through the list of possible types and trying to turn the lua value into a Rust type. -/// If the conversion succeeded then it is assumed that the given lua value corresponds to the given rust type -/// -/// Because of this, it is _very_ important that the Lua -> Rust conversion does as little "type massaging" as possible. -/// As a result, the macro only works with types that implement [FromLuaExact] as implementing this -/// for a type should mean the conversion rather fails than to try and make it work -#[macro_export] -macro_rules! create_union_rlua { - ($visibility:vis $(Derives($($derives:ident), +))? enum $type_name:ident = $($sub_types:ident) | +) => { - #[derive(Clone,$($($derives ,)*)*)] - #[allow(non_camel_case_types)] - $visibility enum $type_name { - $($sub_types($sub_types) ,)* - } - impl<'lua> $crate::rlu::rlua::ToLua<'lua> for $type_name { - fn to_lua(self, lua: $crate::rlu::rlua::Context<'lua>) -> ::std::result::Result<$crate::rlu::rlua::Value<'lua>, $crate::rlu::rlua::Error> { - match self { - $($type_name::$sub_types(x) => x.to_lua(lua),)* - } - } - } - impl<'lua> $crate::rlu::rlua::FromLua<'lua> for $type_name { - fn from_lua(value: $crate::rlu::rlua::Value<'lua>, lua: $crate::rlu::rlua::Context<'lua>) -> ::std::result::Result { - $(match <$sub_types as $crate::rlu::FromLuaExact>::from_lua_exact(value.clone(),lua) { - Ok(x) => return Ok($type_name::$sub_types(x)), - Err($crate::rlu::rlua::Error::FromLuaConversionError{from:_,to:_,message:_}) => {} - Err(x) => return Err(x) - };)* - Err($crate::rlu::rlua::Error::FromLuaConversionError{ - to: stringify!( $($sub_types)|* ), - from: $crate::rlu::get_type_name(&value), - message: None - }) - } - } - impl<'lua> $crate::rlu::FromLuaExact<'lua> for $type_name { - fn from_lua_exact(value: $crate::rlu::rlua::Value<'lua>, lua: $crate::rlu::rlua::Context<'lua>) -> ::std::result::Result { - ::from_lua(value,lua) - } - } - impl $crate::ToTypename for $type_name { - fn to_typename() -> $crate::Type { - let mut types = Vec::new(); - $( - types.push(<$sub_types as $crate::ToTypename>::to_typename()); - )* - - $crate::Type::Or(types) - } - } - - }; -} - -impl<'lua> FromLuaExact<'lua> for String { - fn from_lua_exact(value: rlua::Value<'lua>, _: rlua::Context<'lua>) -> rlua::Result { - match value { - rlua::Value::String(x) => Ok(x.to_str()?.to_owned()), - x => Err(rlua::Error::FromLuaConversionError { - from: x.type_name(), - to: "String", - message: None, - }), - } - } -} - -impl<'lua> FromLuaExact<'lua> for CString { - fn from_lua_exact(value: rlua::Value<'lua>, lua: rlua::Context<'lua>) -> rlua::Result { - let ty = value.type_name(); - let as_str = rlua::String::from_lua_exact(value, lua)?; - match CStr::from_bytes_with_nul(as_str.as_bytes_with_nul()) { - Ok(x) => Ok(x.to_owned()), - Err(_) => Err(rlua::Error::FromLuaConversionError { - from: ty, - to: "CString", - message: None, - }), - } - } -} - -macro_rules! impl_from_exact_non_failing { - ($T:ty, $conv:pat, $bound_on:ident) => { - impl<'lua> FromLuaExact<'lua> for $T { - fn from_lua_exact( - value: rlua::Value<'lua>, - _: rlua::Context<'lua>, - ) -> rlua::Result { - match value { - $conv => Ok($bound_on.into()), - x => Err(rlua::Error::FromLuaConversionError { - from: x.type_name(), - to: stringify!($T), - message: None, - }), - } - } - } - }; -} - -macro_rules! impl_from_exact { - ($T:ty, $conv:pat, $bound_on:ident, $error:ident) => { - impl<'lua> FromLuaExact<'lua> for $T { - fn from_lua_exact( - value: rlua::Value<'lua>, - _: rlua::Context<'lua>, - ) -> rlua::Result { - let ty = value.type_name(); - match value { - $conv => $bound_on.try_into().map_err(|x: $error| { - rlua::Error::FromLuaConversionError { - from: ty, - to: stringify!($T), - message: Some(x.to_string()), - } - }), - _ => Err(rlua::Error::FromLuaConversionError { - from: ty, - to: stringify!($T), - message: None, - }), - } - } - } - }; -} - -impl<'lua, T: FromLuaExact<'lua>> FromLuaExact<'lua> for Option { - fn from_lua_exact(value: rlua::Value<'lua>, lua: rlua::Context<'lua>) -> rlua::Result { - match value { - rlua::Value::Nil => Ok(None), - x => T::from_lua_exact(x, lua).map(Some), - } - } -} - -impl<'lua, T: FromLuaExact<'lua>> FromLuaExact<'lua> for Vec { - fn from_lua_exact(value: rlua::Value<'lua>, lua: rlua::Context<'lua>) -> rlua::Result { - match value { - rlua::Value::Table(x) => x - .sequence_values() - .map(|x| match x { - Ok(x) => T::from_lua_exact(x, lua), - Err(x) => Err(x), - }) - .collect(), - x => Err(rlua::Error::FromLuaConversionError { - from: x.type_name(), - to: "Vec", - message: None, - }), - } - } -} - -impl< - 'lua, - K: Eq + std::hash::Hash + FromLuaExact<'lua>, - V: FromLuaExact<'lua>, - S: std::hash::BuildHasher + Default, - > FromLuaExact<'lua> for HashMap -{ - fn from_lua_exact(value: rlua::Value<'lua>, lua: rlua::Context<'lua>) -> rlua::Result { - if let rlua::Value::Table(table) = value { - table - .pairs() - .map(|x| match x { - Ok((key, value)) => K::from_lua_exact(key, lua) - .and_then(|key| V::from_lua_exact(value, lua).map(|value| (key, value))), - Err(x) => Err(x), - }) - .collect() - } else { - Err(rlua::Error::FromLuaConversionError { - from: value.type_name(), - to: "HashMap", - message: Some("expected table".to_string()), - }) - } - } -} - -impl<'lua, K: Ord + FromLuaExact<'lua>, V: FromLuaExact<'lua>> FromLuaExact<'lua> - for BTreeMap -{ - fn from_lua_exact(value: Value<'lua>, lua: Context<'lua>) -> rlua::Result { - if let Value::Table(table) = value { - table - .pairs() - .map(|x| match x { - Ok((key, value)) => K::from_lua_exact(key, lua) - .and_then(|key| V::from_lua_exact(value, lua).map(|value| (key, value))), - Err(x) => Err(x), - }) - .collect() - } else { - Err(Error::FromLuaConversionError { - from: value.type_name(), - to: "BTreeMap", - message: Some("expected table".to_string()), - }) - } - } -} - -impl<'lua, T: FromLuaExact<'lua>, const N: usize> FromLuaExact<'lua> for [T; N] { - fn from_lua_exact(value: Value<'lua>, lua: Context<'lua>) -> rlua::Result { - let as_vec = Vec::::from_lua_exact(value, lua).map_err(|x| match x { - Error::FromLuaConversionError { - from, - to: _, - message: _, - } => Error::FromLuaConversionError { - from, - to: "Array", - message: Some(format!("Expected array of exactly length {}", N)), - }, - x => x, - })?; - let len = as_vec.len(); - if len != N { - return Err(Error::FromLuaConversionError { - from: "Table", - to: "Array", - message: Some(format!( - "Expected array of exactly length {}, got {}", - N, len - )), - }); - } - match as_vec.try_into() { - Ok(array) => Ok(array), - Err(_) => unreachable!(), - } - } -} - -impl_from_exact_non_failing!(bool, rlua::Value::Boolean(x), x); - -impl_from_exact_non_failing!(Function<'lua>, rlua::Value::Function(x), x); - -impl_from_exact_non_failing!(Table<'lua>, rlua::Value::Table(x), x); - -impl_from_exact_non_failing!(rlua::String<'lua>, rlua::Value::String(x), x); - -#[cfg(all( - not(feature = "rlua_builtin-lua51"), - not(feature = "rlua_system-lua51") -))] -impl_from_exact!(i8, rlua::Value::Integer(x), x, TryFromIntError); -#[cfg(all( - not(feature = "rlua_builtin-lua51"), - not(feature = "rlua_system-lua51") -))] -impl_from_exact!(u8, rlua::Value::Integer(x), x, TryFromIntError); -#[cfg(all( - not(feature = "rlua_builtin-lua51"), - not(feature = "rlua_system-lua51") -))] -impl_from_exact!(i16, rlua::Value::Integer(x), x, TryFromIntError); -#[cfg(all( - not(feature = "rlua_builtin-lua51"), - not(feature = "rlua_system-lua51") -))] -impl_from_exact!(u16, rlua::Value::Integer(x), x, TryFromIntError); -#[cfg(all( - target_pointer_width = "32", - not(feature = "rlua_builtin-lua51"), - not(feature = "rlua_system-lua51") -))] -impl_from_exact_non_failing!(i32, rlua::Value::Integer(x), x); -#[cfg(all( - target_pointer_width = "64", - not(feature = "rlua_builtin-lua51"), - not(feature = "rlua_system-lua51") -))] -impl_from_exact!(i32, rlua::Value::Integer(x), x, TryFromIntError); -#[cfg(all( - not(feature = "rlua_builtin-lua51"), - not(feature = "rlua_system-lua51") -))] -impl_from_exact!(u32, rlua::Value::Integer(x), x, TryFromIntError); -#[cfg(all( - not(feature = "rlua_builtin-lua51"), - not(feature = "rlua_system-lua51") -))] -impl_from_exact_non_failing!(i64, rlua::Value::Integer(x), x); -#[cfg(all( - not(feature = "rlua_builtin-lua51"), - not(feature = "rlua_system-lua51") -))] -impl_from_exact!(u64, rlua::Value::Integer(x), x, TryFromIntError); -#[cfg(all( - not(feature = "rlua_builtin-lua51"), - not(feature = "rlua_system-lua51") -))] -impl_from_exact_non_failing!(i128, rlua::Value::Integer(x), x); -#[cfg(all( - not(feature = "rlua_builtin-lua51"), - not(feature = "rlua_system-lua51") -))] -impl_from_exact!(u128, rlua::Value::Integer(x), x, TryFromIntError); -#[cfg(all( - not(feature = "rlua_builtin-lua51"), - not(feature = "rlua_system-lua51") -))] -impl_from_exact!(isize, rlua::Value::Integer(x), x, TryFromIntError); -#[cfg(all( - not(feature = "rlua_builtin-lua51"), - not(feature = "rlua_system-lua51") -))] -impl_from_exact!(usize, rlua::Value::Integer(x), x, TryFromIntError); - -impl_from_exact_non_failing!(f64, rlua::Value::Number(x), x); - -impl<'lua> FromLuaExact<'lua> for f32 { - fn from_lua_exact(value: rlua::Value<'lua>, lua: rlua::Context<'lua>) -> rlua::Result { - f64::from_lua_exact(value, lua).map(|x| x as f32) - } -} diff --git a/src/rlu/teal_data.rs b/src/rlu/teal_data.rs deleted file mode 100644 index b0bcd80..0000000 --- a/src/rlu/teal_data.rs +++ /dev/null @@ -1,11 +0,0 @@ -use super::TealDataMethods; - -///This is the teal version of [UserData](rlua::UserData). -pub trait TealData: Sized { - ///same as [UserData::add_methods](rlua::UserData::add_methods). - ///Refer to its documentation on how to use it. - /// - ///only difference is that it takes a [TealDataMethods](crate::rlu::TealDataMethods), - ///which is the teal version of [UserDataMethods](rlua::UserDataMethods) - fn add_methods<'lua, T: TealDataMethods<'lua, Self>>(_methods: &mut T) {} -} diff --git a/src/rlu/teal_data_methods.rs b/src/rlu/teal_data_methods.rs deleted file mode 100644 index 8b81009..0000000 --- a/src/rlu/teal_data_methods.rs +++ /dev/null @@ -1,122 +0,0 @@ -use std::borrow::Cow; - -use rlua::{Context, FromLuaMulti, MetaMethod, Result, ToLua, ToLuaMulti}; - -use crate::{TealMultiValue, ToTypename, TypeName}; - -///The teal version of [UserDataMethods](rlua::UserDataMethods) -/// -///The meaning of every method is the same, and so is its use. -///Look at [rlua](rlua::UserDataMethods) for documentation -/// -///The only difference is that [TealDataMethods](crate::rlu::TealDataMethods) have an extra type bound on `A` and `R`. -///These are to get the type names when generating the `.d.tl` file -pub trait TealDataMethods<'lua, T> { - ///Exposes a method to lua - fn add_method(&mut self, name: &S, method: M) - where - S: ?Sized + AsRef, - A: FromLuaMulti<'lua> + TealMultiValue, - R: ToLuaMulti<'lua> + TealMultiValue, - M: 'static + Send + Fn(Context<'lua>, &T, A) -> Result; - ///Exposes a method to lua that has a mutable reference to Self - fn add_method_mut(&mut self, name: &S, method: M) - where - S: ?Sized + AsRef, - A: FromLuaMulti<'lua> + TealMultiValue, - R: ToLuaMulti<'lua> + TealMultiValue, - M: 'static + Send + FnMut(Context<'lua>, &mut T, A) -> Result; - - ///Exposes a function to lua (its a method that does not take Self) - fn add_function(&mut self, name: &S, function: F) - where - S: ?Sized + AsRef, - A: FromLuaMulti<'lua> + TealMultiValue, - R: ToLuaMulti<'lua> + TealMultiValue, - F: 'static + Send + Fn(Context<'lua>, A) -> Result; - - ///Exposes a mutable function to lua - fn add_function_mut(&mut self, name: &S, function: F) - where - S: ?Sized + AsRef, - A: FromLuaMulti<'lua> + TealMultiValue, - R: ToLuaMulti<'lua> + TealMultiValue, - F: 'static + Send + FnMut(Context<'lua>, A) -> Result; - - ///Exposes a meta method to lua - fn add_meta_method(&mut self, meta: MetaMethod, method: M) - where - A: FromLuaMulti<'lua> + TealMultiValue, - R: ToLuaMulti<'lua> + TealMultiValue, - M: 'static + Send + Fn(Context<'lua>, &T, A) -> Result; - ///Exposes a meta and mutable method to lua - fn add_meta_method_mut(&mut self, meta: MetaMethod, method: M) - where - A: FromLuaMulti<'lua> + TealMultiValue, - R: ToLuaMulti<'lua> + TealMultiValue, - M: 'static + Send + FnMut(Context<'lua>, &mut T, A) -> Result; - ///Exposes a meta function to lua - fn add_meta_function(&mut self, meta: MetaMethod, function: F) - where - A: FromLuaMulti<'lua> + TealMultiValue, - R: ToLuaMulti<'lua> + TealMultiValue, - F: 'static + Send + Fn(Context<'lua>, A) -> Result; - ///Exposes a meta and mutable function to lua - fn add_meta_function_mut(&mut self, meta: MetaMethod, function: F) - where - A: FromLuaMulti<'lua> + TealMultiValue, - R: ToLuaMulti<'lua> + TealMultiValue, - F: 'static + Send + FnMut(Context<'lua>, A) -> Result; - ///Adds documentation to the next method/function that gets added - fn document(&mut self, documentation: &str) -> &mut Self; - ///Adds documentation for this type itself. They will be written right above the record in the .d.tl file - fn document_type(&mut self, documentation: &str) -> &mut Self; - ///generates an `instance.help()` function on lua's/teals side, which can be used at run time to view the documentation. - fn generate_help(&mut self); -} - -///collets every instance that needs to be exposed to lua -pub trait InstanceCollector<'lua> { - ///adds an instance - fn add_instance(&mut self, global_name: P, instance: F) -> Result<&mut Self> - where - P: Into>, - T: ToTypename + ToLua<'lua>, - F: FnOnce(Context<'lua>) -> rlua::Result; - ///adds documentation to this instance - fn document_instance(&mut self, doc: &'static str) -> &mut Self; -} -///used to export instances to lua -pub fn set_global_env(env: T, context: rlua::Context) -> rlua::Result<()> { - let globals = context.globals(); - env.add_instances::<_>(&mut (globals, context))?; - Ok(()) -} - -impl<'lua> InstanceCollector<'lua> for (rlua::Table<'lua>, rlua::Context<'lua>) { - fn add_instance< - P: Into>, - T: TypeName + ToLua<'lua>, - F: FnOnce(Context<'lua>) -> rlua::Result, - >( - &mut self, - global_name: P, - instance: F, - ) -> Result<&mut Self> { - let instance = instance(self.1)?; - self.0.set(global_name.into().to_string(), instance)?; - Ok(self) - } - fn document_instance(&mut self, _: &'static str) -> &mut Self { - self - } -} - -///implement this to easily document what global instances are exposed to lua -pub trait ExportInstances: Default { - ///adds the instances - fn add_instances<'lua, T: InstanceCollector<'lua>>( - self, - instance_collector: &mut T, - ) -> Result<()>; -} diff --git a/src/rlu/to_from_macro_doc.md b/src/rlu/to_from_macro_doc.md deleted file mode 100644 index 36be76d..0000000 --- a/src/rlu/to_from_macro_doc.md +++ /dev/null @@ -1,186 +0,0 @@ -Implements the needed traits to make this trait convertible to and from lua values. -It does this differently for structs and enums but will implement the [TypeBody](crate::TypeBody) trait in both cases. - -The macro will also add documentation to the [TypeBody](crate::TypeBody) implementation based on the existing doc comments. In addition, the tags `lua_doc` or `tealr_doc` can be used like `#[tealr_doc = "your comment"]` to add documentation that is only picked up by tealr - -# Structs - -Structs implement the [FromLua](rlua::FromLua) and [ToLua](rlua::ToLua) directly. -These trait implementations convert the struct directly to and from a table. This table contains every filed INCLUDING private fields. - -## Attributes - -### Type level attributes: - -- `tealr_doc`: used as `#[tealr_doc = "your documentation"] - - Allows you to add documentation to the given type - -- `lua_doc`: Alias for `tealr_doc` - -### Field level attributes - -- `remote`: used as `#[tealr(remote = OtherType)]` - - Allows you to specify that a given field should be converted to and from `OtherType` before passing and receiving it to and from lua. - This is done using the [From](std::convert::From) trait. - -- `tealr_doc`: used as `#[tealr_doc = "your documentation"] - - Allows you to add documentation to the given field - -- `lua_doc`: Alias for `tealr_doc` - -# Warning: - -Using this macro on structs WILL make any private fields freely accessible to lua. - -## Example - -```rust -use tealr::{ToTypename,rlu::{rlua::Lua,FromToLua}}; -#[derive(FromToLua,Clone,ToTypename)] -struct Example { - test_field: String -} -impl From for Example { - fn from(t : String) -> Self { - Example{test_field:t} - } -} -impl From for String { - fn from(t: Example) -> Self { - t.test_field - } -} -#[derive(FromToLua,Clone,ToTypename)] -struct Example2 { - #[tealr(remote = Example)] - field1: String -} -let lua = Lua::new(); -lua.context(|lua| { - let instance = Example2 {field1:"amazing".into()}; - let globals = lua.globals(); - globals.set("instance",instance).unwrap(); - let code = " - assert(instance.field1.test_field == \"amazing\") - instance.field1.test_field = \"new_value\" - return instance - "; - let res: Example2 = lua.load(code).set_name("RluaToFromLuaStruct").unwrap().eval().unwrap(); - assert_eq!(res.field1,"new_value"); -}); -``` - -# Enums - -Right now only tuple enums or enums without inner values are supported. -In both cases it works by implementing [TealData](crate::rlu::TealData) and [UserData](rlua::UserData). - -For every variant with inner values 3 methods get added to the [TealData](crate::rlu::TealData). These are: - -- `Is{VariantName}` - Returns true if the underlying enum is of that variant -- `Get{VariantName}`, - Returns `true` and the `inner value` if the enum is of the given variant. Else it returns `false` and `nil` -- `Get{VariantName}OrNil` - Returns the `inner value` if the enum is of the given variant. Else it returns `nil` - -For variants that don't have inner values only the `Is{VariantName}` method gets generated. - -Custom methods can be added using the `extend_methods` attribute. -Similarly, the `extend_fields` attribute can be used to extend the fields that this TealData exposes. - -In addition to the above mentioned traits, it also creates a new zero sized struct. This can be exposed to lua so new instances of this enum can be made while inside lua. -By default this struct has the name `{EnumName}Creator`, but this can be changed using the `creator_name` attribute. -This struct implements [Clone], [TealData](crate::rlu::TealData), [UserData](rlua::UserData), [ToTypename](crate::ToTypename) and [TypeBody](crate::TypeBody) -and has the same visibility as the original enum. - -The [TealData](crate::rlu::TealData) of this struct exposes the functions: - -- `New{VariantName}From` - - This function only gets generated if the variant contains inner values. - - It takes the needed values to construct this variant in the same order as it was defined and returns a new instance of the variant. - -- `New{VariantName}` - This function only gets generated if the variant has no inner values. - It returns a new instance of this enum of the given variant. - -## Attributes - -### Type level attributes - -- `extend_methods` : Used as `#[tealr(extend_methods = function_name)]` - - calls the given function when adding methods to the [TealData](crate::rlu::TealData) of the enum - -- `creator_name` : Used as ``#[tealr(creator_name = NewTypeForCreatorType)]` - - Uses the given name for the enum creator struct - -- `tealr_doc`: used as `#[tealr_doc = "your documentation"] - - Allows you to add documentation to the given type - -- `lua_doc`: Alias for `tealr_doc` - -### Field level attributes - -- `remote`: used as `#[tealr(remote = OtherType)]` - - Allows you to specify that a given field should be converted to and from `OtherType` before passing and receiving it to and from lua. - This is done using the [From](std::convert::From) trait. - -## Example - -```rust -use tealr::{ToTypename,rlu::{FromToLua, TealData,rlua::Lua}}; -#[derive(FromToLua,Clone,ToTypename)] -struct ExampleStruct { - test_field: String - } - impl From for ExampleStruct { - fn from(t : String) -> Self { - ExampleStruct{test_field:t} - } - } - impl From for String { - fn from(t: ExampleStruct) -> Self { - t.test_field - } - } -#[derive(FromToLua,Clone,ToTypename)] -#[tealr(creator_name = ExampleMaker)] -#[tealr(extend_methods = method_extension)] -enum Example { - NoInnerValue, - SingularInnerValue( - #[tealr(remote = ExampleStruct)] - String - ), - DoubleInnerValue(String,u8) -} -fn method_extension<'lua,B:ToTypename,A: tealr::rlu::TealDataMethods<'lua,B>>(fields: &mut A) { - //set methods as usual -} -let instance = Example::SingularInnerValue("SomeValue".into()); -let lua = Lua::new(); -lua.context(|lua|{ - let mut globals = lua.globals(); - globals.set("instance",instance).unwrap(); - globals.set("ExampleCreator",ExampleMaker::new()).unwrap(); - let code = " - - assert(instance:IsSingularInnerValue()) - assert(not instance:IsNoInnerValue()) - assert(instance:GetSingularInnerValueOrNil().test_field == \"SomeValue\") - return ExampleCreator.NewDoubleInnerValueFrom(\"some_new_value\",2) - - "; - let res: Example = lua.load(code).set_name("RluaToFromLuaEnum").unwrap().eval().unwrap(); - assert!(matches!{Example::DoubleInnerValue("some_new_value".to_string(),5),res}); -}); -``` diff --git a/src/rlu/typed_function.rs b/src/rlu/typed_function.rs deleted file mode 100644 index fdd21e1..0000000 --- a/src/rlu/typed_function.rs +++ /dev/null @@ -1,130 +0,0 @@ -use std::marker::PhantomData; - -use rlua::{Context, FromLua, FromLuaMulti, Function, ToLua, ToLuaMulti, Value}; - -use crate::{TealMultiValue, ToTypename}; - -///A typed wrapper around [rlua::Function] -#[derive(Debug)] -pub struct TypedFunction<'lua, Params, Response> -where - Params: TealMultiValue, - Response: TealMultiValue, -{ - inner_function: rlua::Function<'lua>, - _p: PhantomData, - _r: PhantomData, -} -impl<'lua, Params, Response> rlua::FromLua<'lua> for TypedFunction<'lua, Params, Response> -where - Params: TealMultiValue, - Response: TealMultiValue, -{ - fn from_lua(lua_value: rlua::Value<'lua>, lua: rlua::Context<'lua>) -> rlua::Result { - Ok(Self { - inner_function: FromLua::from_lua(lua_value, lua)?, - _p: PhantomData, - _r: PhantomData, - }) - } -} - -impl<'lua, Params, Response> ToLua<'lua> for TypedFunction<'lua, Params, Response> -where - Params: TealMultiValue, - Response: TealMultiValue, -{ - #[allow(clippy::wrong_self_convention)] - fn to_lua(self, _: Context<'lua>) -> rlua::Result> { - Ok(Value::Function(self.inner_function)) - } -} -impl<'lua, Params, Response> ToTypename for TypedFunction<'lua, Params, Response> -where - Params: TealMultiValue, - Response: TealMultiValue, -{ - fn to_typename() -> crate::Type { - crate::Type::Function(crate::FunctionRepresentation { - params: Params::get_types_as_params(), - returns: Response::get_types(), - }) - } -} -impl<'lua, Params, Response> TypedFunction<'lua, Params, Response> -where - Params: ToLuaMulti<'lua> + TealMultiValue, - Response: FromLuaMulti<'lua> + TealMultiValue, -{ - ///Same as [rlua::Function::call](rlua::Function#method.call). Calls the function with the given parameters. - pub fn call(&self, params: Params) -> rlua::Result { - self.inner_function.call(params) - } - ///Calls the function with the given parameters. Panics if something has gone wrong. - pub fn force_call(&self, params: Params) -> Response { - self.inner_function.call(params).unwrap() - } -} -impl<'lua, Params, Response> Clone for TypedFunction<'lua, Params, Response> -where - Params: TealMultiValue, - Response: TealMultiValue, -{ - fn clone(&self) -> Self { - Self { - inner_function: self.inner_function.clone(), - _p: PhantomData, - _r: PhantomData, - } - } -} -impl<'lua, Params, Response> From> for Function<'lua> -where - Params: TealMultiValue, - Response: TealMultiValue, -{ - fn from(fun: TypedFunction<'lua, Params, Response>) -> Self { - fun.inner_function - } -} - -impl<'lua, Params, Response> TypedFunction<'lua, Params, Response> -where - Params: FromLuaMulti<'lua> + TealMultiValue, - Response: ToLuaMulti<'lua> + TealMultiValue, -{ - ///make a typed function directly from a Rust one. - pub fn from_rust, Params) -> rlua::Result>( - func: Func, - context: Context<'lua>, - ) -> rlua::Result { - Ok(Self { - inner_function: context.create_function(func)?, - _p: PhantomData, - _r: PhantomData, - }) - } - ///make a typed function directly from a Rust one. - pub fn from_rust_mut< - Func: 'static + Send + FnMut(Context<'lua>, Params) -> rlua::Result, - >( - func: Func, - context: Context<'lua>, - ) -> rlua::Result { - Ok(Self { - inner_function: context.create_function_mut(func)?, - _p: PhantomData, - _r: PhantomData, - }) - } -} -impl<'lua, Params, Response> TypedFunction<'lua, Params, Response> -where - Params: ToLuaMulti<'lua> + TealMultiValue, - Response: TealMultiValue, -{ - ///call a function without trying to convert it to a rust type. - pub fn call_as_lua(&self, params: Params) -> rlua::Result> { - self.inner_function.call(params) - } -} diff --git a/src/rlu/user_data_wrapper.rs b/src/rlu/user_data_wrapper.rs deleted file mode 100644 index ed6ddf5..0000000 --- a/src/rlu/user_data_wrapper.rs +++ /dev/null @@ -1,204 +0,0 @@ -use std::{collections::HashMap, marker::PhantomData}; - -use bstr::ByteVec; -use rlua::{Context, FromLuaMulti, MetaMethod, Result, ToLuaMulti, UserData, UserDataMethods}; - -use super::{get_meta_name, TealDataMethods}; -use crate::TealMultiValue; - -///Used to turn [UserDataMethods](rlua::UserDataMethods) into [TealDataMethods](crate::rlu::TealDataMethods). -/// -///This allows you to easily implement [UserData](rlua::UserData) by wrapping the [UserDataMethods](rlua::UserDataMethods) in this struct -///and then passing it to the TealData implementation -/// -pub struct UserDataWrapper<'a, 'lua, Container, T> -where - Container: UserDataMethods<'lua, T>, - T: UserData, -{ - cont: &'a mut Container, - _t: PhantomData<(&'a (), T)>, - _x: &'lua PhantomData<()>, - documentation: HashMap, String>, - type_doc: String, - next_docs: Option, -} -impl<'a, 'lua, Container, T> UserDataWrapper<'a, 'lua, Container, T> -where - Container: UserDataMethods<'lua, T> + 'a, - T: UserData, -{ - ///wraps it. - ///``` - ///# use rlua::{Lua, Result, UserData, UserDataMethods}; - ///# use tealr::{rlu::{TealData, TealDataMethods,UserDataWrapper}, TypeWalker, TypeName,}; - /// struct Example {} - /// impl TealData for Example {} - /// impl UserData for Example { - /// fn add_methods<'lua, T: UserDataMethods<'lua, Self>>(methods: &mut T) { - /// let mut x = UserDataWrapper::from_user_data_methods(methods); - /// ::add_methods(&mut x); - /// } - ///} - /// - ///``` - pub fn from_user_data_methods(cont: &'a mut Container) -> Self { - Self { - cont, - _t: std::marker::PhantomData, - _x: &std::marker::PhantomData, - documentation: Default::default(), - type_doc: Default::default(), - next_docs: Default::default(), - } - } -} -impl<'a, 'lua, Container, T> UserDataWrapper<'a, 'lua, Container, T> -where - T: UserData, - Container: UserDataMethods<'lua, T>, -{ - fn copy_docs(&mut self, to: &[u8]) { - if let Some(x) = self.next_docs.take() { - self.documentation.insert(to.to_owned(), x); - } - } -} - -impl<'a, 'lua, Container, T> TealDataMethods<'lua, T> for UserDataWrapper<'a, 'lua, Container, T> -where - T: UserData, - Container: UserDataMethods<'lua, T>, -{ - #[inline(always)] - fn add_method(&mut self, name: &S, method: M) - where - S: ?Sized + AsRef, - A: FromLuaMulti<'lua> + TealMultiValue, - R: ToLuaMulti<'lua> + TealMultiValue, - M: 'static + Send + Fn(Context<'lua>, &T, A) -> Result, - { - self.copy_docs(name.as_ref().as_bytes()); - self.cont.add_method(name.as_ref().as_bytes(), method) - } - #[inline(always)] - fn add_method_mut(&mut self, name: &S, method: M) - where - S: ?Sized + AsRef, - A: FromLuaMulti<'lua>, - R: ToLuaMulti<'lua>, - M: 'static + Send + FnMut(Context<'lua>, &mut T, A) -> Result, - { - self.copy_docs(name.as_ref().as_bytes()); - self.cont.add_method_mut(name.as_ref().as_bytes(), method) - } - #[inline(always)] - fn add_function(&mut self, name: &S, function: F) - where - S: ?Sized + AsRef, - A: FromLuaMulti<'lua>, - R: ToLuaMulti<'lua>, - F: 'static + Send + Fn(Context<'lua>, A) -> Result, - { - self.copy_docs(name.as_ref().as_bytes()); - self.cont.add_function(name.as_ref().as_bytes(), function) - } - #[inline(always)] - fn add_function_mut(&mut self, name: &S, function: F) - where - S: ?Sized + AsRef, - A: FromLuaMulti<'lua>, - R: ToLuaMulti<'lua>, - F: 'static + Send + FnMut(Context<'lua>, A) -> Result, - { - self.copy_docs(name.as_ref().as_bytes()); - self.cont - .add_function_mut(name.as_ref().as_bytes(), function) - } - #[inline(always)] - fn add_meta_method(&mut self, meta: MetaMethod, method: M) - where - A: FromLuaMulti<'lua>, - R: ToLuaMulti<'lua>, - M: 'static + Send + Fn(Context<'lua>, &T, A) -> Result, - { - self.copy_docs(get_meta_name(meta).as_bytes()); - self.cont.add_meta_method(meta, method) - } - #[inline(always)] - fn add_meta_method_mut(&mut self, meta: MetaMethod, method: M) - where - A: FromLuaMulti<'lua>, - R: ToLuaMulti<'lua>, - M: 'static + Send + FnMut(Context<'lua>, &mut T, A) -> Result, - { - self.copy_docs(get_meta_name(meta).as_bytes()); - self.cont.add_meta_method_mut(meta, method) - } - #[inline(always)] - fn add_meta_function(&mut self, meta: MetaMethod, function: F) - where - A: FromLuaMulti<'lua>, - R: ToLuaMulti<'lua>, - F: 'static + Send + Fn(Context<'lua>, A) -> Result, - { - self.copy_docs(get_meta_name(meta).as_bytes()); - self.cont.add_meta_function(meta, function) - } - #[inline(always)] - fn add_meta_function_mut(&mut self, meta: MetaMethod, function: F) - where - A: FromLuaMulti<'lua>, - R: ToLuaMulti<'lua>, - F: 'static + Send + FnMut(Context<'lua>, A) -> Result, - { - self.copy_docs(get_meta_name(meta).as_bytes()); - self.cont.add_meta_function_mut(meta, function) - } - fn document(&mut self, documentation: &str) -> &mut Self { - match &mut self.next_docs { - Some(x) => { - x.push('\n'); - x.push_str(documentation) - } - None => self.next_docs = Some(documentation.to_owned()), - }; - self - } - fn generate_help(&mut self) { - let help = self.documentation.clone(); - let type_doc = self.type_doc.clone(); - self.add_function("help", move |lua, key: Option| { - let doc = match key { - Some(x) => help - .get(x.as_bytes()) - .map(|v| v.as_bytes()) - .map(ToOwned::to_owned) - .unwrap_or_else(|| { - b"The given key is not found. Use `.help()` to list available keys." - .to_vec() - }), - None => { - let mut x = help - .keys() - .map(ToOwned::to_owned) - .flat_map(|mut v| { - v.push_char('\n'); - v - }) - .collect::>(); - let mut y = (type_doc.clone() + "\n" + "Available pages:\n").into_bytes(); - y.append(&mut x); - y - } - }; - lua.create_string(&doc) - }) - } - - fn document_type(&mut self, documentation: &str) -> &mut Self { - self.type_doc.push_str(documentation); - self.type_doc.push('\n'); - self - } -} diff --git a/src/teal_multivalue.rs b/src/teal_multivalue.rs index 0015bed..f28d150 100644 --- a/src/teal_multivalue.rs +++ b/src/teal_multivalue.rs @@ -5,21 +5,17 @@ use crate::{type_representation::KindOfType, ToTypename, Type}; ///Represents a type #[derive(Debug, PartialEq, Eq, Clone, Hash, serde::Serialize, serde::Deserialize)] #[cfg_attr( - all(feature = "mlua", feature = "derive", not(feature = "rlua")), + feature = "derive", derive(crate::mlu::FromToLua, crate::ToTypename) )] #[cfg_attr( - all(feature = "rlua", feature = "derive", not(feature = "mlua")), - derive(crate::rlu::FromToLua, crate::ToTypename) -)] -#[cfg_attr( - all(any(feature = "rlua", feature = "mlua"), feature = "derive",not(all(feature = "rlua", feature = "mlua"))), + all(feature = "derive"), tealr(tealr_name = crate) )] pub struct TealType { ///Name of the type #[cfg_attr( - all(any(feature = "rlua", feature = "mlua"), feature = "derive", not(all(feature = "rlua", feature = "mlua"))), + all(feature = "derive"), tealr(remote = String))] pub name: Cow<'static, str>, ///If the type is build in, a generic or from a library diff --git a/src/type_generator.rs b/src/type_generator.rs index dc49dab..fdb741e 100644 --- a/src/type_generator.rs +++ b/src/type_generator.rs @@ -5,34 +5,18 @@ use std::{ string::FromUtf8Error, }; -#[cfg(feature = "rlua")] -use crate::rlu::{ - get_meta_name as get_meta_name_rlua, TealData as TealDataR, TealDataMethods as TealDataMethodsR, -}; -#[cfg(feature = "rlua")] -use rlua::{ - Context, FromLua as FromLuaR, FromLuaMulti as FromLuaMultiR, MetaMethod as MetaMethodR, - Result as ResultR, ToLuaMulti as ToLuaMultiR, UserData as UserDataR, -}; use serde::{Deserialize, Serialize}; -#[cfg(feature = "mlua")] use crate::mlu::{ get_meta_name as get_meta_name_mlua, MaybeSend, TealData as TealDataM, TealDataFields, TealDataMethods as TealDataMethodsM, }; -#[cfg(feature = "mlua")] -use mlua::{ - FromLua as FromLuaM, FromLuaMulti as FromLuaMultiM, IntoLua as ToLuaM, - IntoLuaMulti as ToLuaMultiM, Lua, MetaMethod as MetaMethodM, Result as ResultM, - UserData as UserDataM, -}; +use mlua::{FromLua as FromLuaM, FromLuaMulti as FromLuaMultiM, IntoLua as ToLuaM, IntoLuaMulti as ToLuaMultiM, Lua, MetaMethod as MetaMethodM, Result as ResultM, UserData as UserDataM, UserDataRef}; use crate::{ exported_function::ExportedFunction, type_parts_to_str, NamePart, ToTypename, Type, TypeName, }; -#[cfg(any(feature = "rlua", feature = "mlua"))] use crate::TealMultiValue; #[derive(Debug, Clone, Hash, PartialEq, Eq)] @@ -46,38 +30,23 @@ impl Deref for NameContainer { &self.0 } } -#[cfg(feature = "rlua")] -impl<'lua> FromLuaR<'lua> for NameContainer { - fn from_lua(lua_value: rlua::Value<'lua>, lua: Context<'lua>) -> ResultR { - Ok(::from_lua(lua_value, lua)? - .into_bytes() - .into()) - } -} -#[cfg(feature = "rlua")] -impl<'lua> crate::rlu::rlua::ToLua<'lua> for NameContainer { - fn to_lua(self, lua: Context<'lua>) -> ResultR> { - lua.create_string(&self.0).and_then(|x| lua.pack(x)) - } -} impl ToTypename for NameContainer { - fn to_typename() -> crate::Type { + fn to_typename() -> Type { Type::new_single("string", crate::KindOfType::Builtin) } } -#[cfg(feature = "mlua")] -impl<'lua> FromLuaM<'lua> for NameContainer { - fn from_lua(lua_value: mlua::Value<'lua>, lua: &'lua Lua) -> ResultM { +impl FromLuaM for NameContainer { + fn from_lua(lua_value: mlua::Value, lua: &Lua) -> ResultM { Ok(::from_lua(lua_value, lua)? .into_bytes() .into()) } } -#[cfg(feature = "mlua")] -impl<'lua> ToLuaM<'lua> for NameContainer { - fn into_lua(self, lua: &'lua Lua) -> ResultM> { + +impl ToLuaM for NameContainer { + fn into_lua(self, lua: &Lua) -> ResultM { lua.create_string(&self.0).and_then(|x| x.into_lua(lua)) } } @@ -112,9 +81,8 @@ impl From> for NameContainer { } } -#[cfg(any(feature = "rlua", feature = "mlua"))] -pub(crate) fn get_method_data>( - name: &S, +pub(crate) fn get_method_data>( + name: S, is_meta_method: bool, extra_self: Option, ) -> ExportedFunction { @@ -123,22 +91,18 @@ pub(crate) fn get_method_data, ), @@ -159,22 +123,18 @@ type V = Vec; ///contains all the information needed to create a teal enum. #[derive(Clone, serde::Serialize, serde::Deserialize)] #[cfg_attr( - all(feature = "mlua", feature = "derive", not(feature = "rlua")), + feature = "derive", derive(crate::mlu::FromToLua, crate::ToTypename) )] #[cfg_attr( - all(feature = "rlua", feature = "derive", not(feature = "mlua")), - derive(crate::rlu::FromToLua, crate::ToTypename) -)] -#[cfg_attr( - all(any(feature = "rlua", feature = "mlua"), feature = "derive", not(all(feature = "rlua", feature = "mlua"))), + feature = "derive", tealr(tealr_name = crate) )] pub struct EnumGenerator { ///the name of this enum #[cfg_attr( - all(any(feature = "rlua", feature = "mlua"), feature = "derive", not(all(feature = "rlua", feature = "mlua"))), + feature = "derive", tealr(remote = V) )] pub name: Cow<'static, [NamePart]>, @@ -220,15 +180,11 @@ impl EnumGenerator { #[derive(serde::Serialize, serde::Deserialize, Clone)] #[cfg_attr( - all(feature = "mlua", feature = "derive", not(feature = "rlua")), + feature = "derive", derive(crate::mlu::FromToLua, crate::ToTypename) )] #[cfg_attr( - all(feature = "rlua", feature = "derive", not(feature = "mlua")), - derive(crate::rlu::FromToLua, crate::ToTypename) -)] -#[cfg_attr( - all(any(feature = "rlua", feature = "mlua"), feature = "derive", not(all(feature = "rlua", feature = "mlua"))), + feature = "derive", tealr(tealr_name = crate) )] @@ -239,7 +195,7 @@ pub struct Field { ///the type of the field, according to the old format #[cfg_attr( - all(any(feature = "rlua", feature = "mlua"), feature = "derive", not(all(feature = "rlua", feature = "mlua"))), + feature = "derive", tealr(remote = V) )] pub teal_type: Cow<'static, [NamePart]>, @@ -274,15 +230,11 @@ impl From for (NameContainer, Cow<'static, [NamePart]>) { ///contains all the information needed to create a record #[derive(Default, Clone, serde::Serialize, serde::Deserialize)] #[cfg_attr( - all(feature = "mlua", feature = "derive", not(feature = "rlua")), + feature = "derive", derive(crate::mlu::FromToLua, crate::ToTypename) )] #[cfg_attr( - all(feature = "rlua", feature = "derive", not(feature = "mlua")), - derive(crate::rlu::FromToLua, crate::ToTypename) -)] -#[cfg_attr( - all(any(feature = "rlua", feature = "mlua"), feature = "derive", not(all(feature = "rlua", feature = "mlua"))), + feature = "derive", tealr(tealr_name = crate) )] @@ -293,7 +245,7 @@ pub struct RecordGenerator { pub is_user_data: bool, ///The name of the type in teal #[cfg_attr( - all(any(feature = "rlua", feature = "mlua"), feature = "derive", not(all(feature = "rlua", feature = "mlua"))), + feature = "derive", tealr(remote = V) )] pub type_name: Cow<'static, [NamePart]>, @@ -350,7 +302,7 @@ impl RecordGenerator { } } - pub(crate) fn generate(self) -> std::result::Result { + pub(crate) fn generate(self) -> Result { //let head = format!("local record {}", self.type_name); let type_name = type_parts_to_str(self.type_name); let mut duplicates = HashSet::new(); @@ -381,7 +333,7 @@ impl RecordGenerator { format!( "{doc}{} : {}", String::from_utf8_lossy(&name), - crate::type_parts_to_str(lua_type) + type_parts_to_str(lua_type) ) }) .collect(); @@ -390,48 +342,48 @@ impl RecordGenerator { .methods .into_iter() .map(|v| v.generate(documentation)) //v.generate(Some(type_name.clone()), documentation)) - .collect::>()?; + .collect::>()?; let methods_mut: Vec<_> = self .mut_methods .into_iter() .map(|v| v.generate(documentation)) - .collect::>()?; + .collect::>()?; let functions: Vec<_> = self .functions .into_iter() .map(|f| f.generate(documentation)) - .collect::>()?; + .collect::>()?; let functions_mut: Vec<_> = self .mut_functions .into_iter() .map(|f| f.generate(documentation)) - .collect::>()?; + .collect::>()?; let meta_methods: Vec<_> = self .meta_method .into_iter() .map(|f| f.generate(documentation)) - .collect::>()?; + .collect::>()?; let meta_methods_mut: Vec<_> = self .meta_method_mut .into_iter() .map(|f| f.generate(documentation)) - .collect::>()?; + .collect::>()?; let meta_function: Vec<_> = self .meta_function .into_iter() .map(|f| f.generate(documentation)) - .collect::>()?; + .collect::>()?; let meta_function_mut: Vec<_> = self .meta_function_mut .into_iter() .map(|f| f.generate(documentation)) - .collect::>()?; + .collect::>()?; let fields = Self::combine_function_names(fields, "Fields"); let methods = Self::combine_function_names(methods, "Pure methods"); @@ -558,17 +510,17 @@ impl RecordGenerator { } } -#[cfg(feature = "rlua")] -impl<'lua, T> TealDataMethodsR<'lua, T> for RecordGenerator + +impl TealDataMethodsM for RecordGenerator where - T: 'static + TealDataR + UserDataR + ToTypename, + T: 'static + TealDataM + UserDataM + ToTypename, { - fn add_method(&mut self, name: &S, _: M) + fn add_method(&mut self, name: S, _: M) where - S: ?Sized + AsRef, - A: FromLuaMultiR<'lua> + TealMultiValue, - R: ToLuaMultiR<'lua> + TealMultiValue, - M: 'static + Send + Fn(Context<'lua>, &T, A) -> ResultR, + S: ToString + AsRef, + A: FromLuaMultiM + TealMultiValue, + R: ToLuaMultiM + TealMultiValue, + M: 'static + MaybeSend + Fn(&Lua, &T, A) -> ResultM, { self.copy_docs(name.as_ref().as_bytes()); self.methods.push(get_method_data::( @@ -578,12 +530,12 @@ where )) } - fn add_method_mut(&mut self, name: &S, _: M) + fn add_method_mut(&mut self, name: S, _: M) where - S: ?Sized + AsRef, - A: FromLuaMultiR<'lua> + TealMultiValue, - R: ToLuaMultiR<'lua> + TealMultiValue, - M: 'static + Send + FnMut(Context<'lua>, &mut T, A) -> ResultR, + S: ToString + AsRef, + A: FromLuaMultiM + TealMultiValue, + R: ToLuaMultiM + TealMultiValue, + M: 'static + MaybeSend + FnMut(&Lua, &mut T, A) -> ResultM, { self.copy_docs(name.as_ref().as_bytes()); self.mut_methods.push(get_method_data::( @@ -593,112 +545,14 @@ where )) } - fn add_function(&mut self, name: &S, _: F) - where - S: ?Sized + AsRef, - A: FromLuaMultiR<'lua> + TealMultiValue, - R: ToLuaMultiR<'lua> + TealMultiValue, - F: 'static + Send + Fn(Context<'lua>, A) -> ResultR, - { - self.copy_docs(name.as_ref().as_bytes()); - self.functions - .push(get_method_data::(name, false, None)) - } - - fn add_function_mut(&mut self, name: &S, _: F) - where - S: ?Sized + AsRef, - A: FromLuaMultiR<'lua> + TealMultiValue, - R: ToLuaMultiR<'lua> + TealMultiValue, - F: 'static + Send + FnMut(Context<'lua>, A) -> ResultR, - { - self.copy_docs(name.as_ref().as_bytes()); - self.mut_functions - .push(get_method_data::(name, false, None)) - } - - fn add_meta_method(&mut self, name: MetaMethodR, _: M) - where - A: FromLuaMultiR<'lua> + TealMultiValue, - R: ToLuaMultiR<'lua> + TealMultiValue, - M: 'static + Send + Fn(Context<'lua>, &T, A) -> ResultR, - { - self.copy_docs(get_meta_name_rlua(name).as_bytes()); - self.meta_method.push(get_method_data::( - get_meta_name_rlua(name), - false, - Some(T::to_typename()), - )) - } - - fn add_meta_method_mut(&mut self, name: MetaMethodR, _: M) - where - A: FromLuaMultiR<'lua> + TealMultiValue, - R: ToLuaMultiR<'lua> + TealMultiValue, - M: 'static + Send + FnMut(Context<'lua>, &mut T, A) -> ResultR, - { - self.copy_docs(get_meta_name_rlua(name).as_bytes()); - self.meta_method_mut.push(get_method_data::( - get_meta_name_rlua(name), - false, - Some(T::to_typename()), - )) - } - - fn add_meta_function(&mut self, name: MetaMethodR, _: F) - where - A: FromLuaMultiR<'lua> + TealMultiValue, - R: ToLuaMultiR<'lua> + TealMultiValue, - F: 'static + Send + Fn(Context<'lua>, A) -> ResultR, - { - self.copy_docs(get_meta_name_rlua(name).as_bytes()); - self.meta_function.push(get_method_data::( - get_meta_name_rlua(name), - false, - None, - )) - } - - fn add_meta_function_mut(&mut self, name: MetaMethodR, _: F) - where - A: FromLuaMultiR<'lua> + TealMultiValue, - R: ToLuaMultiR<'lua> + TealMultiValue, - F: 'static + Send + FnMut(Context<'lua>, A) -> ResultR, - { - self.copy_docs(get_meta_name_rlua(name).as_bytes()); - self.meta_function_mut.push(get_method_data::( - get_meta_name_rlua(name), - false, - None, - )) - } - fn document(&mut self, documentation: &str) -> &mut Self { - self.document(documentation); - self - } - fn generate_help(&mut self) { - self.functions - .push(get_method_data::, String, _>( - "help", false, None, - )) - } - - fn document_type(&mut self, documentation: &str) -> &mut Self { - self.document_type(documentation) - } -} - -#[cfg(feature = "mlua")] -impl<'lua, T> TealDataMethodsM<'lua, T> for RecordGenerator -where - T: 'static + TealDataM + UserDataM + ToTypename, -{ - fn add_method(&mut self, name: &S, _: M) + #[cfg(feature = "mlua_async")] + fn add_async_method, A, R, M, MR>(&mut self, name: S, _: M) where - S: ?Sized + AsRef, - A: FromLuaMultiM<'lua> + TealMultiValue, - R: ToLuaMultiM<'lua> + TealMultiValue, - M: 'static + MaybeSend + Fn(&'lua Lua, &T, A) -> ResultM, + T: 'static, + M: Fn(Lua, UserDataRef, A) -> MR + MaybeSend + 'static, + A: FromLuaMultiM + TealMultiValue, + MR: std::future::Future> + MaybeSend + 'static, + R: ToLuaMultiM + TealMultiValue, { self.copy_docs(name.as_ref().as_bytes()); self.methods.push(get_method_data::( @@ -708,50 +562,49 @@ where )) } - fn add_method_mut(&mut self, name: &S, _: M) + fn add_function(&mut self, name: S, _: F) where - S: ?Sized + AsRef, - A: FromLuaMultiM<'lua> + TealMultiValue, - R: ToLuaMultiM<'lua> + TealMultiValue, - M: 'static + MaybeSend + FnMut(&'lua Lua, &mut T, A) -> ResultM, + S: ToString + AsRef, + A: FromLuaMultiM + TealMultiValue, + R: ToLuaMultiM + TealMultiValue, + F: 'static + MaybeSend + Fn(&Lua, A) -> ResultM, { self.copy_docs(name.as_ref().as_bytes()); - self.mut_methods.push(get_method_data::( - name, - false, - Some(T::to_typename()), - )) + self.functions + .push(get_method_data::(name, false, None)) } - fn add_function(&mut self, name: &S, _: F) + fn add_function_mut(&mut self, name: S, _: F) where - S: ?Sized + AsRef, - A: FromLuaMultiM<'lua> + TealMultiValue, - R: ToLuaMultiM<'lua> + TealMultiValue, - F: 'static + MaybeSend + Fn(&'lua Lua, A) -> ResultM, + S: ToString + AsRef, + A: FromLuaMultiM + TealMultiValue, + R: ToLuaMultiM + TealMultiValue, + F: 'static + MaybeSend + FnMut(&Lua, A) -> ResultM, { self.copy_docs(name.as_ref().as_bytes()); - self.functions + self.mut_functions .push(get_method_data::(name, false, None)) } - fn add_function_mut(&mut self, name: &S, _: F) + #[cfg(feature = "mlua_async")] + fn add_async_function(&mut self, name: S, _: F) where - S: ?Sized + AsRef, - A: FromLuaMultiM<'lua> + TealMultiValue, - R: ToLuaMultiM<'lua> + TealMultiValue, - F: 'static + MaybeSend + FnMut(&'lua Lua, A) -> ResultM, + S: AsRef + ToString, + A: FromLuaMultiM + TealMultiValue, + R: ToLuaMultiM + TealMultiValue, + F: Fn(Lua, A) -> FR + MaybeSend + 'static, + FR: std::future::Future>, { self.copy_docs(name.as_ref().as_bytes()); - self.mut_functions + self.functions .push(get_method_data::(name, false, None)) } fn add_meta_method(&mut self, name: MetaMethodM, _: M) where - A: FromLuaMultiM<'lua> + TealMultiValue, - R: ToLuaMultiM<'lua> + TealMultiValue, - M: 'static + MaybeSend + Fn(&'lua Lua, &T, A) -> ResultM, + A: FromLuaMultiM + TealMultiValue, + R: ToLuaMultiM + TealMultiValue, + M: 'static + MaybeSend + Fn(&Lua, &T, A) -> ResultM, { self.copy_docs(name.name().as_bytes()); self.meta_method.push(get_method_data::( @@ -763,9 +616,9 @@ where fn add_meta_method_mut(&mut self, name: MetaMethodM, _: M) where - A: FromLuaMultiM<'lua> + TealMultiValue, - R: ToLuaMultiM<'lua> + TealMultiValue, - M: 'static + MaybeSend + FnMut(&'lua Lua, &mut T, A) -> ResultM, + A: FromLuaMultiM + TealMultiValue, + R: ToLuaMultiM + TealMultiValue, + M: 'static + MaybeSend + FnMut(&Lua, &mut T, A) -> ResultM, { self.copy_docs(name.name().as_bytes()); self.meta_method_mut.push(get_method_data::( @@ -774,12 +627,11 @@ where Some(T::to_typename()), )) } - fn add_meta_function(&mut self, name: MetaMethodM, _: F) where - A: FromLuaMultiM<'lua> + TealMultiValue, - R: ToLuaMultiM<'lua> + TealMultiValue, - F: 'static + MaybeSend + Fn(&'lua Lua, A) -> ResultM, + A: FromLuaMultiM + TealMultiValue, + R: ToLuaMultiM + TealMultiValue, + F: 'static + MaybeSend + Fn(&Lua, A) -> ResultM, { self.copy_docs(name.name().as_bytes()); self.meta_function.push(get_method_data::( @@ -791,9 +643,9 @@ where fn add_meta_function_mut(&mut self, name: MetaMethodM, _: F) where - A: FromLuaMultiM<'lua> + TealMultiValue, - R: ToLuaMultiM<'lua> + TealMultiValue, - F: 'static + MaybeSend + FnMut(&'lua Lua, A) -> ResultM, + A: FromLuaMultiM + TealMultiValue, + R: ToLuaMultiM + TealMultiValue, + F: 'static + MaybeSend + FnMut(&Lua, A) -> ResultM, { self.copy_docs(name.name().as_bytes()); self.meta_function_mut.push(get_method_data::( @@ -802,44 +654,7 @@ where None, )) } - #[cfg(feature = "mlua_async")] - fn add_async_method<'s, S: ?Sized + AsRef, A, R, M, MR>(&mut self, name: &S, _: M) - where - 'lua: 's, - T: 'static, - M: Fn(&'lua Lua, &'s T, A) -> MR + MaybeSend + 'static, - A: FromLuaMultiM<'lua> + TealMultiValue, - MR: std::future::Future> + 's, - R: ToLuaMultiM<'lua> + TealMultiValue, - { - self.copy_docs(name.as_ref().as_bytes()); - self.methods.push(get_method_data::( - name, - false, - Some(T::to_typename()), - )) - } - - #[cfg(feature = "mlua_async")] - fn add_async_function(&mut self, name: &S, _: F) - where - S: AsRef + ?Sized, - A: FromLuaMultiM<'lua> + TealMultiValue, - R: ToLuaMultiM<'lua> + TealMultiValue, - F: 'static + MaybeSend + Fn(&'lua Lua, A) -> FR, - FR: 'lua + std::future::Future>, - { - self.copy_docs(name.as_ref().as_bytes()); - self.functions - .push(get_method_data::(name, false, None)) - } - fn generate_help(&mut self) { - self.functions - .push(get_method_data::, String, _>( - "help", false, None, - )) - } fn document(&mut self, documentation: &str) -> &mut Self { self.document(documentation); self @@ -847,50 +662,60 @@ where fn document_type(&mut self, documentation: &str) -> &mut Self { self.document_type(documentation) } + fn generate_help(&mut self) { + self.functions + .push(get_method_data::, String, _>( + "help", false, None, + )) + } } -#[cfg(feature = "mlua")] -impl<'lua, T> TealDataFields<'lua, T> for RecordGenerator + +impl TealDataFields for RecordGenerator where T: 'static + TealDataM + UserDataM + ToTypename, { - fn add_field_method_get(&mut self, name: &S, _: M) + fn document(&mut self, documentation: &str) { + self.document(documentation) + } + + fn add_field_method_get(&mut self, name: S, _: M) where - S: AsRef + ?Sized, - R: mlua::IntoLua<'lua> + ToTypename, - M: 'static + MaybeSend + Fn(&'lua Lua, &T) -> mlua::Result, + S: AsRef + ToString, + R: mlua::IntoLua + ToTypename, + M: 'static + MaybeSend + Fn(&Lua, &T) -> mlua::Result, { self.copy_docs(name.as_ref().as_bytes()); self.fields .push((name.as_ref().as_bytes().to_vec().into(), R::to_typename()).into()); } - fn add_field_method_set(&mut self, name: &S, _: M) + fn add_field_method_set(&mut self, name: S, _: M) where - S: AsRef + ?Sized, - A: mlua::FromLua<'lua> + ToTypename, - M: 'static + MaybeSend + FnMut(&'lua Lua, &mut T, A) -> mlua::Result<()>, + S: AsRef + ToString, + A: mlua::FromLua + ToTypename, + M: 'static + MaybeSend + FnMut(&Lua, &mut T, A) -> mlua::Result<()>, { self.copy_docs(name.as_ref().as_bytes()); self.fields .push((name.as_ref().as_bytes().to_vec().into(), A::to_typename()).into()); } - fn add_field_function_get(&mut self, name: &S, _: F) + fn add_field_function_get(&mut self, name: S, _: F) where - S: AsRef + ?Sized, - R: mlua::IntoLua<'lua> + ToTypename, - F: 'static + MaybeSend + Fn(&'lua Lua, mlua::AnyUserData<'lua>) -> mlua::Result, + S: AsRef + ToString, + R: mlua::IntoLua + ToTypename, + F: 'static + MaybeSend + Fn(&Lua, mlua::AnyUserData) -> mlua::Result, { self.copy_docs(name.as_ref().as_bytes()); self.static_fields .push((name.as_ref().as_bytes().to_vec().into(), R::to_typename()).into()); } - fn add_field_function_set(&mut self, name: &S, _: F) + fn add_field_function_set(&mut self, name: S, _: F) where - S: AsRef + ?Sized, - A: mlua::FromLua<'lua> + ToTypename, - F: 'static + MaybeSend + FnMut(&'lua Lua, mlua::AnyUserData<'lua>, A) -> mlua::Result<()>, + S: AsRef + ToString, + A: mlua::FromLua + ToTypename, + F: 'static + MaybeSend + FnMut(&Lua, mlua::AnyUserData, A) -> mlua::Result<()>, { self.copy_docs(name.as_ref().as_bytes()); self.static_fields @@ -899,8 +724,8 @@ where fn add_meta_field_with(&mut self, meta: MetaMethodM, _: F) where - F: 'static + MaybeSend + Fn(&'lua Lua) -> mlua::Result, - R: mlua::IntoLua<'lua> + ToTypename, + F: 'static + MaybeSend + Fn(&Lua) -> mlua::Result, + R: mlua::IntoLua + ToTypename, { let x = Into::::into(meta); let name: Cow<'_, str> = Cow::Owned(x.name().to_string()); @@ -908,8 +733,4 @@ where self.static_fields .push((NameContainer::from(name), R::to_typename()).into()); } - - fn document(&mut self, documentation: &str) { - self.document(documentation) - } } diff --git a/src/type_representation.rs b/src/type_representation.rs index 5d72545..d801f9b 100644 --- a/src/type_representation.rs +++ b/src/type_representation.rs @@ -1,7 +1,7 @@ use crate::{FunctionParam, MapRepresentation, SingleType, ToTypename, Type}; macro_rules! impl_type_name_life_time { ($teal_type:literal $current_type:ty) => { - impl<'lua> ToTypename for $current_type { + impl ToTypename for $current_type { fn to_typename() -> Type { Type::Single(SingleType { name: $teal_type.into(), @@ -32,15 +32,11 @@ macro_rules! impl_type_name { ///Keeps track of any special treatment a type needs to get #[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] #[cfg_attr( - all(feature = "mlua", feature = "derive", not(feature = "rlua")), + feature = "derive", derive(crate::mlu::FromToLua, crate::ToTypename) )] #[cfg_attr( - all(feature = "rlua", feature = "derive", not(feature = "mlua")), - derive(crate::rlu::FromToLua, crate::ToTypename) -)] -#[cfg_attr( - all(any(feature = "rlua", feature = "mlua"), feature = "derive", not(all(feature = "rlua", feature = "mlua")) ), + feature = "derive", tealr(tealr_name = crate) )] pub enum KindOfType { @@ -126,15 +122,11 @@ macro_rules! new_type { } #[derive(Debug, Clone, PartialEq, Hash, Eq, serde::Serialize, serde::Deserialize)] #[cfg_attr( - all(feature = "mlua", feature = "derive", not(feature = "rlua")), + feature = "derive", derive(crate::mlu::FromToLua, crate::ToTypename) )] #[cfg_attr( - all(feature = "rlua", feature = "derive", not(feature = "mlua")), - derive(crate::rlu::FromToLua, crate::ToTypename) -)] -#[cfg_attr( - all(any(feature = "rlua", feature = "mlua"), feature = "derive", not(all(feature = "rlua", feature = "mlua"))), + feature = "derive", tealr(tealr_name = crate) )] ///The parts that a name consists of @@ -143,7 +135,7 @@ pub enum NamePart { ///An example could be the `function(` part inside `function(integer):string` Symbol( #[cfg_attr( - all(any(feature = "rlua", feature = "mlua"), feature = "derive",not(all(feature = "rlua", feature = "mlua"))), + feature = "derive", tealr(remote = String))] Cow<'static, str>, ), @@ -266,42 +258,20 @@ impl_type_name!("string" String,std::ffi::CString,bstr::BString ,&str,&std::ffi: impl_type_name!("number" f32,f64); impl_type_name!("integer" i8,u8,u16,i16,u32,i32,u64,i64,u128,i128,isize,usize); -#[cfg(feature = "rlua")] -impl_type_name_life_time!("thread" rlua::Thread<'lua>); - -#[cfg(feature = "mlua")] -impl_type_name_life_time!("thread" mlua::Thread<'lua>); +impl_type_name_life_time!("thread" mlua::Thread); #[cfg(feature = "mlua_async")] -impl<'lua, R> ToTypename for mlua::AsyncThread<'lua, R> { +impl ToTypename for mlua::AsyncThread { fn to_typename() -> Type { Type::new_single("thread", KindOfType::Builtin) } } -#[cfg(feature = "rlua")] -impl_type_name_life_time!("any" rlua::Value<'lua>); +impl_type_name_life_time!("any" mlua::Value); -#[cfg(feature = "mlua")] -impl_type_name_life_time!("any" mlua::Value<'lua>); - -#[cfg(feature = "rlua")] -use rlua::{Table as TableR, Value as ValueR}; - -#[cfg(feature = "mlua")] use mlua::{Table as TableM, Value as ValueM}; -#[cfg(feature = "rlua")] -impl<'lua> ToTypename for TableR<'lua> { - fn to_typename() -> Type { - Type::Map(crate::MapRepresentation { - key: ValueR::to_typename().into(), - value: ValueR::to_typename().into(), - }) - } -} -#[cfg(feature = "mlua")] -impl<'lua> ToTypename for TableM<'lua> { +impl ToTypename for TableM { fn to_typename() -> Type { Type::Map(crate::MapRepresentation { key: ValueM::to_typename().into(), @@ -310,31 +280,11 @@ impl<'lua> ToTypename for TableM<'lua> { } } -#[cfg(feature = "rlua")] -impl_type_name_life_time!("string" rlua::String<'lua>); - -#[cfg(feature = "mlua")] -impl_type_name_life_time!("string" mlua::String<'lua>); +impl_type_name_life_time!("string" mlua::String); -#[cfg(feature = "mlua")] use mlua::Function as FunctionM; -#[cfg(feature = "rlua")] -use rlua::Function as FunctionR; -#[cfg(feature = "rlua")] -impl<'lua> ToTypename for FunctionR<'lua> { - fn to_typename() -> Type { - Type::Function(crate::FunctionRepresentation { - params: vec![FunctionParam { - param_name: Some("...".into()), - ty: Type::new_single("any", KindOfType::Builtin), - }], - returns: vec![Type::new_single("any...", KindOfType::Builtin)], - }) - } -} -#[cfg(feature = "mlua")] -impl<'lua> ToTypename for FunctionM<'lua> { +impl ToTypename for FunctionM { fn to_typename() -> Type { Type::Function(crate::FunctionRepresentation { params: vec![FunctionParam { diff --git a/src/type_walker.rs b/src/type_walker.rs index 4d7b3e1..4419b76 100644 --- a/src/type_walker.rs +++ b/src/type_walker.rs @@ -7,26 +7,22 @@ type V = Vec; #[derive(Clone, serde::Serialize, serde::Deserialize)] ///Used to document what global instances get made by the module #[cfg_attr( - all(feature = "mlua", feature = "derive", not(feature = "rlua")), + feature = "derive", derive(crate::mlu::FromToLua, crate::ToTypename) )] #[cfg_attr( - all(feature = "rlua", feature = "derive", not(feature = "mlua")), - derive(crate::rlu::FromToLua, crate::ToTypename) -)] -#[cfg_attr( - all(any(feature = "rlua", feature = "mlua"), feature = "derive", not(all(feature = "rlua", feature = "mlua"))), + feature = "derive", tealr(tealr_name = crate) )] pub struct GlobalInstance { ///name of the global #[cfg_attr( - all(any(feature = "rlua", feature = "mlua"), feature = "derive", not(all(feature = "rlua", feature = "mlua"))), + feature = "derive", tealr(remote = String))] pub name: Cow<'static, str>, ///the type according to the old format #[cfg_attr( - all(any(feature = "rlua", feature = "mlua"), feature = "derive", not(all(feature = "rlua", feature = "mlua"))), + feature = "derive", tealr(remote = V))] pub teal_type: Cow<'static, [NamePart]>, ///the type @@ -40,15 +36,11 @@ pub struct GlobalInstance { #[derive(Clone, serde::Serialize, serde::Deserialize)] ///Used to document what global instances get made by the module #[cfg_attr( - all(feature = "mlua", feature = "derive", not(feature = "rlua")), + feature = "derive", derive(crate::mlu::FromToLua, crate::ToTypename) )] #[cfg_attr( - all(feature = "rlua", feature = "derive", not(feature = "mlua")), - derive(crate::rlu::FromToLua, crate::ToTypename) -)] -#[cfg_attr( - all(any(feature = "rlua", feature = "mlua"), feature = "derive", not(all(feature = "rlua", feature = "mlua"))), + feature = "derive", tealr(tealr_name = crate) )] pub struct ExtraPage { @@ -61,15 +53,11 @@ pub struct ExtraPage { ///This generates the .d.tl files #[derive(Clone, serde::Serialize, serde::Deserialize)] #[cfg_attr( - all(feature = "mlua", feature = "derive", not(feature = "rlua")), + feature = "derive", derive(crate::mlu::FromToLua, crate::ToTypename) )] #[cfg_attr( - all(feature = "rlua", feature = "derive", not(feature = "mlua")), - derive(crate::rlu::FromToLua, crate::ToTypename) -)] -#[cfg_attr( - all(any(feature = "rlua", feature = "mlua"), feature = "derive", not(all(feature = "rlua", feature = "mlua"))), + feature = "derive", tealr(tealr_name = crate) )] pub struct TypeWalker { @@ -139,24 +127,6 @@ impl TypeWalker { self } ///generates the `.d.tl` file. It outputs the string, its up to you to store it. - #[cfg_attr(feature = "rlua", doc = " ```")] - #[cfg_attr(not(feature = "rlua"), doc = " ```ignore")] - ///# use rlua::{Lua, Result, UserDataMethods}; - ///# use tealr::{rlu::{TealData,UserData, TealDataMethods,UserDataWrapper}, TypeWalker, ToTypename}; - ///#[derive(UserData,ToTypename)] - ///struct Example {} - ///impl TealData for Example {} - ///let generated_string = TypeWalker::new().process_type::().generate("Examples",true); - ///assert_eq!(generated_string,Ok(String::from("global record Examples - ///\trecord Example - ///\t\tuserdata - /// - /// - ///\tend - ///end - ///return Examples" - ///))); - ///``` #[deprecated( since = "0.9.0", note = "Generation of .d.tl files has been moved to tealr_doc_gen. Use TypeWaller::to_json() instead to get json parsable by tealr_doc_gen." @@ -218,24 +188,6 @@ impl TypeWalker { )) } ///Same as calling [Typewalker::generate(outer_name,true)](crate::TypeWalker::generate). - #[cfg_attr(feature = "rlua", doc = " ```")] - #[cfg_attr(not(feature = "rlua"), doc = " ```ignore")] - ///# use rlua::{Lua, Result, UserDataMethods}; - ///# use tealr::{rlu::{TealData, TealDataMethods,UserDataWrapper,UserData}, TypeWalker, ToTypename}; - ///#[derive(UserData,ToTypename)] - ///struct Example {} - ///impl TealData for Example {} - ///let generated_string = TypeWalker::new().process_type::().generate_global("Examples"); - ///assert_eq!(generated_string,Ok(String::from("global record Examples - ///\trecord Example - ///\t\tuserdata - /// - /// - ///\tend - ///end - ///return Examples" - ///))); - ///``` #[deprecated( since = "0.9.0", note = "Generation of .d.tl files has been moved to tealr_doc_gen. Use TypeWaller::to_json() instead to get json parsable by tealr_doc_gen." @@ -245,24 +197,6 @@ impl TypeWalker { self.generate(outer_name, true) } ///Same as calling [Typewalker::generate(outer_name,false)](crate::TypeWalker::generate). - #[cfg_attr(feature = "rlua", doc = " ```")] - #[cfg_attr(not(feature = "rlua"), doc = " ```ignore")] - ///# use rlua::{Lua, Result, UserDataMethods}; - ///# use tealr::{rlu::{TealData, TealDataMethods,UserDataWrapper,UserData,}, TypeWalker, ToTypename}; - ///#[derive(UserData,ToTypename)] - ///struct Example {} - ///impl TealData for Example {} - ///let generated_string = TypeWalker::new().process_type::().generate_local("Examples"); - ///assert_eq!(generated_string,Ok(String::from("local record Examples - ///\trecord Example - ///\t\tuserdata - /// - /// - ///\tend - ///end - ///return Examples" - ///))); - ///``` #[deprecated( since = "0.9.0", note = "Generation of .d.tl files has been moved to tealr_doc_gen. Use TypeWaller::to_json() instead to get json parsable by tealr_doc_gen." @@ -294,20 +228,6 @@ impl TypeWalker { } } -#[cfg(all(feature = "rlua", not(feature = "mlua")))] -impl TypeWalker { - ///collect every instance that is getting shared with lua - pub fn document_global_instance( - mut self, - ) -> rlua::Result { - let mut collector = crate::export_instance::InstanceWalker::new(); - T::default().add_instances(&mut collector)?; - self.global_instances_off.append(&mut collector.instances); - Ok(self) - } -} - -#[cfg(feature = "mlua")] impl TypeWalker { ///collect every instance that is getting shared with lua pub fn document_global_instance( diff --git a/tealr_derive/Cargo.toml b/tealr_derive/Cargo.toml index 4d3dbbb..ec0229d 100644 --- a/tealr_derive/Cargo.toml +++ b/tealr_derive/Cargo.toml @@ -20,10 +20,10 @@ embed_compiler_from_local = ["tempfile", "zip", "syn"] # most likely doesn't work on Windows debug_macros = [] [dependencies] -proc-macro2 = "1" -quote = "1" -syn = { version = "1", optional = true } -tempfile = { version = "3.3.0", optional = true } -ureq = { version = "2.4.0", optional = true } -venial = "0.4" -zip = { version = "0.6.2", optional = true } +proc-macro2 = "1.0" +quote = "1.0" +syn = { version = "2.0", optional = true } +tempfile = { version = "3.13.0", optional = true } +ureq = { version = "2.9.1", optional = true } +venial = "0.6.0" +zip = { version = "2.2.0", optional = true } diff --git a/tealr_derive/README.md b/tealr_derive/README.md index b968100..b881dc2 100644 --- a/tealr_derive/README.md +++ b/tealr_derive/README.md @@ -1,6 +1,6 @@ # Tealr_derive The derive macro used by [tealr](https://github.com/lenscas/tealr/tree/master/tealr). -Tealr is a crate that can generate `.d.tl` files for types that are exposed to `lua`/`teal` through [rlua](https://crates.io/crates/rlua) +Tealr is a crate that can generate `.d.tl` files for types that are exposed to `lua`/`teal` through [mlua](https://crates.io/crates/mlua) Read the [README.md](https://github.com/lenscas/tealr/tree/master/tealr/README.md) in [tealr](https://github.com/lenscas/tealr/tree/master/tealr) for more information. diff --git a/tealr_derive/src/compile_inline_teal.rs b/tealr_derive/src/compile_inline_teal.rs index f42caaf..2f3a65d 100644 --- a/tealr_derive/src/compile_inline_teal.rs +++ b/tealr_derive/src/compile_inline_teal.rs @@ -68,7 +68,7 @@ pub(crate) fn compile_inline_teal(input: TokenStream) -> TokenStream { .write_all(code.as_bytes()) .expect("Could not write teal source file"); - let mut command = Command::new("tl") + let output = Command::new("tl") .args([ OsStr::new("check"), OsStr::new("-I"), @@ -76,14 +76,11 @@ pub(crate) fn compile_inline_teal(input: TokenStream) -> TokenStream { OsStr::new("input.tl"), ]) .current_dir(temp_path) - .spawn() + .output() .expect("Could not run `tl check`. Make sure it is available in the path"); - if !command - .wait() - .expect("Something has gone wrong while running `tl check`") - .success() - { + if !output.status.success() { + eprintln!("{}", String::from_utf8_lossy(&output.stderr).trim()); panic!("There was an error while typechecking your teal code.") } diff --git a/tealr_derive/src/embed_compiler.rs b/tealr_derive/src/embed_compiler.rs index 82fd2d0..9523810 100644 --- a/tealr_derive/src/embed_compiler.rs +++ b/tealr_derive/src/embed_compiler.rs @@ -72,11 +72,11 @@ fn get_version(version: String) -> String { let mut last = Checker::Start; let is_valid_version = version.char_indices().all(|(loc, chara)| { if loc == 0 { - if chara == 'v' { + return if chara == 'v' { last = Checker::V; - return true; + true } else { - return false; + false } } match last { diff --git a/tealr_derive/src/embed_compiler/load_from_disk.rs b/tealr_derive/src/embed_compiler/load_from_disk.rs index 3b33a7f..538850e 100644 --- a/tealr_derive/src/embed_compiler/load_from_disk.rs +++ b/tealr_derive/src/embed_compiler/load_from_disk.rs @@ -24,49 +24,59 @@ fn run_find_command(is_local: bool) -> String { } } stdout - .split(|v| v == '\n') + .lines() .next() .expect("Did not get the expected output from luarocks") .to_string() } use std::{fs::read_to_string, process::Command}; + pub(crate) fn discover_tl_tl() -> String { run_find_command(true) } pub(crate) fn get_local_teal(path: String) -> String { let build_dir = tempfile::tempdir().expect("Could not get a temporary directory to build teal"); - - let mut compiler = Command::new("tl") + let compiler = Command::new("tl") .current_dir(build_dir.path()) .args(["gen", "-o", "output.lua", "--skip-compat53"]) .arg(path) .spawn() - .map_err(|v| { - let x = match v.kind() { + .map_err(|e| { + (match e.kind() { std::io::ErrorKind::NotFound => "Could not compile teal. Command `tl` not found.", std::io::ErrorKind::PermissionDenied => { "Permission denied when running the teal compiler." } _ => "Error while running teal. Is it available as `tl` in the path?", - }; + }, e) + }); + + + let mut compiler = match compiler { + Ok(v) => v, + Err((msg, e)) => { + if let Err(error) = build_dir.close() { + eprint!("Could not close temporary directory : {}", error); + } panic!( - "Could not compile teal:{x}\nRaw error:{}\n{}", - v.raw_os_error() - .map(|v| format!("Kind:{v}")) + "Could not compile teal:{msg}\nRaw error:{}\n{}", + e.raw_os_error() + .map(|e| format!("Kind:{e}")) .unwrap_or_default(), - v.kind() + e.kind() ) - }) - .expect( - "Failed running the teal compiler. Is `tl` installed and accessible through the path?", - ); + }, + }; if !compiler .wait() .expect("Could not wait for compiler") .success() { + if let Err(e) = build_dir.close() { + eprint!("Could not close temporary directory : {}", e); + } panic!( "Could not compile teal without compatibility library. Is `tl` available in the path?" ) diff --git a/tealr_derive/src/from_to_lua.rs b/tealr_derive/src/from_to_lua.rs index 5a316fc..ea8c6ea 100644 --- a/tealr_derive/src/from_to_lua.rs +++ b/tealr_derive/src/from_to_lua.rs @@ -1,6 +1,6 @@ use proc_macro2::{Literal, Span, TokenStream}; use quote::ToTokens; -use venial::{parse_declaration, Struct}; +use venial::{parse_item, Struct}; pub(crate) fn get_tealr_name(attributes: &[venial::Attribute]) -> TokenStream { find_tag_with_value("tealr_name", attributes) @@ -12,21 +12,22 @@ pub(crate) fn get_tealr_name(attributes: &[venial::Attribute]) -> TokenStream { fn debug_macro(ts: TokenStream) -> TokenStream { let hopefully_unique = { use ::std::hash::*; - let ref mut hasher = ::std::collections::hash_map::RandomState::new().build_hasher(); + let hasher = &mut RandomState::new().build_hasher(); hasher.finish() }; //FEEL FREE TO TWEAK THIS DEFAULT PATH (e.g., your target dir) let mut debug_macros_dir = ::std::path::PathBuf::from("/tmp"); - ::std::fs::create_dir_all(&debug_macros_dir).unwrap(); - let ref file_name = { + std::fs::create_dir_all(&debug_macros_dir).unwrap(); + let file_name = &{ debug_macros_dir.push(format!("{:016x}.rs", hopefully_unique)); debug_macros_dir.into_os_string().into_string().unwrap() }; - ::std::fs::write(file_name, ts.to_string()).unwrap(); + std::fs::write(file_name, ts.to_string()).unwrap(); quote!(::core::include! { #file_name }) } #[cfg(not(feature = "debug_macros"))] +#[warn(unused_imports)] fn debug_macro(ts: TokenStream) -> TokenStream { ts } @@ -47,7 +48,7 @@ fn find_tag_with_value(to_find: &str, tags: &[venial::Attribute]) -> Option impl Iterator + '_ { +fn find_doc_tags(tags: &[venial::Attribute]) -> impl Iterator + '_ { tags.iter() .filter(|v| { let name = v.path.iter().cloned().collect::().to_string(); @@ -101,7 +102,6 @@ struct BasicConfig { teal_data_methods_location: TokenStream, invalid_enum_variant_error: TokenStream, typename_macro: TokenStream, - is_mlua: bool, } fn implement_for_struct(structure: Struct, config: BasicConfig) -> TokenStream { @@ -122,10 +122,10 @@ fn implement_for_struct(structure: Struct, config: BasicConfig) -> TokenStream { let (to_add, (to_remove, type_body)): (TokenStream, (TokenStream, TokenStream)) = match structure.fields { - venial::StructFields::Unit => { + venial::Fields::Unit => { return venial::Error::new("Unit structs are not supported.").to_compile_error() } - venial::StructFields::Tuple(x) => x + venial::Fields::Tuple(x) => x .fields .iter() .enumerate() @@ -138,14 +138,14 @@ fn implement_for_struct(structure: Struct, config: BasicConfig) -> TokenStream { .map(|v| { ( quote! {<#v as ::std::convert::From<#ty>>::from(self.#key_as_str)}, - quote! {get::<_,#v>(#key)?.into()}, + quote! {get::<#v>(#key)?.into()}, v.to_token_stream(), ) }) .unwrap_or_else(|| { (quote! {self.#key_as_str}, quote! {get(#key)?}, quote! {#ty}) }); - let docs = find_doc_tags(&x.0.attributes).map(|v|quote!{ + let docs = find_doc_tags(&x.0.attributes).map(|v| quote! { gen.document(#v); }).collect::(); ( @@ -165,7 +165,7 @@ fn implement_for_struct(structure: Struct, config: BasicConfig) -> TokenStream { ) }) .unzip(), - venial::StructFields::Named(x) => x + venial::Fields::Named(x) => x .fields .iter() .map(|(field, _)| { @@ -176,7 +176,7 @@ fn implement_for_struct(structure: Struct, config: BasicConfig) -> TokenStream { .map(|v| { ( quote! {<#v as ::std::convert::From<#ty>>::from(self.#name)}, - quote! {get::<_,#v>(stringify!(#name))?.into()}, + quote! {get::<#v>(stringify!(#name))?.into()}, v.to_token_stream(), ) }) @@ -187,7 +187,7 @@ fn implement_for_struct(structure: Struct, config: BasicConfig) -> TokenStream { quote! {#ty}, ) }); - let docs = find_doc_tags(&field.attributes).map(|v|quote!{ + let docs = find_doc_tags(&field.attributes).map(|v| quote! { gen.document(#v); }).collect::(); ( @@ -213,15 +213,15 @@ fn implement_for_struct(structure: Struct, config: BasicConfig) -> TokenStream { .map(|v| quote! {gen.document_type(#v);}) .collect::(); quote! { - impl<'lua> #to_loc for #name { + impl #to_loc for #name { fn #to_lua_name(self, #lua_location) -> #result_location_to { let mut table = #create_table()?; #to_add lua.pack(table) } } - impl<'lua> #from_loc for #name { - fn from_lua(lua_value:#lua_value<'lua>, #lua_location) -> #result_location_from { + impl #from_loc for #name { + fn from_lua(lua_value:#lua_value, #lua_location) -> #result_location_from { let as_table = match lua_value { #lua_value::Table(x) => x, x => Err(#error_message)? @@ -269,13 +269,13 @@ fn implement_for_enum(enumeration: venial::Enum, config: BasicConfig) -> TokenSt .then(|| { ( quote! { - fn add_fields<'lua, F: #user_data_fields_location<'lua, Self>>(fields: &mut F) { + fn add_fields>(fields: &mut F) { let mut wrapper = #user_data_wrapper_location::from_user_data_fields(fields); ::add_fields(&mut wrapper) } }, quote! { - fn add_fields<'lua, F: #teal_data_fields_location<'lua, Self>>(fields: &mut F) { + fn add_fields>(fields: &mut F) { #call_fields } }, @@ -285,15 +285,15 @@ fn implement_for_enum(enumeration: venial::Enum, config: BasicConfig) -> TokenSt ) }) .unwrap_or_else(|| (quote! {}, quote! {}, quote! {})); - let (variant_functions,(creator_functions,is_of_branches)): (Vec<_>,(Vec<_>,TokenStream)) = enumeration + let (variant_functions, (creator_functions, is_of_branches)): (Vec<_>, (Vec<_>, TokenStream)) = enumeration .variants .iter() .map(|(variant, _)| { let variant_name = variant.name.clone(); let variant_as_text = variant_name.to_string(); let is_method_name = format!("Is{}", variant_name); - let new_variant = format!("New{}",variant_name); - if variant.is_empty_variant() || matches!(variant.contents, venial::StructFields::Unit) + let new_variant = format!("New{}", variant_name); + if variant.is_empty_variant() || matches!(variant.fields, venial::Fields::Unit) { (vec![quote! { methods.add_method( @@ -303,21 +303,21 @@ fn implement_for_enum(enumeration: venial::Enum, config: BasicConfig) -> TokenSt _ => Ok(false) } ); - }],( - vec![quote! { + }], ( + vec![quote! { methods.add_function( #new_variant, |_,()| Ok(#name::#variant_name) ); }], - quote!{ + quote! { #name::#variant_name => #variant_as_text, } - )) + )) } else { - match &variant.contents { - venial::StructFields::Unit => unreachable!(), - venial::StructFields::Tuple(x) => { + match &variant.fields { + venial::Fields::Unit => unreachable!(), + venial::Fields::Tuple(x) => { let field_names = x .fields .iter() @@ -328,39 +328,39 @@ fn implement_for_enum(enumeration: venial::Enum, config: BasicConfig) -> TokenSt ( proc_macro2::Ident::new( &z, - x.ty.tokens.first().map(|v|v.span()) - .unwrap_or_else(Span::call_site)), + x.ty.tokens.first().map(|v| v.span()) + .unwrap_or_else(Span::call_site)), x, ) }) .map(|(v, field)| (quote! {#v}, field)) .map(|(v, field)| { - let (to_with_from_conversion,to_as_type) = find_tag_with_value("remote", &field.attributes) + let (to_with_from_conversion, to_as_type) = find_tag_with_value("remote", &field.attributes) .or_else(|| { let name = field.ty; Some(quote! {#name}) }) .map(|to| - (quote! {<(#to) as From<_>>::from(<_ as ::std::borrow::ToOwned>::to_owned(#v))},to) + (quote! {<(#to) as From<_>>::from(<_ as ::std::borrow::ToOwned>::to_owned(#v))}, to) ) .unwrap(); - (v, to_with_from_conversion,to_as_type) + (v, to_with_from_conversion, to_as_type) }) .collect::>(); let (combined_with, combined_none): (Vec, Vec) = field_names .iter() - .map(|(_, to,_)| (quote!(Some(#to)), quote!(None))) + .map(|(_, to, _)| (quote!(Some(#to)), quote!(None))) .unzip(); - let to_as_types =add_commas(field_names.iter().map(|(_,_,t)|t.to_owned()).collect::>()); + let to_as_types = add_commas(field_names.iter().map(|(_, _, t)| t.to_owned()).collect::>()); let combined_none = add_commas(combined_none); let combined_with = add_commas(combined_with); - let fields = add_commas(field_names.iter().map(|v|v.0.clone()).collect()); + let fields = add_commas(field_names.iter().map(|v| v.0.clone()).collect()); let is_method_name = format!("Is{variant_name}"); let get_method_name = format!("Get{variant_name}"); let get_or_nill_method_name = format!("Get{variant_name}OrNil"); let new_variant_from = format!("New{variant_name}From"); - let convert_back = add_commas(field_names.into_iter().map(|(name,_,_)|quote!{<_ as ::std::convert::From<_>>::from(#name)}).collect::>()); + let convert_back = add_commas(field_names.into_iter().map(|(name, _, _)| quote! {<_ as ::std::convert::From<_>>::from(#name)}).collect::>()); (vec![quote! { methods.add_method( @@ -384,18 +384,18 @@ fn implement_for_enum(enumeration: venial::Enum, config: BasicConfig) -> TokenSt _ => Ok((#combined_none)) } ); - }],( - vec![quote!{ + }], ( + vec![quote! { methods.add_function( #new_variant_from, |_, (#fields):(#to_as_types)| Ok(#name::#variant_name(#convert_back)) ); - }],quote!{ + }], quote! { #name::#variant_name(..) => #variant_as_text, })) } - venial::StructFields::Named(_) => todo!(), + venial::Fields::Named(_) => todo!(), } } }) @@ -408,14 +408,14 @@ fn implement_for_enum(enumeration: venial::Enum, config: BasicConfig) -> TokenSt let mut trait_impls = quote! { impl #user_data_location for #name { #add_fields_user_data - fn add_methods<'lua, M: #user_data_methods_location<'lua, Self>>(methods: &mut M) { + fn add_methods>(methods: &mut M) { let mut wrapper = #user_data_wrapper_location::from_user_data_methods(methods); ::add_methods(&mut wrapper) } } impl #teal_data_location for #name { #add_fields_teal_data - fn add_methods<'lua, T: #teal_data_methods_location<'lua, Self>>(methods: &mut T) { + fn add_methods>(methods: &mut T) { #variant_functions #call_methods methods.add_method("GetTypeName",|_,this,()|{ @@ -463,12 +463,8 @@ fn implement_for_enum(enumeration: venial::Enum, config: BasicConfig) -> TokenSt ///Automatically generated for exporting to lua #visibility struct #creator_struct_name {} }; - let parsed = venial::parse_declaration(creator_struct_stream.clone()).unwrap(); - let with_userdata = if config.is_mlua { - crate::user_data::impl_mlua_user_data_derive(&parsed) - } else { - crate::user_data::impl_rlua_user_data_derive(&parsed) - }; + let parsed = parse_item(creator_struct_stream.clone()).unwrap(); + let with_userdata = crate::user_data::impl_mlua_user_data_derive(&parsed); //let with_type_name = crate::user_data::impl_type_representation_derive(&parsed); let with_clone = quote! { impl ::std::clone::Clone for #creator_struct_name { @@ -479,7 +475,7 @@ fn implement_for_enum(enumeration: venial::Enum, config: BasicConfig) -> TokenSt }; let with_teal_data = quote! { impl #teal_data_location for #creator_struct_name { - fn add_methods<'lua, T: #teal_data_methods_location<'lua, Self>>(methods: &mut T) { + fn add_methods>(methods: &mut T) { #creator_functions } } @@ -503,15 +499,14 @@ fn implement_for_enum(enumeration: venial::Enum, config: BasicConfig) -> TokenSt trait_impls.extend(Some(with_clone)); trait_impls.extend(Some(with_teal_data)); trait_impls.extend(Some(with_new_method)); - if config.is_mlua { - let from_loc = config.from_location; - let lua_value = config.lua_value; - let lua_location = config.lua_type; - let error_message = config.error_message; - let result_location_from = config.result_location_from; - let with_from_lua = quote! { - impl<'lua> #from_loc for #name { - fn from_lua(lua_value:#lua_value<'lua>, #lua_location) -> #result_location_from { + let from_loc = config.from_location; + let lua_value = config.lua_value; + let lua_location = config.lua_type; + let error_message = config.error_message; + let result_location_from = config.result_location_from; + let with_from_lua = quote! { + impl #from_loc for #name { + fn from_lua(lua_value:#lua_value, #lua_location) -> #result_location_from { match lua_value.as_userdata() { Some(x) => x.take(), None => { @@ -522,8 +517,7 @@ fn implement_for_enum(enumeration: venial::Enum, config: BasicConfig) -> TokenSt } } }; - trait_impls.extend(with_from_lua); - } + trait_impls.extend(with_from_lua); trait_impls } @@ -567,7 +561,7 @@ fn implement_for_c_enum(enumeration: venial::Enum, config: BasicConfig) -> Token .unzip(); quote! { - impl<'lua> #to_loc for #name { + impl #to_loc for #name { fn #to_lua_name(self, #lua_location) -> #result_location_to { let res = match self { #to_branches @@ -575,8 +569,8 @@ fn implement_for_c_enum(enumeration: venial::Enum, config: BasicConfig) -> Token lua.pack(res.to_string()) } } - impl<'lua> #from_loc for #name { - fn from_lua(lua_value:#lua_value<'lua>, #lua_location) -> #result_location_from { + impl #from_loc for #name { + fn from_lua(lua_value:#lua_value, #lua_location) -> #result_location_from { let x = ::from_lua(lua_value,lua)?; Ok(match x.as_str() { #from_branches @@ -596,21 +590,21 @@ fn implement_for_c_enum(enumeration: venial::Enum, config: BasicConfig) -> Token } pub(crate) fn mlua_from_to_lua(input: TokenStream) -> TokenStream { - let parsed = parse_declaration(input).unwrap(); + let parsed = parse_item(input).unwrap(); let tealr_name = get_tealr_name(parsed.attributes()); let config = BasicConfig { - to_location: quote! {#tealr_name::mlu::mlua::IntoLua<'lua>}, + to_location: quote! {#tealr_name::mlu::mlua::IntoLua}, to_lua_name: quote!(into_lua), - from_location: quote! {#tealr_name::mlu::mlua::FromLua<'lua>}, + from_location: quote! {#tealr_name::mlu::mlua::FromLua}, create_table: quote! {lua.create_table}, - result_location_to: quote! {#tealr_name::mlu::mlua::Result<#tealr_name::mlu::mlua::Value<'lua>>}, + result_location_to: quote! {#tealr_name::mlu::mlua::Result<#tealr_name::mlu::mlua::Value>}, result_location_from: quote! {#tealr_name::mlu::mlua::Result}, - lua_type: quote! {lua: &'lua #tealr_name::mlu::mlua::Lua}, + lua_type: quote! {lua: &#tealr_name::mlu::mlua::Lua}, lua_value: quote! {#tealr_name::mlu::mlua::Value}, error_message: quote! { #tealr_name::mlu::mlua::Error::FromLuaConversionError{ from: x.type_name(), - to: "unknown", + to: "unknown".to_string(), message:None } }, @@ -629,64 +623,15 @@ pub(crate) fn mlua_from_to_lua(input: TokenStream) -> TokenStream { teal_data_methods_location: quote! {#tealr_name::mlu::TealDataMethods}, invalid_enum_variant_error: quote! {#tealr_name::mlu::mlua::Error::FromLuaConversionError { from: "String", - to:"unknown", + to:"unknown".to_string(), message:None } }, - is_mlua: true, typename_macro: quote! {#tealr_name::ToTypename}, }; match parsed { - venial::Declaration::Struct(x) => implement_for_struct(x, config), - venial::Declaration::Enum(x) => implement_for_enum(x, config), + venial::Item::Struct(x) => implement_for_struct(x, config), + venial::Item::Enum(x) => implement_for_enum(x, config), _ => venial::Error::new("Only structs and enums are supported").to_compile_error(), } } - -pub(crate) fn rlua_from_to_lua(input: TokenStream) -> TokenStream { - let parsed = parse_declaration(input).unwrap(); - let tealr_name = get_tealr_name(parsed.attributes()); - let config = BasicConfig { - to_location: quote! {#tealr_name::rlu::rlua::ToLua<'lua>}, - to_lua_name: quote!(to_lua), - from_location: quote! {#tealr_name::rlu::rlua::FromLua<'lua>}, - create_table: quote! {lua.create_table}, - result_location_to: quote! {#tealr_name::rlu::rlua::Result<#tealr_name::rlu::rlua::Value<'lua>>}, - result_location_from: quote! {#tealr_name::rlu::rlua::Result}, - lua_type: quote! {lua: #tealr_name::rlu::rlua::Context<'lua>}, - lua_value: quote! {#tealr_name::rlu::rlua::Value}, - error_message: quote! { - #tealr_name::rlu::rlua::Error::FromLuaConversionError{ - from: x. type_name(), - to: "unknown", - message:None - } - }, - type_name_path: quote! {#tealr_name::ToTypename}, - type_body_loc: quote! {#tealr_name::TypeBody}, - type_generator_loc: quote! {#tealr_name::TypeGenerator}, - record_generator_loc: quote! {#tealr_name::RecordGenerator}, - enum_generator_loc: quote! {#tealr_name::EnumGenerator}, - user_data_location: quote! {#tealr_name::rlu::rlua::UserData}, - teal_data_location: quote! {#tealr_name::rlu::TealData}, - has_userdata_fields: false, - user_data_fields_location: quote! {}, - teal_data_fields_location: quote! {#tealr_name::rlu::TealDataFields}, - user_data_wrapper_location: quote! {#tealr_name::rlu::UserDataWrapper}, - user_data_methods_location: quote! {#tealr_name::rlu::rlua::UserDataMethods}, - teal_data_methods_location: quote! {#tealr_name::rlu::TealDataMethods}, - invalid_enum_variant_error: quote! {#tealr_name::rlu::rlua::Error::FromLuaConversionError { - from: "String", - to:"unknown", - message:None - } }, - is_mlua: false, - typename_macro: quote! {#tealr_name::ToTypename}, - }; - - debug_macro(match parsed { - venial::Declaration::Struct(x) => implement_for_struct(x, config), - venial::Declaration::Enum(x) => implement_for_enum(x, config), - _ => venial::Error::new("Only structs and enums are supported").to_compile_error(), - }) -} diff --git a/tealr_derive/src/lib.rs b/tealr_derive/src/lib.rs index 025c123..689f6d0 100644 --- a/tealr_derive/src/lib.rs +++ b/tealr_derive/src/lib.rs @@ -1,7 +1,7 @@ //!# Tealr_derive //!The derive macros used by [tealr](https://github.com/lenscas/tealr/tree/master/tealr). //! -//!Tealr is a crate that can generate `.d.tl` files for types that are exposed to `lua`/`teal` through [rlua](https://crates.io/crates/rlua) and [mlua](https://crates.io/crates/rlua) +//!Tealr is a crate that can generate `.d.tl` files for types that are exposed to `lua`/`teal` through [mlua](https://crates.io/crates/mlua) //! //!Read the [README.md](https://github.com/lenscas/tealr/tree/master/README.md) in [tealr](https://github.com/lenscas/tealr/tree/master) for more information. @@ -24,23 +24,14 @@ mod user_data; ))] use embed_compiler::EmbedOptions; use proc_macro::TokenStream; -use venial::parse_declaration; - -#[cfg(feature = "derive")] -#[proc_macro_derive(RluaUserData, attributes(tealr))] -pub fn rlua_user_data_derive(input: TokenStream) -> TokenStream { - use user_data::impl_rlua_user_data_derive; - - let ast = parse_declaration(input.into()).unwrap(); - impl_rlua_user_data_derive(&ast).into() -} +use venial::parse_item; #[cfg(feature = "derive")] #[proc_macro_derive(MluaUserData, attributes(tealr))] pub fn mlua_user_data_derive(input: TokenStream) -> TokenStream { use user_data::impl_mlua_user_data_derive; - let ast = parse_declaration(input.into()).unwrap(); + let ast = parse_item(input.into()).unwrap(); impl_mlua_user_data_derive(&ast).into() } @@ -49,29 +40,18 @@ pub fn mlua_user_data_derive(input: TokenStream) -> TokenStream { pub fn type_representation_derive(input: TokenStream) -> TokenStream { use user_data::impl_type_representation_derive; - let ast = parse_declaration(input.into()).unwrap(); + let ast = parse_item(input.into()).unwrap(); impl_type_representation_derive(&ast).into() } -#[cfg(feature = "derive")] -#[proc_macro_derive(RluaTealDerive, attributes(tealr))] -pub fn rlua_teal_derive(input: TokenStream) -> TokenStream { - use crate::user_data::{impl_rlua_user_data_derive, impl_type_representation_derive}; - - let ast = parse_declaration(input.into()).unwrap(); - let mut stream = impl_type_representation_derive(&ast); - stream.extend(impl_rlua_user_data_derive(&ast)); - stream.into() -} - #[cfg(feature = "derive")] #[proc_macro_derive(MluaTealDerive, attributes(tealr))] pub fn mlua_teal_derive(input: TokenStream) -> TokenStream { use crate::user_data::impl_type_representation_derive; use user_data::impl_mlua_user_data_derive; - let ast = parse_declaration(input.into()).unwrap(); + let ast = parse_item(input.into()).unwrap(); let mut stream = impl_type_representation_derive(&ast); stream.extend(impl_mlua_user_data_derive(&ast)); @@ -156,11 +136,5 @@ pub fn embed_compiler(input: TokenStream) -> TokenStream { #[cfg(feature = "derive")] #[proc_macro_derive(MluaFromToLua, attributes(tealr, lua_doc, tealr_doc))] pub fn mlua_from_to_lua(input: TokenStream) -> TokenStream { - crate::from_to_lua::mlua_from_to_lua(input.into()).into() -} - -#[cfg(feature = "derive")] -#[proc_macro_derive(RluaFromToLua, attributes(tealr, lua_doc, tealr_doc))] -pub fn rlua_from_to_lua(input: TokenStream) -> TokenStream { - crate::from_to_lua::rlua_from_to_lua(input.into()).into() + from_to_lua::mlua_from_to_lua(input.into()).into() } diff --git a/tealr_derive/src/user_data.rs b/tealr_derive/src/user_data.rs index 6512922..d07bd66 100644 --- a/tealr_derive/src/user_data.rs +++ b/tealr_derive/src/user_data.rs @@ -1,9 +1,9 @@ use proc_macro2::{Ident, TokenStream}; -use venial::{Declaration, Error}; +use venial::{Item, Error}; use crate::from_to_lua::get_tealr_name; -pub(crate) fn impl_type_representation_derive(ast: &Declaration) -> proc_macro2::TokenStream { +pub(crate) fn impl_type_representation_derive(ast: &Item) -> TokenStream { let name = ast.name(); let tealr_name = get_tealr_name(ast.attributes()); let gen = quote! { @@ -43,34 +43,11 @@ fn generate_type_body( } } -pub(crate) fn impl_rlua_user_data_derive(ast: &Declaration) -> proc_macro2::TokenStream { +pub(crate) fn impl_mlua_user_data_derive(ast: &Item) -> TokenStream { let tealr_name = get_tealr_name(ast.attributes()); let name = match ast { - Declaration::Struct(x) => &x.name, - Declaration::Enum(x) => &x.name, - _ => { - return Error::new("As of right now, only structs and enums are supported.") - .to_compile_error() - } - }; - let type_body = - generate_type_body(name, quote! {#tealr_name::rlu::TealData}, None, &tealr_name); - quote! { - impl #tealr_name::rlu::rlua::UserData for #name { - fn add_methods<'lua, T: #tealr_name::rlu::rlua::UserDataMethods<'lua, Self>>(methods: &mut T) { - let mut x = #tealr_name::rlu::UserDataWrapper::from_user_data_methods(methods); - ::add_methods(&mut x); - } - } - #type_body - } -} - -pub(crate) fn impl_mlua_user_data_derive(ast: &Declaration) -> proc_macro2::TokenStream { - let tealr_name = get_tealr_name(ast.attributes()); - let name = match ast { - Declaration::Struct(x) => &x.name, - Declaration::Enum(x) => &x.name, + Item::Struct(x) => &x.name, + Item::Enum(x) => &x.name, _ => { return Error::new("As of right now, only structs and enums are supported.") .to_compile_error() @@ -84,11 +61,11 @@ pub(crate) fn impl_mlua_user_data_derive(ast: &Declaration) -> proc_macro2::Toke ); quote! { impl #tealr_name::mlu::mlua::UserData for #name { - fn add_methods<'lua, T: #tealr_name::mlu::mlua::UserDataMethods<'lua, Self>>(methods: &mut T) { + fn add_methods>(methods: &mut T) { let mut x = #tealr_name::mlu::UserDataWrapper::from_user_data_methods(methods); ::add_methods(&mut x); } - fn add_fields<'lua, F: #tealr_name::mlu::mlua::UserDataFields<'lua, Self>>(fields: &mut F) { + fn add_fields>(fields: &mut F) { let mut wrapper = #tealr_name::mlu::UserDataWrapper::from_user_data_fields(fields); ::add_fields(&mut wrapper) } diff --git a/tests/mlua/async.json b/tests/async.json similarity index 100% rename from tests/mlua/async.json rename to tests/async.json diff --git a/tests/mlua/async.rs b/tests/async.rs similarity index 87% rename from tests/mlua/async.rs rename to tests/async.rs index 30e4245..cbd0a2d 100644 --- a/tests/mlua/async.rs +++ b/tests/async.rs @@ -18,23 +18,23 @@ use tealr::{ #[derive(Clone, UserData, ToTypename)] struct Example {} -impl<'lua> FromLua<'lua> for Example { - fn from_lua(value: mlua::prelude::LuaValue<'lua>, _: &'lua Lua) -> Result { +impl FromLua for Example { + fn from_lua(value: mlua::prelude::LuaValue, _: &Lua) -> Result { value .as_userdata() .map(|x| x.take()) .unwrap_or(Err(mlua::Error::FromLuaConversionError { from: value.type_name(), - to: "Example", + to: "Example".to_string(), message: None, })) } } -//now, implement TealData. This tells rlua what methods are available and tealr what the types are +//now, implement TealData. This tells mlua what methods are available and tealr what the types are impl TealData for Example { //implement your methods/functions - fn add_methods<'lua, T: TealDataMethods<'lua, Self>>(methods: &mut T) { + fn add_methods>(methods: &mut T) { methods.add_async_method("example_method", |_, _, x: i8| std::future::ready(Ok(x))); methods.add_async_function("example_method_mut", |_, x: (i8, String)| { std::future::ready(Ok(x.1)) @@ -60,7 +60,7 @@ fn async_fn() -> Result<()> { let generated: serde_json::Value = serde_json::from_str(&file_contents).unwrap(); let mut original: serde_json::Value = - serde_json::from_str(include_str!("./async.json")).unwrap(); + serde_json::from_str(include_str!("async.json")).unwrap(); let x = original .get_mut("tealr_version_used") .expect("missing tealr_version_used in original"); diff --git a/tests/mlua/embed_teal.rs b/tests/embed_teal.rs similarity index 81% rename from tests/mlua/embed_teal.rs rename to tests/embed_teal.rs index 3e6c89c..66a5c99 100644 --- a/tests/mlua/embed_teal.rs +++ b/tests/embed_teal.rs @@ -3,7 +3,7 @@ use tealr::embed_compiler; #[test] fn legacy_syntax() -> mlua::Result<()> { let compiler = embed_compiler!("v0.13.1"); - let code = compiler("tests/mlua/test_embedded_compiler"); + let code = compiler("tests/test_embedded_compiler"); let res: u8 = mlua::Lua::new() .load(&code) .set_name("embedded_compiler_legacy") @@ -14,7 +14,7 @@ fn legacy_syntax() -> mlua::Result<()> { #[test] fn new_syntax_github() -> mlua::Result<()> { let compiler = embed_compiler!(GitHub(version = "v0.13.1")); - let code = compiler("tests/mlua/test_embedded_compiler"); + let code = compiler("tests/test_embedded_compiler"); let res: u8 = mlua::Lua::new() .load(&code) .set_name("embedded_compiler_legacy") @@ -26,7 +26,7 @@ fn new_syntax_github() -> mlua::Result<()> { #[test] fn new_version_luarocks() -> mlua::Result<()> { let compiler = embed_compiler!(Luarocks(version = "v0.13.1")); - let code = compiler("tests/mlua/test_embedded_compiler"); + let code = compiler("tests/test_embedded_compiler"); let res: u8 = mlua::Lua::new() .load(&code) .set_name("embedded_compiler_legacy") @@ -38,7 +38,7 @@ fn new_version_luarocks() -> mlua::Result<()> { fn new_syntax_from_local_discover() -> mlua::Result<()> { let compiler = embed_compiler!(Local()); - let code = compiler("tests/mlua/test_embedded_compiler"); + let code = compiler("tests/test_embedded_compiler"); let res: u8 = mlua::Lua::new() .load(&code) .set_name("embedded_compiler_legacy") diff --git a/tests/mlua/export_instances.json b/tests/export_instances.json similarity index 100% rename from tests/mlua/export_instances.json rename to tests/export_instances.json diff --git a/tests/mlua/export_instances.rs b/tests/export_instances.rs similarity index 85% rename from tests/mlua/export_instances.rs rename to tests/export_instances.rs index 2e48a7b..118bbec 100644 --- a/tests/mlua/export_instances.rs +++ b/tests/export_instances.rs @@ -13,7 +13,7 @@ struct Example {} //now, implement TealData. This tells mlua what methods are available and tealr what the types are impl TealData for Example { //implement your methods/functions - fn add_methods<'lua, T: TealDataMethods<'lua, Self>>(methods: &mut T) { + fn add_methods>(methods: &mut T) { methods.add_method("limited_callback", |lua, _, fun: TypedFunction| { let param = X::from_lua("nice!".into_lua(lua)?, lua)?; let res = fun.call(param)?; @@ -27,7 +27,7 @@ impl TealData for Example { #[derive(Default)] struct Export; impl tealr::mlu::ExportInstances for Export { - fn add_instances<'lua, T: tealr::mlu::InstanceCollector<'lua>>( + fn add_instances( self, instance_collector: &mut T, ) -> mlua::Result<()> { @@ -35,11 +35,11 @@ impl tealr::mlu::ExportInstances for Export { .document_instance("a simple function that does a + 1") .document_instance("it is just for testing purposes") .add_instance("example_a", |context| { - tealr::mlu::TypedFunction::from_rust(|_, a: i32| Ok(a + 1), context) + TypedFunction::from_rust(|_, a: i32| Ok(a + 1), context) })? .document_instance("A simple generic function to make sure generic functions in global context stay working") .add_instance("example_generic", |context| { - tealr::mlu::TypedFunction::from_rust(|_, a: tealr::mlu::generics::X| Ok(a), context) + TypedFunction::from_rust(|_, a: tealr::mlu::generics::X| Ok(a), context) })?; Ok(()) } @@ -56,7 +56,7 @@ fn test_limited() { let generated: serde_json::Value = serde_json::from_str(&file_contents).unwrap(); let mut original: serde_json::Value = - serde_json::from_str(include_str!("./export_instances.json")).unwrap(); + serde_json::from_str(include_str!("export_instances.json")).unwrap(); let mut x = original .get_mut("tealr_version_used") diff --git a/tests/mlua/function_wrapper.rs b/tests/function_wrapper.rs similarity index 93% rename from tests/mlua/function_wrapper.rs rename to tests/function_wrapper.rs index 7d1f9b1..9f0166b 100644 --- a/tests/mlua/function_wrapper.rs +++ b/tests/function_wrapper.rs @@ -24,7 +24,7 @@ fn try_to_use() -> mlua::Result<()> { #[derive(Clone, UserData, ToTypename)] struct Test {} impl TealData for Test { - fn add_methods<'lua, T: TealDataMethods<'lua, Self>>(methods: &mut T) { + fn add_methods>(methods: &mut T) { methods.add_method( "test_function_as_parameter", |_, _, x: TypedFunction<(u8, u8), u8>| x.call((10, 20)), @@ -58,7 +58,7 @@ fn pass_back() -> mlua::Result<()> { #[derive(Clone, UserData, ToTypename)] struct Test {} impl TealData for Test { - fn add_methods<'lua, T: TealDataMethods<'lua, Self>>(methods: &mut T) { + fn add_methods>(methods: &mut T) { methods.add_method( "test_function_as_parameter", |_, _, x: TypedFunction<(u8, u8), u8>| Ok(x), diff --git a/tests/mlua/generics.json b/tests/generics.json similarity index 100% rename from tests/mlua/generics.json rename to tests/generics.json diff --git a/tests/mlua/generics.rs b/tests/generics.rs similarity index 91% rename from tests/mlua/generics.rs rename to tests/generics.rs index 2b18733..c571484 100644 --- a/tests/mlua/generics.rs +++ b/tests/generics.rs @@ -13,7 +13,7 @@ struct Example {} //now, implement TealData. This tells mlua what methods are available and tealr what the types are impl TealData for Example { //implement your methods/functions - fn add_methods<'lua, T: TealDataMethods<'lua, Self>>(methods: &mut T) { + fn add_methods>(methods: &mut T) { methods.add_method( "generic_function_callback", |lua, _, fun: TypedFunction| { @@ -39,7 +39,7 @@ fn make_generic() { let new_value: serde_json::Value = serde_json::from_str(&file_contents).unwrap(); let mut old_value: serde_json::Value = - serde_json::from_str(include_str!("./generics.json")).unwrap(); + serde_json::from_str(include_str!("generics.json")).unwrap(); let mut x = old_value .get_mut("tealr_version_used") .expect("missing tealr_version_used in original"); diff --git a/tests/mlua/inlined_type.json b/tests/inlined_type.json similarity index 100% rename from tests/mlua/inlined_type.json rename to tests/inlined_type.json diff --git a/tests/mlua/inlined_type.rs b/tests/inlined_type.rs similarity index 85% rename from tests/mlua/inlined_type.rs rename to tests/inlined_type.rs index 5711f04..7cd0204 100644 --- a/tests/mlua/inlined_type.rs +++ b/tests/inlined_type.rs @@ -17,26 +17,26 @@ use tealr::{ //The clone is only needed because one of the example functions has it as a parameter #[derive(Clone, UserData, ToTypename)] struct Example {} -impl<'lua> FromLua<'lua> for Example { +impl FromLua for Example { fn from_lua( - value: mlua::prelude::LuaValue<'lua>, - _: &'lua Lua, + value: mlua::prelude::LuaValue, + _: &Lua, ) -> tealr::mlu::mlua::Result { value .as_userdata() .map(|x| x.take()) .unwrap_or(Err(mlua::Error::FromLuaConversionError { from: value.type_name(), - to: "Example", + to: "Example".to_string(), message: None, })) } } -//now, implement TealData. This tells rlua what methods are available and tealr what the types are +//now, implement TealData. This tells mlua what methods are available and tealr what the types are impl TealData for Example { //implement your methods/functions - fn add_methods<'lua, T: TealDataMethods<'lua, Self>>(methods: &mut T) { + fn add_methods>(methods: &mut T) { methods.add_method("example_method", |_, _, x: i8| Ok(x)); methods.add_method_mut("example_method_mut", |_, _, x: (i8, String)| Ok(x.1)); methods.add_function("example_function", |_, x: Vec| Ok((x, 8))); @@ -56,7 +56,7 @@ fn make_inline_type() { let new_value: serde_json::Value = serde_json::from_str(&file_contents).unwrap(); let mut old_value: serde_json::Value = - serde_json::from_str(include_str!("./inlined_type.json")).unwrap(); + serde_json::from_str(include_str!("inlined_type.json")).unwrap(); let mut x = old_value .get_mut("tealr_version_used") .expect("missing tealr_version_used in original"); diff --git a/tests/mlua/meta_methods.json b/tests/meta_methods.json similarity index 100% rename from tests/mlua/meta_methods.json rename to tests/meta_methods.json diff --git a/tests/mlua/meta_methods.rs b/tests/meta_methods.rs similarity index 88% rename from tests/mlua/meta_methods.rs rename to tests/meta_methods.rs index 892c133..62fe10f 100644 --- a/tests/mlua/meta_methods.rs +++ b/tests/meta_methods.rs @@ -12,7 +12,7 @@ struct Example { //now, implement TealData. This tells Mlua what methods are available and tealr what the types are impl TealData for Example { //implement your methods/functions - fn add_methods<'lua, T: TealDataMethods<'lua, Self>>(methods: &mut T) { + fn add_methods>(methods: &mut T) { methods.add_meta_method(MetaMethod::Add, |_, me, other: i8| { Ok(Example { add: me.add + other, @@ -30,7 +30,7 @@ fn test() { let new_value: serde_json::Value = serde_json::from_str(&file_contents).unwrap(); let mut old_value: serde_json::Value = - serde_json::from_str(include_str!("./meta_methods.json")).unwrap(); + serde_json::from_str(include_str!("meta_methods.json")).unwrap(); let mut x = old_value .get_mut("tealr_version_used") .expect("missing tealr_version_used in original"); diff --git a/tests/mlua/named_parameters.json b/tests/named_parameters.json similarity index 100% rename from tests/mlua/named_parameters.json rename to tests/named_parameters.json diff --git a/tests/mlua/named_parameters.rs b/tests/named_parameters.rs similarity index 84% rename from tests/mlua/named_parameters.rs rename to tests/named_parameters.rs index b8b0438..cba9c90 100644 --- a/tests/mlua/named_parameters.rs +++ b/tests/named_parameters.rs @@ -7,21 +7,21 @@ use tealr::{ }; #[derive(Clone, UserData, ToTypename)] struct Example {} -impl<'lua> FromLua<'lua> for Example { - fn from_lua(value: mlua::prelude::LuaValue<'lua>, _: &'lua Lua) -> Result { +impl FromLua for Example { + fn from_lua(value: mlua::prelude::LuaValue, _: &Lua) -> Result { value .as_userdata() .map(|x| x.take()) .unwrap_or(Err(mlua::Error::FromLuaConversionError { from: value.type_name(), - to: "Example", + to: "Example".to_string(), message: None, })) } } impl TealData for Example { - fn add_methods<'lua, T: TealDataMethods<'lua, Self>>(methods: &mut T) { + fn add_methods>(methods: &mut T) { tealr::mlua_create_named_parameters!( TestName with field_1 : String, @@ -42,7 +42,7 @@ fn main() -> Result<()> { let new_value: serde_json::Value = serde_json::from_str(&file_contents).unwrap(); let mut old_value: serde_json::Value = - serde_json::from_str(include_str!("./named_parameters.json")).unwrap(); + serde_json::from_str(include_str!("named_parameters.json")).unwrap(); let mut x = old_value .get_mut("tealr_version_used") diff --git a/tests/mlua/readme_pieces.rs b/tests/readme_pieces.rs similarity index 84% rename from tests/mlua/readme_pieces.rs rename to tests/readme_pieces.rs index cd672c2..745e493 100644 --- a/tests/mlua/readme_pieces.rs +++ b/tests/readme_pieces.rs @@ -13,14 +13,14 @@ fn test() { } #[derive(Clone, UserData, ToTypename)] struct ExampleMlua {} -impl<'lua> FromLua<'lua> for ExampleMlua { - fn from_lua(value: mlua::prelude::LuaValue<'lua>, _: &'lua Lua) -> Result { +impl FromLua for ExampleMlua { + fn from_lua(value: mlua::prelude::LuaValue, _: &Lua) -> Result { value .as_userdata() .map(|x| x.take()) .unwrap_or(Err(mlua::Error::FromLuaConversionError { from: value.type_name(), - to: "Example", + to: "Example".to_string(), message: None, })) } @@ -28,7 +28,7 @@ impl<'lua> FromLua<'lua> for ExampleMlua { impl tealr::mlu::TealData for ExampleMlua { //implement your methods/functions - fn add_methods<'lua, T: tealr::mlu::TealDataMethods<'lua, Self>>(methods: &mut T) { + fn add_methods>(methods: &mut T) { methods.document_type("This is documentation added to the type itself."); methods.document("This documentation gets added to the exposed function bellow."); methods.add_method("example_method", |_, _, x: i8| Ok(x)); @@ -52,26 +52,26 @@ create_generic_mlua!(X); struct Example { example: u32, } -impl<'lua> FromLua<'lua> for Example { - fn from_lua(value: mlua::prelude::LuaValue<'lua>, _: &'lua Lua) -> Result { +impl FromLua for Example { + fn from_lua(value: mlua::prelude::LuaValue, _: &Lua) -> Result { value .as_userdata() .map(|x| x.take()) .unwrap_or(Err(mlua::Error::FromLuaConversionError { from: value.type_name(), - to: "Example", + to: "Example".to_string(), message: None, })) } } impl TealData for Example { - fn add_methods<'lua, T: TealDataMethods<'lua, Self>>(methods: &mut T) { + fn add_methods>(methods: &mut T) { methods.add_method( "generic_function_callback", |_, _, fun: TypedFunction| fun.call("A nice string!".to_string()), ); } - fn add_fields<'lua, F: tealr::mlu::TealDataFields<'lua, Self>>(fields: &mut F) { + fn add_fields>(fields: &mut F) { fields.add_field_method_get("example", |_, this| Ok(this.example)); fields.add_field_method_set("example", |_, this, value| { this.example = value; @@ -96,7 +96,7 @@ fn pieces() -> Result<()> { let compiler = embed_compiler!("v0.13.1"); let code = compiler("example/basic_teal_file"); - let lua = tealr::mlu::mlua::Lua::new(); + let lua = Lua::new(); let _res: u8 = lua.load(&code).set_name("embedded_compiler").eval()?; let add_1 = TypedFunction::::from_rust(|_lua, x| Ok(x + 1), &lua)?; assert_eq!(add_1.call(2)?, 3); diff --git a/tests/rlua/embed_teal.rs b/tests/rlua/embed_teal.rs deleted file mode 100644 index 62ea092..0000000 --- a/tests/rlua/embed_teal.rs +++ /dev/null @@ -1,59 +0,0 @@ -use tealr::embed_compiler; - -#[test] -fn legacy_syntax() -> rlua::Result<()> { - let compiler = embed_compiler!("v0.13.1"); - let res = rlua::Lua::new().context(|ctx| { - let code = compiler("tests/rlua/test_embedded_compiler"); - let res: u8 = ctx - .load(&code) - .set_name("embedded_compiler_legacy")? - .eval()?; - Ok(res) - })?; - assert_eq!(res, 5); - Ok(()) -} -#[test] -fn new_syntax_github() -> rlua::Result<()> { - let compiler = embed_compiler!(GitHub(version = "v0.13.1")); - let res = rlua::Lua::new().context(|ctx| { - let code = compiler("tests/rlua/test_embedded_compiler"); - let res: u8 = ctx - .load(&code) - .set_name("embedded_compiler_legacy")? - .eval()?; - Ok(res) - })?; - assert_eq!(res, 5); - Ok(()) -} - -#[test] -fn new_version_luarocks() -> rlua::Result<()> { - let compiler = embed_compiler!(Luarocks(version = "v0.13.1")); - let res = rlua::Lua::new().context(|ctx| { - let code = compiler("tests/rlua/test_embedded_compiler"); - let res: u8 = ctx - .load(&code) - .set_name("embedded_compiler_legacy")? - .eval()?; - Ok(res) - })?; - assert_eq!(res, 5); - Ok(()) -} -#[test] -fn new_syntax_from_local_discover() -> rlua::Result<()> { - let compiler = embed_compiler!(Local()); - let res = rlua::Lua::new().context(|ctx| { - let code = compiler("tests/rlua/test_embedded_compiler"); - let res: u8 = ctx - .load(&code) - .set_name("embedded_compiler_legacy")? - .eval()?; - Ok(res) - })?; - assert_eq!(res, 5); - Ok(()) -} diff --git a/tests/rlua/export_instance.json b/tests/rlua/export_instance.json deleted file mode 100644 index 4a038a1..0000000 --- a/tests/rlua/export_instance.json +++ /dev/null @@ -1 +0,0 @@ -{"tealr_version_used":"0.9.0-alpha4","given_types":[{"Record":{"should_be_inlined":false,"is_user_data":true,"type_name":[{"Type":{"name":"Example","type_kind":"External","generics":null}}],"fields":[],"static_fields":[],"methods":[{"name":"limited_callback","signature":[{"Symbol":"function"},{"Symbol":"("},{"Symbol":"self"},{"Symbol":":"},{"Type":{"name":"Example","type_kind":"External","generics":null}},{"Symbol":" , "},{"Symbol":"function"},{"Symbol":"("},{"Symbol":"("},{"Type":{"name":"string","type_kind":"Builtin","generics":null}},{"Symbol":" | "},{"Type":{"name":"number","type_kind":"Builtin","generics":null}},{"Symbol":" | "},{"Type":{"name":"boolean","type_kind":"Builtin","generics":null}},{"Symbol":")"},{"Symbol":")"},{"Symbol":":("},{"Symbol":"("},{"Type":{"name":"string","type_kind":"Builtin","generics":null}},{"Symbol":" | "},{"Type":{"name":"number","type_kind":"Builtin","generics":null}},{"Symbol":" | "},{"Type":{"name":"boolean","type_kind":"Builtin","generics":null}},{"Symbol":")"},{"Symbol":")"},{"Symbol":")"},{"Symbol":":("},{"Symbol":"("},{"Type":{"name":"string","type_kind":"Builtin","generics":null}},{"Symbol":" | "},{"Type":{"name":"number","type_kind":"Builtin","generics":null}},{"Symbol":" | "},{"Type":{"name":"boolean","type_kind":"Builtin","generics":null}},{"Symbol":")"},{"Symbol":")"}],"params":[{"param_name":"self","ty":{"Single":{"name":"Example","kind":"External"}}},{"param_name":null,"ty":{"Function":{"params":[{"param_name":null,"ty":{"Or":[{"Single":{"name":"string","kind":"Builtin"}},{"Single":{"name":"number","kind":"Builtin"}},{"Single":{"name":"boolean","kind":"Builtin"}}]}}],"returns":[{"Or":[{"Single":{"name":"string","kind":"Builtin"}},{"Single":{"name":"number","kind":"Builtin"}},{"Single":{"name":"boolean","kind":"Builtin"}}]}]}}}],"returns":[{"Or":[{"Single":{"name":"string","kind":"Builtin"}},{"Single":{"name":"number","kind":"Builtin"}},{"Single":{"name":"boolean","kind":"Builtin"}}]}],"is_meta_method":false},{"name":"limited_array","signature":[{"Symbol":"function"},{"Symbol":"("},{"Symbol":"self"},{"Symbol":":"},{"Type":{"name":"Example","type_kind":"External","generics":null}},{"Symbol":" , "},{"Symbol":"{"},{"Symbol":"("},{"Type":{"name":"string","type_kind":"Builtin","generics":null}},{"Symbol":" | "},{"Type":{"name":"number","type_kind":"Builtin","generics":null}},{"Symbol":" | "},{"Type":{"name":"boolean","type_kind":"Builtin","generics":null}},{"Symbol":")"},{"Symbol":"}"},{"Symbol":")"},{"Symbol":":("},{"Symbol":"{"},{"Symbol":"("},{"Type":{"name":"string","type_kind":"Builtin","generics":null}},{"Symbol":" | "},{"Type":{"name":"number","type_kind":"Builtin","generics":null}},{"Symbol":" | "},{"Type":{"name":"boolean","type_kind":"Builtin","generics":null}},{"Symbol":")"},{"Symbol":"}"},{"Symbol":")"}],"params":[{"param_name":"self","ty":{"Single":{"name":"Example","kind":"External"}}},{"param_name":null,"ty":{"Array":{"Or":[{"Single":{"name":"string","kind":"Builtin"}},{"Single":{"name":"number","kind":"Builtin"}},{"Single":{"name":"boolean","kind":"Builtin"}}]}}}],"returns":[{"Array":{"Or":[{"Single":{"name":"string","kind":"Builtin"}},{"Single":{"name":"number","kind":"Builtin"}},{"Single":{"name":"boolean","kind":"Builtin"}}]}}],"is_meta_method":false},{"name":"limited_simple","signature":[{"Symbol":"function"},{"Symbol":"("},{"Symbol":"self"},{"Symbol":":"},{"Type":{"name":"Example","type_kind":"External","generics":null}},{"Symbol":" , "},{"Symbol":"("},{"Type":{"name":"string","type_kind":"Builtin","generics":null}},{"Symbol":" | "},{"Type":{"name":"number","type_kind":"Builtin","generics":null}},{"Symbol":" | "},{"Type":{"name":"boolean","type_kind":"Builtin","generics":null}},{"Symbol":")"},{"Symbol":")"},{"Symbol":":("},{"Symbol":"("},{"Type":{"name":"string","type_kind":"Builtin","generics":null}},{"Symbol":" | "},{"Type":{"name":"number","type_kind":"Builtin","generics":null}},{"Symbol":" | "},{"Type":{"name":"boolean","type_kind":"Builtin","generics":null}},{"Symbol":")"},{"Symbol":")"}],"params":[{"param_name":"self","ty":{"Single":{"name":"Example","kind":"External"}}},{"param_name":null,"ty":{"Or":[{"Single":{"name":"string","kind":"Builtin"}},{"Single":{"name":"number","kind":"Builtin"}},{"Single":{"name":"boolean","kind":"Builtin"}}]}}],"returns":[{"Or":[{"Single":{"name":"string","kind":"Builtin"}},{"Single":{"name":"number","kind":"Builtin"}},{"Single":{"name":"boolean","kind":"Builtin"}}]}],"is_meta_method":false}],"mut_methods":[],"functions":[],"mut_functions":[],"meta_method":[],"meta_method_mut":[],"meta_function":[],"meta_function_mut":[],"documentation":{},"type_doc":"","next_docs":null,"should_generate_help_method":true}}],"global_instances_off":[{"name":"test","teal_type":[{"Type":{"name":"Example","type_kind":"External","generics":null}}],"ty":{"Single":{"name":"Example","kind":"External"}},"is_external":true,"doc":""},{"name":"example_a","teal_type":[{"Symbol":"function"},{"Symbol":"("},{"Type":{"name":"integer","type_kind":"Builtin","generics":null}},{"Symbol":")"},{"Symbol":":("},{"Type":{"name":"integer","type_kind":"Builtin","generics":null}},{"Symbol":")"}],"ty":{"Function":{"params":[{"param_name":null,"ty":{"Single":{"name":"integer","kind":"Builtin"}}}],"returns":[{"Single":{"name":"integer","kind":"Builtin"}}]}},"is_external":true,"doc":"a simple function that does a + 1\nit is just for testing purposes\n"},{"name":"example_generic","teal_type":[{"Symbol":"function"},{"Symbol":"<"},{"Type":{"name":"X","type_kind":"Generic","generics":null}},{"Symbol":">"},{"Symbol":"("},{"Type":{"name":"X","type_kind":"Generic","generics":null}},{"Symbol":")"},{"Symbol":":("},{"Type":{"name":"X","type_kind":"Generic","generics":null}},{"Symbol":")"}],"ty":{"Function":{"params":[{"param_name":null,"ty":{"Single":{"name":"X","kind":"Generic"}}}],"returns":[{"Single":{"name":"X","kind":"Generic"}}]}},"is_external":true,"doc":""}],"extra_page":[]} \ No newline at end of file diff --git a/tests/rlua/export_instances.rs b/tests/rlua/export_instances.rs deleted file mode 100644 index e8bda2c..0000000 --- a/tests/rlua/export_instances.rs +++ /dev/null @@ -1,77 +0,0 @@ -use rlua::ToLua; -use tealr::{ - create_union_rlua, - rlu::{rlua::FromLua, TealData, TealDataMethods, TypedFunction, UserData}, - ToTypename, TypeWalker, -}; -create_union_rlua!(enum X = String | f32 | bool); - -#[derive(Clone, UserData, ToTypename)] -struct Example {} - -//now, implement TealData. This tells mlua what methods are available and tealr what the types are -impl TealData for Example { - //implement your methods/functions - fn add_methods<'lua, T: TealDataMethods<'lua, Self>>(methods: &mut T) { - methods.add_method("limited_callback", |lua, _, fun: TypedFunction| { - let param = X::from_lua("nice!".to_lua(lua)?, lua)?; - let res = fun.call(param)?; - Ok(res) - }); - methods.add_method("limited_array", |_, _, x: Vec| Ok(x)); - methods.add_method("limited_simple", |_, _, x: X| Ok(x)); - } -} - -#[derive(Default)] -struct Export; -impl tealr::rlu::ExportInstances for Export { - fn add_instances<'lua, T: tealr::rlu::InstanceCollector<'lua>>( - self, - instance_collector: &mut T, - ) -> rlua::Result<()> { - instance_collector - .add_instance("test", |_| Ok(Example {}))? - .document_instance("a simple function that does a + 1") - .document_instance("it is just for testing purposes") - .add_instance("example_a", |context| { - tealr::rlu::TypedFunction::from_rust(|_, a: i32| Ok(a + 1), context) - })? - .add_instance("example_generic", |context| { - tealr::rlu::TypedFunction::from_rust(|_, a: tealr::rlu::generics::X| Ok(a), context) - })?; - Ok(()) - } -} - -#[test] -fn test_limited() { - let file_contents = TypeWalker::new() - .process_type::() - .document_global_instance::() - .unwrap() - .to_json() - .expect("oh no :("); - let generated: serde_json::Value = serde_json::from_str(&file_contents).unwrap(); - let mut original: serde_json::Value = - serde_json::from_str(include_str!("./export_instance.json")).unwrap(); - let x = original - .get_mut("tealr_version_used") - .expect("missing tealr_version_used in original"); - if let serde_json::Value::String(x) = x { - *x = tealr::get_tealr_version().to_string(); - } - assert_eq!(generated, original); - let res: bool = rlua::Lua::new() - .context(|ctx| { - tealr::rlu::set_global_env(Export {}, ctx)?; - - let code = " - assert(example_a(2) == 3) - return test:limited_simple(true) - "; - ctx.load(code).eval() - }) - .unwrap(); - assert!(res); -} diff --git a/tests/rlua/function_wrapper.rs b/tests/rlua/function_wrapper.rs deleted file mode 100644 index ce47db6..0000000 --- a/tests/rlua/function_wrapper.rs +++ /dev/null @@ -1,90 +0,0 @@ -use tealr::{ - rlu::{TealData, TealDataMethods, TypedFunction, UserData}, - type_parts_to_str, ToTypename, -}; -#[test] -fn generate_correct_type() { - assert_eq!( - type_parts_to_str( - #[allow(deprecated)] - TypedFunction::::to_old_type_parts() - ), - "function(string):(string)" - ); - assert_eq!( - type_parts_to_str( - #[allow(deprecated)] - TypedFunction::, f32>::to_old_type_parts() - ), - "function(function(integer , string):(string , integer)):(number)" - ); -} -#[test] -fn try_to_use() -> rlua::Result<()> { - #[derive(Clone, UserData, ToTypename)] - struct Test {} - impl TealData for Test { - fn add_methods<'lua, T: TealDataMethods<'lua, Self>>(methods: &mut T) { - methods.add_method( - "test_function_as_parameter", - |_, _, x: TypedFunction<(u8, u8), u8>| x.call((10, 20)), - ); - } - } - let code = tealr::compile_inline_teal!( - " -global record Test - test_function_as_parameter:function(Test,function(integer,integer):integer):integer -end - -global test: Test - -global function add(a:integer,b:integer):integer - return a + b -end -return test:test_function_as_parameter(add) -" - ); - let res: u8 = rlua::Lua::new().context(|ctx| { - let globals = ctx.globals(); - globals.set("test", Test {})?; - ctx.load(code).eval() - })?; - assert_eq!(res, 30); - Ok(()) -} - -#[test] -fn pass_back() -> rlua::Result<()> { - #[derive(Clone, UserData, ToTypename)] - struct Test {} - impl TealData for Test { - fn add_methods<'lua, T: TealDataMethods<'lua, Self>>(methods: &mut T) { - methods.add_method( - "test_function_as_parameter", - |_, _, x: TypedFunction<(u8, u8), u8>| Ok(x), - ); - } - } - let code = tealr::compile_inline_teal!( - " -global record Test - test_function_as_parameter:function(Test,function(integer,integer):integer):(function(integer,integer):integer) -end - -global test: Test - -local function add(a:integer,b:integer):integer - return a + b -end -return test:test_function_as_parameter(add)(10,20) -" - ); - let res: u8 = rlua::Lua::new().context(|ctx| { - let globals = ctx.globals(); - globals.set("test", Test {})?; - ctx.load(code).eval() - })?; - assert_eq!(res, 30); - Ok(()) -} diff --git a/tests/rlua/generics.json b/tests/rlua/generics.json deleted file mode 100644 index 17df73b..0000000 --- a/tests/rlua/generics.json +++ /dev/null @@ -1,623 +0,0 @@ -{ - "tealr_version_used": "0.9.0-alpha4", - "given_types": [ - { - "Record": { - "should_be_inlined": false, - "is_user_data": true, - "type_name": [ - { - "Type": { - "name": "Example", - "type_kind": "External", - "generics": null - } - } - ], - "fields": [], - "static_fields": [], - "methods": [ - { - "name": "generic_function_callback", - "signature": [ - { - "Symbol": "function" - }, - { - "Symbol": "<" - }, - { - "Type": { - "name": "X", - "type_kind": "Generic", - "generics": null - } - }, - { - "Symbol": ">" - }, - { - "Symbol": "(" - }, - { - "Symbol": "self" - }, - { - "Symbol": ":" - }, - { - "Type": { - "name": "Example", - "type_kind": "External", - "generics": null - } - }, - { - "Symbol": " , " - }, - { - "Symbol": "function" - }, - { - "Symbol": "(" - }, - { - "Type": { - "name": "X", - "type_kind": "Generic", - "generics": null - } - }, - { - "Symbol": ")" - }, - { - "Symbol": ":(" - }, - { - "Type": { - "name": "X", - "type_kind": "Generic", - "generics": null - } - }, - { - "Symbol": ")" - }, - { - "Symbol": ")" - }, - { - "Symbol": ":(" - }, - { - "Type": { - "name": "X", - "type_kind": "Generic", - "generics": null - } - }, - { - "Symbol": ")" - } - ], - "params": [ - { - "param_name": "self", - "ty": { - "Single": { - "name": "Example", - "kind": "External" - } - } - }, - { - "param_name": null, - "ty": { - "Function": { - "params": [ - { - "param_name": null, - "ty": { - "Single": { - "name": "X", - "kind": "Generic" - } - } - } - ], - "returns": [ - { - "Single": { - "name": "X", - "kind": "Generic" - } - } - ] - } - } - } - ], - "returns": [ - { - "Single": { - "name": "X", - "kind": "Generic" - } - } - ], - "is_meta_method": false - }, - { - "name": "generic_array", - "signature": [ - { - "Symbol": "function" - }, - { - "Symbol": "<" - }, - { - "Type": { - "name": "X", - "type_kind": "Generic", - "generics": null - } - }, - { - "Symbol": ">" - }, - { - "Symbol": "(" - }, - { - "Symbol": "self" - }, - { - "Symbol": ":" - }, - { - "Type": { - "name": "Example", - "type_kind": "External", - "generics": null - } - }, - { - "Symbol": " , " - }, - { - "Symbol": "{" - }, - { - "Type": { - "name": "X", - "type_kind": "Generic", - "generics": null - } - }, - { - "Symbol": "}" - }, - { - "Symbol": ")" - }, - { - "Symbol": ":(" - }, - { - "Symbol": "{" - }, - { - "Type": { - "name": "X", - "type_kind": "Generic", - "generics": null - } - }, - { - "Symbol": "}" - }, - { - "Symbol": ")" - } - ], - "params": [ - { - "param_name": "self", - "ty": { - "Single": { - "name": "Example", - "kind": "External" - } - } - }, - { - "param_name": null, - "ty": { - "Array": { - "Single": { - "name": "X", - "kind": "Generic" - } - } - } - } - ], - "returns": [ - { - "Array": { - "Single": { - "name": "X", - "kind": "Generic" - } - } - } - ], - "is_meta_method": false - }, - { - "name": "generic_hashmap", - "signature": [ - { - "Symbol": "function" - }, - { - "Symbol": "<" - }, - { - "Type": { - "name": "X", - "type_kind": "Generic", - "generics": null - } - }, - { - "Symbol": ">" - }, - { - "Symbol": "(" - }, - { - "Symbol": "self" - }, - { - "Symbol": ":" - }, - { - "Type": { - "name": "Example", - "type_kind": "External", - "generics": null - } - }, - { - "Symbol": " , " - }, - { - "Symbol": "{" - }, - { - "Type": { - "name": "string", - "type_kind": "Builtin", - "generics": null - } - }, - { - "Symbol": " : " - }, - { - "Type": { - "name": "X", - "type_kind": "Generic", - "generics": null - } - }, - { - "Symbol": "}" - }, - { - "Symbol": ")" - }, - { - "Symbol": ":(" - }, - { - "Symbol": "{" - }, - { - "Type": { - "name": "string", - "type_kind": "Builtin", - "generics": null - } - }, - { - "Symbol": " : " - }, - { - "Type": { - "name": "X", - "type_kind": "Generic", - "generics": null - } - }, - { - "Symbol": "}" - }, - { - "Symbol": " , " - }, - { - "Type": { - "name": "integer", - "type_kind": "Builtin", - "generics": null - } - }, - { - "Symbol": ")" - } - ], - "params": [ - { - "param_name": "self", - "ty": { - "Single": { - "name": "Example", - "kind": "External" - } - } - }, - { - "param_name": null, - "ty": { - "Map": { - "key": { - "Single": { - "name": "string", - "kind": "Builtin" - } - }, - "value": { - "Single": { - "name": "X", - "kind": "Generic" - } - } - } - } - } - ], - "returns": [ - { - "Map": { - "key": { - "Single": { - "name": "string", - "kind": "Builtin" - } - }, - "value": { - "Single": { - "name": "X", - "kind": "Generic" - } - } - } - }, - { - "Single": { - "name": "integer", - "kind": "Builtin" - } - } - ], - "is_meta_method": false - }, - { - "name": "just_generics", - "signature": [ - { - "Symbol": "function" - }, - { - "Symbol": "<" - }, - { - "Type": { - "name": "X", - "type_kind": "Generic", - "generics": null - } - }, - { - "Symbol": ">" - }, - { - "Symbol": "(" - }, - { - "Symbol": "self" - }, - { - "Symbol": ":" - }, - { - "Type": { - "name": "Example", - "type_kind": "External", - "generics": null - } - }, - { - "Symbol": " , " - }, - { - "Type": { - "name": "X", - "type_kind": "Generic", - "generics": null - } - }, - { - "Symbol": ")" - }, - { - "Symbol": ":(" - }, - { - "Type": { - "name": "X", - "type_kind": "Generic", - "generics": null - } - }, - { - "Symbol": ")" - } - ], - "params": [ - { - "param_name": "self", - "ty": { - "Single": { - "name": "Example", - "kind": "External" - } - } - }, - { - "param_name": null, - "ty": { - "Single": { - "name": "X", - "kind": "Generic" - } - } - } - ], - "returns": [ - { - "Single": { - "name": "X", - "kind": "Generic" - } - } - ], - "is_meta_method": false - }, - { - "name": "non_generic_container", - "signature": [ - { - "Symbol": "function" - }, - { - "Symbol": "(" - }, - { - "Symbol": "self" - }, - { - "Symbol": ":" - }, - { - "Type": { - "name": "Example", - "type_kind": "External", - "generics": null - } - }, - { - "Symbol": " , " - }, - { - "Symbol": "{" - }, - { - "Type": { - "name": "string", - "type_kind": "Builtin", - "generics": null - } - }, - { - "Symbol": "}" - }, - { - "Symbol": ")" - }, - { - "Symbol": ":(" - }, - { - "Symbol": "{" - }, - { - "Type": { - "name": "string", - "type_kind": "Builtin", - "generics": null - } - }, - { - "Symbol": "}" - }, - { - "Symbol": ")" - } - ], - "params": [ - { - "param_name": "self", - "ty": { - "Single": { - "name": "Example", - "kind": "External" - } - } - }, - { - "param_name": null, - "ty": { - "Array": { - "Single": { - "name": "string", - "kind": "Builtin" - } - } - } - } - ], - "returns": [ - { - "Array": { - "Single": { - "name": "string", - "kind": "Builtin" - } - } - } - ], - "is_meta_method": false - } - ], - "mut_methods": [], - "functions": [], - "mut_functions": [], - "meta_method": [], - "meta_method_mut": [], - "meta_function": [], - "meta_function_mut": [], - "documentation": {}, - "type_doc": "", - "next_docs": null, - "should_generate_help_method": true - } - } - ], - "global_instances_off": [], - "extra_page": [] -} \ No newline at end of file diff --git a/tests/rlua/generics.rs b/tests/rlua/generics.rs deleted file mode 100644 index f2afb60..0000000 --- a/tests/rlua/generics.rs +++ /dev/null @@ -1,46 +0,0 @@ -use std::collections::HashMap; - -use tealr::{ - rlu::{generics::X, rlua::ToLua, TealData, TealDataMethods, TypedFunction, UserData}, - ToTypename, TypeWalker, -}; - -#[derive(Clone, UserData, ToTypename)] -struct Example {} - -//now, implement TealData. This tells mlua what methods are available and tealr what the types are -impl TealData for Example { - //implement your methods/functions - fn add_methods<'lua, T: TealDataMethods<'lua, Self>>(methods: &mut T) { - methods.add_method( - "generic_function_callback", - |lua, _, fun: TypedFunction| { - let param = X::from("nice!".to_lua(lua)?); - let res = fun.call(param)?; - Ok(res) - }, - ); - methods.add_method("generic_array", |_, _, x: Vec| Ok(x)); - methods.add_method("generic_hashmap", |_, _, x: HashMap| Ok((x, 8))); - methods.add_method("just_generics", |_, _, x: X| Ok(x)); - methods.add_method("non_generic_container", |_, _, x: Vec| Ok(x)) - } -} - -#[test] -fn make_generic() { - let file_contents = TypeWalker::new() - .process_type::() - .to_json_pretty() - .unwrap(); - let new_value: serde_json::Value = serde_json::from_str(&file_contents).unwrap(); - let mut old_value: serde_json::Value = - serde_json::from_str(include_str!("./generics.json")).unwrap(); - let mut x = old_value - .get_mut("tealr_version_used") - .expect("missing tealr_version_used in original"); - if let serde_json::Value::String(x) = &mut x { - *x = tealr::get_tealr_version().to_string(); - } - assert_eq!(new_value, old_value); -} diff --git a/tests/rlua/meta_methods.json b/tests/rlua/meta_methods.json deleted file mode 100644 index 00bb814..0000000 --- a/tests/rlua/meta_methods.json +++ /dev/null @@ -1,116 +0,0 @@ -{ - "tealr_version_used": "0.9.0-alpha4", - "given_types": [ - { - "Record": { - "should_be_inlined": false, - "is_user_data": true, - "type_name": [ - { - "Type": { - "name": "Example", - "type_kind": "External", - "generics": null - } - } - ], - "fields": [], - "static_fields": [], - "methods": [], - "mut_methods": [], - "functions": [], - "mut_functions": [], - "meta_method": [ - { - "name": "__add", - "signature": [ - { - "Symbol": "function" - }, - { - "Symbol": "(" - }, - { - "Symbol": "self" - }, - { - "Symbol": ":" - }, - { - "Type": { - "name": "Example", - "type_kind": "External", - "generics": null - } - }, - { - "Symbol": " , " - }, - { - "Type": { - "name": "integer", - "type_kind": "Builtin", - "generics": null - } - }, - { - "Symbol": ")" - }, - { - "Symbol": ":(" - }, - { - "Type": { - "name": "Example", - "type_kind": "External", - "generics": null - } - }, - { - "Symbol": ")" - } - ], - "params": [ - { - "param_name": "self", - "ty": { - "Single": { - "name": "Example", - "kind": "External" - } - } - }, - { - "param_name": null, - "ty": { - "Single": { - "name": "integer", - "kind": "Builtin" - } - } - } - ], - "returns": [ - { - "Single": { - "name": "Example", - "kind": "External" - } - } - ], - "is_meta_method": false - } - ], - "meta_method_mut": [], - "meta_function": [], - "meta_function_mut": [], - "documentation": {}, - "type_doc": "", - "next_docs": null, - "should_generate_help_method": true - } - } - ], - "global_instances_off": [], - "extra_page": [] -} \ No newline at end of file diff --git a/tests/rlua/meta_methods.rs b/tests/rlua/meta_methods.rs deleted file mode 100644 index b35372b..0000000 --- a/tests/rlua/meta_methods.rs +++ /dev/null @@ -1,39 +0,0 @@ -use tealr::{ - rlu::{rlua::MetaMethod, TealData, TealDataMethods, UserData}, - ToTypename, TypeWalker, -}; - -#[derive(Clone, UserData, ToTypename)] -struct Example { - add: i8, -} - -//now, implement TealData. This tells rlua what methods are available and tealr what the types are -impl TealData for Example { - //implement your methods/functions - fn add_methods<'lua, T: TealDataMethods<'lua, Self>>(methods: &mut T) { - methods.add_meta_method(MetaMethod::Add, |_, me, other: i8| { - Ok(Example { - add: me.add + other, - }) - }) - } -} -#[test] -fn test() { - //create .d.tl file and compare against expected - let file_contents = TypeWalker::new() - .process_type::() - .to_json_pretty() - .unwrap(); - let new_value: serde_json::Value = serde_json::from_str(&file_contents).unwrap(); - let mut old_value: serde_json::Value = - serde_json::from_str(include_str!("./meta_methods.json")).unwrap(); - let mut x = old_value - .get_mut("tealr_version_used") - .expect("missing tealr_version_used in original"); - if let serde_json::Value::String(x) = &mut x { - *x = tealr::get_tealr_version().to_string(); - } - assert_eq!(new_value, old_value); -} diff --git a/tests/rlua/named_parameters.json b/tests/rlua/named_parameters.json deleted file mode 100644 index 7f2b948..0000000 --- a/tests/rlua/named_parameters.json +++ /dev/null @@ -1,163 +0,0 @@ -{ - "tealr_version_used": "0.9.0-alpha4", - "given_types": [ - { - "Record": { - "should_be_inlined": false, - "is_user_data": true, - "type_name": [ - { - "Type": { - "name": "Example", - "type_kind": "External", - "generics": null - } - } - ], - "fields": [], - "static_fields": [], - "methods": [ - { - "name": "example_method", - "signature": [ - { - "Symbol": "function" - }, - { - "Symbol": "(" - }, - { - "Symbol": "self" - }, - { - "Symbol": ":" - }, - { - "Type": { - "name": "Example", - "type_kind": "External", - "generics": null - } - }, - { - "Symbol": " , " - }, - { - "Symbol": "field_1" - }, - { - "Symbol": ":" - }, - { - "Type": { - "name": "string", - "type_kind": "Builtin", - "generics": null - } - }, - { - "Symbol": " , " - }, - { - "Symbol": "field_2" - }, - { - "Symbol": ":" - }, - { - "Type": { - "name": "integer", - "type_kind": "Builtin", - "generics": null - } - }, - { - "Symbol": ")" - }, - { - "Symbol": ":(" - }, - { - "Type": { - "name": "string", - "type_kind": "Builtin", - "generics": null - } - }, - { - "Symbol": " , " - }, - { - "Type": { - "name": "integer", - "type_kind": "Builtin", - "generics": null - } - }, - { - "Symbol": ")" - } - ], - "params": [ - { - "param_name": "self", - "ty": { - "Single": { - "name": "Example", - "kind": "External" - } - } - }, - { - "param_name": "field_1", - "ty": { - "Single": { - "name": "string", - "kind": "Builtin" - } - } - }, - { - "param_name": "field_2", - "ty": { - "Single": { - "name": "integer", - "kind": "Builtin" - } - } - } - ], - "returns": [ - { - "Single": { - "name": "string", - "kind": "Builtin" - } - }, - { - "Single": { - "name": "integer", - "kind": "Builtin" - } - } - ], - "is_meta_method": false - } - ], - "mut_methods": [], - "functions": [], - "mut_functions": [], - "meta_method": [], - "meta_method_mut": [], - "meta_function": [], - "meta_function_mut": [], - "documentation": {}, - "type_doc": "", - "next_docs": null, - "should_generate_help_method": true - } - } - ], - "global_instances_off": [], - "extra_page": [] -} \ No newline at end of file diff --git a/tests/rlua/named_parameters.rs b/tests/rlua/named_parameters.rs deleted file mode 100644 index 16a37a5..0000000 --- a/tests/rlua/named_parameters.rs +++ /dev/null @@ -1,49 +0,0 @@ -use tealr::{ - rlu::{rlua::Result, TealData, TealDataMethods, UserData}, - ToTypename, TypeWalker, -}; -#[derive(Clone, UserData, ToTypename)] -struct Example {} - -impl TealData for Example { - fn add_methods<'lua, T: TealDataMethods<'lua, Self>>(methods: &mut T) { - tealr::rlu::create_named_parameters!( - TestName with - field_1 : String, - field_2 : i64, - ); - methods.add_method("example_method", |_, _, a: TestName| { - Ok((a.field_1, a.field_2)) - }); - } -} - -#[test] -fn main() -> Result<()> { - let file_contents = TypeWalker::new() - .process_type::() - .to_json_pretty() - .unwrap(); - - let new_value: serde_json::Value = serde_json::from_str(&file_contents).unwrap(); - let mut old_value: serde_json::Value = - serde_json::from_str(include_str!("./named_parameters.json")).unwrap(); - let mut x = old_value - .get_mut("tealr_version_used") - .expect("missing tealr_version_used in original"); - if let serde_json::Value::String(x) = &mut x { - *x = tealr::get_tealr_version().to_string(); - } - assert_eq!(new_value, old_value); - - tealr::rlu::rlua::Lua::new().context(|ctx| { - let globals = ctx.globals(); - globals.set("test", Example {})?; - let code = "return test:example_method(\"field_1 is a string\", 3)"; - let (field1, field2): (String, i64) = ctx.load(code).set_name("test?")?.eval()?; - assert_eq!(field1, "field_1 is a string"); - assert_eq!(field2, 3); - Ok(()) - })?; - Ok(()) -} diff --git a/tests/rlua/readme_pieces.rs b/tests/rlua/readme_pieces.rs deleted file mode 100644 index 9cbd39c..0000000 --- a/tests/rlua/readme_pieces.rs +++ /dev/null @@ -1,55 +0,0 @@ -use tealr::{compile_inline_teal, create_union_rlua, embed_compiler, ToTypename, TypeWalker}; - -#[test] -fn test() { - pieces().unwrap(); -} - -#[derive(Clone, tealr::rlu::UserData, ToTypename)] -struct ExampleRlua {} - -//now, implement rlu::TealData. -//This tells rlua what methods are available and tealr what the types are -impl tealr::rlu::TealData for ExampleRlua { - //implement your methods/functions - fn add_methods<'lua, T: tealr::rlu::TealDataMethods<'lua, Self>>(methods: &mut T) { - methods.document_type("This is documentation added to the type itself."); - - methods.document("This documentation gets added to the exposed function bellow."); - methods.add_method("example_method", |_, _, x: i8| Ok(x)); - methods.add_method_mut("example_method_mut", |_, _, x: (i8, String)| Ok(x.1)); - methods.add_function("example_function", |_, x: Vec| Ok((x, 8))); - methods.document("***You*** can also embed markdown to the documentation, which gets picked up by [tealr_doc_gen](https://github.com/lenscas/type_generator)`"); - methods.document("It is also possible to use this function multiple times. These are added as paragraphs."); - methods.add_function_mut( - "example_function_mut", - |_, x: (bool, Option)| Ok(x), - ); - //This creates the instance.help() function, which returns the documentation as a string. - methods.generate_help() - } -} -create_union_rlua!(enum YourTypeName = i32 | String); - -fn pieces() -> Result<(), rlua::Error> { - //the functionality of these pieces of code are already being tested at other places - //This is just to make sure the examples in the readme keep working - if false { - //create the json file - let _file_contents = TypeWalker::new() - .process_type::() - .to_json() - .expect("oh no :("); - - //compile inline teal - let _code = compile_inline_teal!("local x : number = 5 return x"); - //embed teal - let compiler = embed_compiler!("v0.13.1"); - let _res: u8 = tealr::rlu::rlua::Lua::new().context(|ctx| { - let code = compiler("example/basic_teal_file"); - ctx.load(&code).set_name("embedded_compiler")?.eval() - })?; - } - - Ok(()) -} diff --git a/tests/rlua/test_embedded_compiler.tl b/tests/rlua/test_embedded_compiler.tl deleted file mode 100644 index b49b493..0000000 --- a/tests/rlua/test_embedded_compiler.tl +++ /dev/null @@ -1,3 +0,0 @@ -local type Y = number -local x : Y = 5 -return x diff --git a/tests/rlua/to_from_derived.json b/tests/rlua/to_from_derived.json deleted file mode 100644 index 6188a13..0000000 --- a/tests/rlua/to_from_derived.json +++ /dev/null @@ -1,1093 +0,0 @@ -{ - "tealr_version_used": "0.9.0-alpha4", - "given_types": [ - { - "Record": { - "should_be_inlined": false, - "is_user_data": false, - "type_name": [ - { - "Type": { - "name": "V", - "type_kind": "External", - "generics": null - } - } - ], - "fields": [ - { - "name": "param0", - "teal_type": [ - { - "Type": { - "name": "string", - "type_kind": "Builtin", - "generics": null - } - } - ], - "ty": { - "Single": { - "name": "string", - "kind": "Builtin" - } - } - } - ], - "static_fields": [], - "methods": [], - "mut_methods": [], - "functions": [], - "mut_functions": [], - "meta_method": [], - "meta_method_mut": [], - "meta_function": [], - "meta_function_mut": [], - "documentation": {}, - "type_doc": "", - "next_docs": null, - "should_generate_help_method": true - } - }, - { - "Enum": { - "name": [ - { - "Type": { - "name": "ExampleCStyleEnum", - "type_kind": "External", - "generics": null - } - } - ], - "variants": [ - "This", - "Is", - "A", - "Basic", - "Example" - ], - "type_doc": "" - } - }, - { - "Record": { - "should_be_inlined": false, - "is_user_data": true, - "type_name": [ - { - "Type": { - "name": "TestCreatorOfDOOM", - "type_kind": "External", - "generics": null - } - } - ], - "fields": [], - "static_fields": [], - "methods": [], - "mut_methods": [], - "functions": [ - { - "name": "NewAmazingFrom", - "signature": [ - { - "Symbol": "function" - }, - { - "Symbol": "(" - }, - { - "Type": { - "name": "V", - "type_kind": "External", - "generics": null - } - }, - { - "Symbol": ")" - }, - { - "Symbol": ":(" - }, - { - "Type": { - "name": "Test2", - "type_kind": "External", - "generics": null - } - }, - { - "Symbol": ")" - } - ], - "params": [ - { - "param_name": null, - "ty": { - "Single": { - "name": "V", - "kind": "External" - } - } - } - ], - "returns": [ - { - "Single": { - "name": "Test2", - "kind": "External" - } - } - ], - "is_meta_method": false - }, - { - "name": "NewLessSo", - "signature": [ - { - "Symbol": "function" - }, - { - "Symbol": "(" - }, - { - "Symbol": ")" - }, - { - "Symbol": ":(" - }, - { - "Type": { - "name": "Test2", - "type_kind": "External", - "generics": null - } - }, - { - "Symbol": ")" - } - ], - "params": [], - "returns": [ - { - "Single": { - "name": "Test2", - "kind": "External" - } - } - ], - "is_meta_method": false - }, - { - "name": "NewOWowADoubleFrom", - "signature": [ - { - "Symbol": "function" - }, - { - "Symbol": "(" - }, - { - "Type": { - "name": "string", - "type_kind": "Builtin", - "generics": null - } - }, - { - "Symbol": " , " - }, - { - "Type": { - "name": "integer", - "type_kind": "Builtin", - "generics": null - } - }, - { - "Symbol": ")" - }, - { - "Symbol": ":(" - }, - { - "Type": { - "name": "Test2", - "type_kind": "External", - "generics": null - } - }, - { - "Symbol": ")" - } - ], - "params": [ - { - "param_name": null, - "ty": { - "Single": { - "name": "string", - "kind": "Builtin" - } - } - }, - { - "param_name": null, - "ty": { - "Single": { - "name": "integer", - "kind": "Builtin" - } - } - } - ], - "returns": [ - { - "Single": { - "name": "Test2", - "kind": "External" - } - } - ], - "is_meta_method": false - } - ], - "mut_functions": [], - "meta_method": [], - "meta_method_mut": [], - "meta_function": [], - "meta_function_mut": [], - "documentation": {}, - "type_doc": "", - "next_docs": null, - "should_generate_help_method": true - } - }, - { - "Record": { - "should_be_inlined": false, - "is_user_data": true, - "type_name": [ - { - "Type": { - "name": "Test2", - "type_kind": "External", - "generics": null - } - } - ], - "fields": [], - "static_fields": [], - "methods": [ - { - "name": "IsAmazing", - "signature": [ - { - "Symbol": "function" - }, - { - "Symbol": "(" - }, - { - "Symbol": "self" - }, - { - "Symbol": ":" - }, - { - "Type": { - "name": "Test2", - "type_kind": "External", - "generics": null - } - }, - { - "Symbol": ")" - }, - { - "Symbol": ":(" - }, - { - "Type": { - "name": "boolean", - "type_kind": "Builtin", - "generics": null - } - }, - { - "Symbol": ")" - } - ], - "params": [ - { - "param_name": "self", - "ty": { - "Single": { - "name": "Test2", - "kind": "External" - } - } - } - ], - "returns": [ - { - "Single": { - "name": "boolean", - "kind": "Builtin" - } - } - ], - "is_meta_method": false - }, - { - "name": "GetAmazing", - "signature": [ - { - "Symbol": "function" - }, - { - "Symbol": "(" - }, - { - "Symbol": "self" - }, - { - "Symbol": ":" - }, - { - "Type": { - "name": "Test2", - "type_kind": "External", - "generics": null - } - }, - { - "Symbol": ")" - }, - { - "Symbol": ":(" - }, - { - "Type": { - "name": "boolean", - "type_kind": "Builtin", - "generics": null - } - }, - { - "Symbol": " , " - }, - { - "Type": { - "name": "V", - "type_kind": "External", - "generics": null - } - }, - { - "Symbol": ")" - } - ], - "params": [ - { - "param_name": "self", - "ty": { - "Single": { - "name": "Test2", - "kind": "External" - } - } - } - ], - "returns": [ - { - "Single": { - "name": "boolean", - "kind": "Builtin" - } - }, - { - "Single": { - "name": "V", - "kind": "External" - } - } - ], - "is_meta_method": false - }, - { - "name": "GetAmazingOrNil", - "signature": [ - { - "Symbol": "function" - }, - { - "Symbol": "(" - }, - { - "Symbol": "self" - }, - { - "Symbol": ":" - }, - { - "Type": { - "name": "Test2", - "type_kind": "External", - "generics": null - } - }, - { - "Symbol": ")" - }, - { - "Symbol": ":(" - }, - { - "Type": { - "name": "V", - "type_kind": "External", - "generics": null - } - }, - { - "Symbol": ")" - } - ], - "params": [ - { - "param_name": "self", - "ty": { - "Single": { - "name": "Test2", - "kind": "External" - } - } - } - ], - "returns": [ - { - "Single": { - "name": "V", - "kind": "External" - } - } - ], - "is_meta_method": false - }, - { - "name": "IsLessSo", - "signature": [ - { - "Symbol": "function" - }, - { - "Symbol": "(" - }, - { - "Symbol": "self" - }, - { - "Symbol": ":" - }, - { - "Type": { - "name": "Test2", - "type_kind": "External", - "generics": null - } - }, - { - "Symbol": ")" - }, - { - "Symbol": ":(" - }, - { - "Type": { - "name": "boolean", - "type_kind": "Builtin", - "generics": null - } - }, - { - "Symbol": ")" - } - ], - "params": [ - { - "param_name": "self", - "ty": { - "Single": { - "name": "Test2", - "kind": "External" - } - } - } - ], - "returns": [ - { - "Single": { - "name": "boolean", - "kind": "Builtin" - } - } - ], - "is_meta_method": false - }, - { - "name": "IsOWowADouble", - "signature": [ - { - "Symbol": "function" - }, - { - "Symbol": "(" - }, - { - "Symbol": "self" - }, - { - "Symbol": ":" - }, - { - "Type": { - "name": "Test2", - "type_kind": "External", - "generics": null - } - }, - { - "Symbol": ")" - }, - { - "Symbol": ":(" - }, - { - "Type": { - "name": "boolean", - "type_kind": "Builtin", - "generics": null - } - }, - { - "Symbol": ")" - } - ], - "params": [ - { - "param_name": "self", - "ty": { - "Single": { - "name": "Test2", - "kind": "External" - } - } - } - ], - "returns": [ - { - "Single": { - "name": "boolean", - "kind": "Builtin" - } - } - ], - "is_meta_method": false - }, - { - "name": "GetOWowADouble", - "signature": [ - { - "Symbol": "function" - }, - { - "Symbol": "(" - }, - { - "Symbol": "self" - }, - { - "Symbol": ":" - }, - { - "Type": { - "name": "Test2", - "type_kind": "External", - "generics": null - } - }, - { - "Symbol": ")" - }, - { - "Symbol": ":(" - }, - { - "Type": { - "name": "boolean", - "type_kind": "Builtin", - "generics": null - } - }, - { - "Symbol": " , " - }, - { - "Type": { - "name": "string", - "type_kind": "Builtin", - "generics": null - } - }, - { - "Symbol": " , " - }, - { - "Type": { - "name": "integer", - "type_kind": "Builtin", - "generics": null - } - }, - { - "Symbol": ")" - } - ], - "params": [ - { - "param_name": "self", - "ty": { - "Single": { - "name": "Test2", - "kind": "External" - } - } - } - ], - "returns": [ - { - "Single": { - "name": "boolean", - "kind": "Builtin" - } - }, - { - "Single": { - "name": "string", - "kind": "Builtin" - } - }, - { - "Single": { - "name": "integer", - "kind": "Builtin" - } - } - ], - "is_meta_method": false - }, - { - "name": "GetOWowADoubleOrNil", - "signature": [ - { - "Symbol": "function" - }, - { - "Symbol": "(" - }, - { - "Symbol": "self" - }, - { - "Symbol": ":" - }, - { - "Type": { - "name": "Test2", - "type_kind": "External", - "generics": null - } - }, - { - "Symbol": ")" - }, - { - "Symbol": ":(" - }, - { - "Type": { - "name": "string", - "type_kind": "Builtin", - "generics": null - } - }, - { - "Symbol": " , " - }, - { - "Type": { - "name": "integer", - "type_kind": "Builtin", - "generics": null - } - }, - { - "Symbol": ")" - } - ], - "params": [ - { - "param_name": "self", - "ty": { - "Single": { - "name": "Test2", - "kind": "External" - } - } - } - ], - "returns": [ - { - "Single": { - "name": "string", - "kind": "Builtin" - } - }, - { - "Single": { - "name": "integer", - "kind": "Builtin" - } - } - ], - "is_meta_method": false - }, - { - "name": "GetTypeName", - "signature": [ - { - "Symbol": "function" - }, - { - "Symbol": "(" - }, - { - "Symbol": "self" - }, - { - "Symbol": ":" - }, - { - "Type": { - "name": "Test2", - "type_kind": "External", - "generics": null - } - }, - { - "Symbol": ")" - }, - { - "Symbol": ":(" - }, - { - "Type": { - "name": "string", - "type_kind": "Builtin", - "generics": null - } - }, - { - "Symbol": ")" - } - ], - "params": [ - { - "param_name": "self", - "ty": { - "Single": { - "name": "Test2", - "kind": "External" - } - } - } - ], - "returns": [ - { - "Single": { - "name": "string", - "kind": "Builtin" - } - } - ], - "is_meta_method": false - } - ], - "mut_methods": [], - "functions": [ - { - "name": "NewAmazingFrom", - "signature": [ - { - "Symbol": "function" - }, - { - "Symbol": "(" - }, - { - "Type": { - "name": "V", - "type_kind": "External", - "generics": null - } - }, - { - "Symbol": ")" - }, - { - "Symbol": ":(" - }, - { - "Type": { - "name": "Test2", - "type_kind": "External", - "generics": null - } - }, - { - "Symbol": ")" - } - ], - "params": [ - { - "param_name": null, - "ty": { - "Single": { - "name": "V", - "kind": "External" - } - } - } - ], - "returns": [ - { - "Single": { - "name": "Test2", - "kind": "External" - } - } - ], - "is_meta_method": false - }, - { - "name": "NewLessSo", - "signature": [ - { - "Symbol": "function" - }, - { - "Symbol": "(" - }, - { - "Symbol": ")" - }, - { - "Symbol": ":(" - }, - { - "Type": { - "name": "Test2", - "type_kind": "External", - "generics": null - } - }, - { - "Symbol": ")" - } - ], - "params": [], - "returns": [ - { - "Single": { - "name": "Test2", - "kind": "External" - } - } - ], - "is_meta_method": false - }, - { - "name": "NewOWowADoubleFrom", - "signature": [ - { - "Symbol": "function" - }, - { - "Symbol": "(" - }, - { - "Type": { - "name": "string", - "type_kind": "Builtin", - "generics": null - } - }, - { - "Symbol": " , " - }, - { - "Type": { - "name": "integer", - "type_kind": "Builtin", - "generics": null - } - }, - { - "Symbol": ")" - }, - { - "Symbol": ":(" - }, - { - "Type": { - "name": "Test2", - "type_kind": "External", - "generics": null - } - }, - { - "Symbol": ")" - } - ], - "params": [ - { - "param_name": null, - "ty": { - "Single": { - "name": "string", - "kind": "Builtin" - } - } - }, - { - "param_name": null, - "ty": { - "Single": { - "name": "integer", - "kind": "Builtin" - } - } - } - ], - "returns": [ - { - "Single": { - "name": "Test2", - "kind": "External" - } - } - ], - "is_meta_method": false - } - ], - "mut_functions": [], - "meta_method": [], - "meta_method_mut": [], - "meta_function": [], - "meta_function_mut": [], - "documentation": {}, - "type_doc": "", - "next_docs": null, - "should_generate_help_method": true - } - }, - { - "Record": { - "should_be_inlined": false, - "is_user_data": false, - "type_name": [ - { - "Type": { - "name": "Example", - "type_kind": "External", - "generics": null - } - } - ], - "fields": [ - { - "name": "field1", - "teal_type": [ - { - "Type": { - "name": "Test2", - "type_kind": "External", - "generics": null - } - } - ], - "ty": { - "Single": { - "name": "Test2", - "kind": "External" - } - } - }, - { - "name": "nice", - "teal_type": [ - { - "Type": { - "name": "integer", - "type_kind": "Builtin", - "generics": null - } - } - ], - "ty": { - "Single": { - "name": "integer", - "kind": "Builtin" - } - } - }, - { - "name": "v", - "teal_type": [ - { - "Type": { - "name": "ExampleCStyleEnum", - "type_kind": "External", - "generics": null - } - } - ], - "ty": { - "Single": { - "name": "ExampleCStyleEnum", - "kind": "External" - } - } - } - ], - "static_fields": [], - "methods": [], - "mut_methods": [], - "functions": [], - "mut_functions": [], - "meta_method": [], - "meta_method_mut": [], - "meta_function": [], - "meta_function_mut": [], - "documentation": {}, - "type_doc": "", - "next_docs": null, - "should_generate_help_method": true - } - } - ], - "global_instances_off": [], - "extra_page": [] -} \ No newline at end of file diff --git a/tests/rlua/to_from_derived.rs b/tests/rlua/to_from_derived.rs deleted file mode 100644 index f151091..0000000 --- a/tests/rlua/to_from_derived.rs +++ /dev/null @@ -1,106 +0,0 @@ -use tealr::{ - rlu::{rlua::Lua, FromToLua}, - ToTypename, TypeWalker, -}; - -#[derive(FromToLua, ToTypename, PartialEq, Debug, Clone)] -enum ExampleCStyleEnum { - This, - Is, - A, - Basic, - Example, -} - -#[derive(FromToLua, Clone, ToTypename)] -struct V(String); -impl From for V { - fn from(x: String) -> Self { - Self(x) - } -} -impl From for String { - fn from(x: V) -> Self { - x.0 - } -} - -#[derive(FromToLua, Clone, ToTypename, serde::Deserialize)] -#[tealr(creator_name = TestCreatorOfDOOM)] -#[serde(deny_unknown_fields)] -pub(crate) enum Test2 { - Amazing(#[tealr(remote = V)] String), - LessSo, - OWowADouble(String, i8), -} -impl From for Test2 { - fn from(field: String) -> Self { - Self::Amazing(field) - } -} -impl From for String { - fn from(s: Test2) -> Self { - match s { - Test2::Amazing(x) => x, - Test2::LessSo => String::new(), - Test2::OWowADouble(x, _) => x, - } - } -} - -#[derive(Clone, Debug, FromToLua, ToTypename, PartialEq)] -struct Example { - #[tealr(remote = Test2)] - field1: String, - nice: i32, - v: ExampleCStyleEnum, -} - -#[test] -fn main() -> Result<(), Box> { - //lets first generate the definition file - let file_contents = TypeWalker::new() - .process_type::() - .process_type::() - .process_type::() - .process_type::() - .process_type::() - .to_json_pretty() - .expect("oh no :("); - - let new_value: serde_json::Value = serde_json::from_str(&file_contents).unwrap(); - let mut old_value: serde_json::Value = - serde_json::from_str(include_str!("./to_from_derived.json")).unwrap(); - let mut x = old_value - .get_mut("tealr_version_used") - .expect("missing tealr_version_used in original"); - if let serde_json::Value::String(x) = &mut x { - *x = tealr::get_tealr_version().to_string(); - } - assert_eq!(new_value, old_value); - let mut to_pass = Example { - field1: String::from("nice"), - nice: 2, - v: ExampleCStyleEnum::Example, - }; - - let lua = Lua::new(); - let res: Example = lua.context(|lua| { - let globals = lua.globals(); - - globals.set("test", to_pass.clone())?; - globals.set("creator", TestCreatorOfDOOM::new())?; - let code = " - local v = assert(test.field1:GetAmazingOrNil()) - assert(v[0] == \"nice\") - assert(test.nice == 2) - test.field1 = creator.NewLessSo() - return test - "; - lua.load(code).set_name("test?")?.eval() - })?; - to_pass.field1 = String::from(Test2::LessSo); - assert_eq!(res, to_pass); - - Ok(()) -} diff --git a/tests/rlua/type_picker.json b/tests/rlua/type_picker.json deleted file mode 100644 index 1679b29..0000000 --- a/tests/rlua/type_picker.json +++ /dev/null @@ -1,623 +0,0 @@ -{ - "tealr_version_used": "0.9.0-alpha4", - "given_types": [ - { - "Record": { - "should_be_inlined": false, - "is_user_data": true, - "type_name": [ - { - "Type": { - "name": "Example", - "type_kind": "External", - "generics": null - } - } - ], - "fields": [], - "static_fields": [], - "methods": [ - { - "name": "limited_callback", - "signature": [ - { - "Symbol": "function" - }, - { - "Symbol": "(" - }, - { - "Symbol": "self" - }, - { - "Symbol": ":" - }, - { - "Type": { - "name": "Example", - "type_kind": "External", - "generics": null - } - }, - { - "Symbol": " , " - }, - { - "Symbol": "function" - }, - { - "Symbol": "(" - }, - { - "Symbol": "(" - }, - { - "Type": { - "name": "string", - "type_kind": "Builtin", - "generics": null - } - }, - { - "Symbol": " | " - }, - { - "Type": { - "name": "number", - "type_kind": "Builtin", - "generics": null - } - }, - { - "Symbol": " | " - }, - { - "Type": { - "name": "boolean", - "type_kind": "Builtin", - "generics": null - } - }, - { - "Symbol": ")" - }, - { - "Symbol": ")" - }, - { - "Symbol": ":(" - }, - { - "Symbol": "(" - }, - { - "Type": { - "name": "string", - "type_kind": "Builtin", - "generics": null - } - }, - { - "Symbol": " | " - }, - { - "Type": { - "name": "number", - "type_kind": "Builtin", - "generics": null - } - }, - { - "Symbol": " | " - }, - { - "Type": { - "name": "boolean", - "type_kind": "Builtin", - "generics": null - } - }, - { - "Symbol": ")" - }, - { - "Symbol": ")" - }, - { - "Symbol": ")" - }, - { - "Symbol": ":(" - }, - { - "Symbol": "(" - }, - { - "Type": { - "name": "string", - "type_kind": "Builtin", - "generics": null - } - }, - { - "Symbol": " | " - }, - { - "Type": { - "name": "number", - "type_kind": "Builtin", - "generics": null - } - }, - { - "Symbol": " | " - }, - { - "Type": { - "name": "boolean", - "type_kind": "Builtin", - "generics": null - } - }, - { - "Symbol": ")" - }, - { - "Symbol": ")" - } - ], - "params": [ - { - "param_name": "self", - "ty": { - "Single": { - "name": "Example", - "kind": "External" - } - } - }, - { - "param_name": null, - "ty": { - "Function": { - "params": [ - { - "param_name": null, - "ty": { - "Or": [ - { - "Single": { - "name": "string", - "kind": "Builtin" - } - }, - { - "Single": { - "name": "number", - "kind": "Builtin" - } - }, - { - "Single": { - "name": "boolean", - "kind": "Builtin" - } - } - ] - } - } - ], - "returns": [ - { - "Or": [ - { - "Single": { - "name": "string", - "kind": "Builtin" - } - }, - { - "Single": { - "name": "number", - "kind": "Builtin" - } - }, - { - "Single": { - "name": "boolean", - "kind": "Builtin" - } - } - ] - } - ] - } - } - } - ], - "returns": [ - { - "Or": [ - { - "Single": { - "name": "string", - "kind": "Builtin" - } - }, - { - "Single": { - "name": "number", - "kind": "Builtin" - } - }, - { - "Single": { - "name": "boolean", - "kind": "Builtin" - } - } - ] - } - ], - "is_meta_method": false - }, - { - "name": "limited_array", - "signature": [ - { - "Symbol": "function" - }, - { - "Symbol": "(" - }, - { - "Symbol": "self" - }, - { - "Symbol": ":" - }, - { - "Type": { - "name": "Example", - "type_kind": "External", - "generics": null - } - }, - { - "Symbol": " , " - }, - { - "Symbol": "{" - }, - { - "Symbol": "(" - }, - { - "Type": { - "name": "string", - "type_kind": "Builtin", - "generics": null - } - }, - { - "Symbol": " | " - }, - { - "Type": { - "name": "number", - "type_kind": "Builtin", - "generics": null - } - }, - { - "Symbol": " | " - }, - { - "Type": { - "name": "boolean", - "type_kind": "Builtin", - "generics": null - } - }, - { - "Symbol": ")" - }, - { - "Symbol": "}" - }, - { - "Symbol": ")" - }, - { - "Symbol": ":(" - }, - { - "Symbol": "{" - }, - { - "Symbol": "(" - }, - { - "Type": { - "name": "string", - "type_kind": "Builtin", - "generics": null - } - }, - { - "Symbol": " | " - }, - { - "Type": { - "name": "number", - "type_kind": "Builtin", - "generics": null - } - }, - { - "Symbol": " | " - }, - { - "Type": { - "name": "boolean", - "type_kind": "Builtin", - "generics": null - } - }, - { - "Symbol": ")" - }, - { - "Symbol": "}" - }, - { - "Symbol": ")" - } - ], - "params": [ - { - "param_name": "self", - "ty": { - "Single": { - "name": "Example", - "kind": "External" - } - } - }, - { - "param_name": null, - "ty": { - "Array": { - "Or": [ - { - "Single": { - "name": "string", - "kind": "Builtin" - } - }, - { - "Single": { - "name": "number", - "kind": "Builtin" - } - }, - { - "Single": { - "name": "boolean", - "kind": "Builtin" - } - } - ] - } - } - } - ], - "returns": [ - { - "Array": { - "Or": [ - { - "Single": { - "name": "string", - "kind": "Builtin" - } - }, - { - "Single": { - "name": "number", - "kind": "Builtin" - } - }, - { - "Single": { - "name": "boolean", - "kind": "Builtin" - } - } - ] - } - } - ], - "is_meta_method": false - }, - { - "name": "limited_simple", - "signature": [ - { - "Symbol": "function" - }, - { - "Symbol": "(" - }, - { - "Symbol": "self" - }, - { - "Symbol": ":" - }, - { - "Type": { - "name": "Example", - "type_kind": "External", - "generics": null - } - }, - { - "Symbol": " , " - }, - { - "Symbol": "(" - }, - { - "Type": { - "name": "string", - "type_kind": "Builtin", - "generics": null - } - }, - { - "Symbol": " | " - }, - { - "Type": { - "name": "number", - "type_kind": "Builtin", - "generics": null - } - }, - { - "Symbol": " | " - }, - { - "Type": { - "name": "boolean", - "type_kind": "Builtin", - "generics": null - } - }, - { - "Symbol": ")" - }, - { - "Symbol": ")" - }, - { - "Symbol": ":(" - }, - { - "Symbol": "(" - }, - { - "Type": { - "name": "string", - "type_kind": "Builtin", - "generics": null - } - }, - { - "Symbol": " | " - }, - { - "Type": { - "name": "number", - "type_kind": "Builtin", - "generics": null - } - }, - { - "Symbol": " | " - }, - { - "Type": { - "name": "boolean", - "type_kind": "Builtin", - "generics": null - } - }, - { - "Symbol": ")" - }, - { - "Symbol": ")" - } - ], - "params": [ - { - "param_name": "self", - "ty": { - "Single": { - "name": "Example", - "kind": "External" - } - } - }, - { - "param_name": null, - "ty": { - "Or": [ - { - "Single": { - "name": "string", - "kind": "Builtin" - } - }, - { - "Single": { - "name": "number", - "kind": "Builtin" - } - }, - { - "Single": { - "name": "boolean", - "kind": "Builtin" - } - } - ] - } - } - ], - "returns": [ - { - "Or": [ - { - "Single": { - "name": "string", - "kind": "Builtin" - } - }, - { - "Single": { - "name": "number", - "kind": "Builtin" - } - }, - { - "Single": { - "name": "boolean", - "kind": "Builtin" - } - } - ] - } - ], - "is_meta_method": false - } - ], - "mut_methods": [], - "functions": [], - "mut_functions": [], - "meta_method": [], - "meta_method_mut": [], - "meta_function": [], - "meta_function_mut": [], - "documentation": {}, - "type_doc": "", - "next_docs": null, - "should_generate_help_method": true - } - } - ], - "global_instances_off": [], - "extra_page": [] -} \ No newline at end of file diff --git a/tests/rlua/type_picker.rs b/tests/rlua/type_picker.rs deleted file mode 100644 index 9ac3fd6..0000000 --- a/tests/rlua/type_picker.rs +++ /dev/null @@ -1,55 +0,0 @@ -use rlua::ToLua; -use tealr::{ - create_union_rlua, - rlu::{rlua::FromLua, TealData, TealDataMethods, TypedFunction, UserData}, - ToTypename, TypeWalker, -}; - -create_union_rlua!(enum X = String | f32 | bool); - -#[derive(Clone, UserData, ToTypename)] -struct Example {} - -//now, implement TealData. This tells mlua what methods are available and tealr what the types are -impl TealData for Example { - //implement your methods/functions - fn add_methods<'lua, T: TealDataMethods<'lua, Self>>(methods: &mut T) { - methods.add_method("limited_callback", |lua, _, fun: TypedFunction| { - let param = X::from_lua("nice!".to_lua(lua)?, lua)?; - let res = fun.call(param)?; - Ok(res) - }); - methods.add_method("limited_array", |_, _, x: Vec| Ok(x)); - methods.add_method("limited_simple", |_, _, x: X| Ok(x)); - } -} - -#[test] -fn test_limited() { - let file_contents = TypeWalker::new() - .process_type::() - .to_json_pretty() - .unwrap(); - - let new_value: serde_json::Value = serde_json::from_str(&file_contents).unwrap(); - let mut old_value: serde_json::Value = - serde_json::from_str(include_str!("./type_picker.json")).unwrap(); - let mut x = old_value - .get_mut("tealr_version_used") - .expect("missing tealr_version_used in original"); - if let serde_json::Value::String(x) = &mut x { - *x = tealr::get_tealr_version().to_string(); - } - assert_eq!(new_value, old_value); - let res: bool = rlua::Lua::new() - .context(|ctx| { - let globals = ctx.globals(); - globals.set("test", Example {}).unwrap(); - let code = " - return test:limited_simple(true) - "; - ctx.load(code).eval() - }) - .unwrap(); - assert!(res); -} diff --git a/tests/mlua/test_embedded_compiler.tl b/tests/test_embedded_compiler.tl similarity index 100% rename from tests/mlua/test_embedded_compiler.tl rename to tests/test_embedded_compiler.tl diff --git a/tests/mlua/to_from_derived.json b/tests/to_from_derived.json similarity index 100% rename from tests/mlua/to_from_derived.json rename to tests/to_from_derived.json diff --git a/tests/mlua/to_from_derived.rs b/tests/to_from_derived.rs similarity index 97% rename from tests/mlua/to_from_derived.rs rename to tests/to_from_derived.rs index 6d1e998..2feb503 100644 --- a/tests/mlua/to_from_derived.rs +++ b/tests/to_from_derived.rs @@ -70,7 +70,7 @@ fn main() -> Result<(), Box> { let new_value: serde_json::Value = serde_json::from_str(&file_contents).unwrap(); let mut old_value: serde_json::Value = - serde_json::from_str(include_str!("./to_from_derived.json")).unwrap(); + serde_json::from_str(include_str!("to_from_derived.json")).unwrap(); let mut x = old_value .get_mut("tealr_version_used") diff --git a/tests/mlua/type_picker.json b/tests/type_picker.json similarity index 100% rename from tests/mlua/type_picker.json rename to tests/type_picker.json diff --git a/tests/mlua/type_picker.rs b/tests/type_picker.rs similarity index 91% rename from tests/mlua/type_picker.rs rename to tests/type_picker.rs index 5a13d47..5940c30 100644 --- a/tests/mlua/type_picker.rs +++ b/tests/type_picker.rs @@ -13,7 +13,7 @@ struct Example {} //now, implement TealData. This tells mlua what methods are available and tealr what the types are impl TealData for Example { //implement your methods/functions - fn add_methods<'lua, T: TealDataMethods<'lua, Self>>(methods: &mut T) { + fn add_methods>(methods: &mut T) { methods.add_method("limited_callback", |lua, _, fun: TypedFunction| { let param = X::from_lua("nice!".into_lua(lua)?, lua)?; let res = fun.call(param)?; @@ -33,7 +33,7 @@ fn test_limited() { let new_value: serde_json::Value = serde_json::from_str(&file_contents).unwrap(); let mut old_value: serde_json::Value = - serde_json::from_str(include_str!("./type_picker.json")).unwrap(); + serde_json::from_str(include_str!("type_picker.json")).unwrap(); let mut x = old_value .get_mut("tealr_version_used")