mirror of
https://github.com/mlua-rs/mlua
synced 2026-06-08 16:05:43 +00:00
Compare commits
590 Commits
v0.9
...
v0.12.0-rc.2
| Author | SHA1 | Date | |
|---|---|---|---|
| 0711c614c7 | |||
| 743325f7d6 | |||
| 0b365e92a9 | |||
| 15fb63b2a2 | |||
| 0849d05c83 | |||
| 38c05b850e | |||
| 8d1841f8cf | |||
| e9271d2e32 | |||
| e263220fb3 | |||
| e6d16815d7 | |||
| ae88e8acf8 | |||
| fcab60bac4 | |||
| 208a70f407 | |||
| ca360f9019 | |||
| a7c5a24a7b | |||
| b7c98ad9bb | |||
| 1f3dafa564 | |||
| 1d4a756436 | |||
| 6e7d6c78ed | |||
| 023e4c61d8 | |||
| 92bd06d3c1 | |||
| d8544bf038 | |||
| 7114c03489 | |||
| f4cacc524e | |||
| cc7f7ce7b7 | |||
| 72de602ec3 | |||
| 1573dd1242 | |||
| 39d3201848 | |||
| 4aa6214b45 | |||
| 72824a468a | |||
| c54b90623c | |||
| 5f0e06fb66 | |||
| 181c9d07b7 | |||
| 4e827179d1 | |||
| cc26dcd4ff | |||
| 201e30bc07 | |||
| 4e028d8409 | |||
| 3d1ae981d3 | |||
| 8c93948f2f | |||
| f2b5cc44de | |||
| 27f91dfd1b | |||
| 75ff11f795 | |||
| df6097ab38 | |||
| 65bb6279ee | |||
| 31b88e85bb | |||
| 3be4745190 | |||
| c52deec988 | |||
| 3ab3c997b3 | |||
| 5872ed70f5 | |||
| e7e92b4f6f | |||
| d27693b61a | |||
| c9848d6faf | |||
| 9126bb8ce0 | |||
| 7f1d716a44 | |||
| be56e2205c | |||
| c5aadc68cd | |||
| a5ae2a1fc3 | |||
| 59872da63d | |||
| a24d2151af | |||
| 56c227fd7e | |||
| d5d66abe42 | |||
| a2d8b21964 | |||
| a9604c4946 | |||
| 81ae8e1393 | |||
| a959b98d30 | |||
| efd0856033 | |||
| c91066006f | |||
| a45fe9bb93 | |||
| f1a97e4193 | |||
| 47e6a37323 | |||
| bf0c96908f | |||
| 8817720362 | |||
| 35294359ad | |||
| eb76db59da | |||
| 33bf3ffde7 | |||
| 0f3fdb0539 | |||
| 79d438aaad | |||
| 30cf4bef58 | |||
| 5776c72208 | |||
| 943c3aed58 | |||
| 8fcb6a8416 | |||
| 452dc8be88 | |||
| 63a255bbc9 | |||
| 151adc0e87 | |||
| 7f3ec63ab5 | |||
| f19c6aac3b | |||
| 29af448ad9 | |||
| 497d84828a | |||
| 0e489901a5 | |||
| 88063e756f | |||
| c8436e2b80 | |||
| 613748ec16 | |||
| 2fbd266da6 | |||
| c79b5e9cdb | |||
| 2ace892613 | |||
| c1ffd4e790 | |||
| d9c139b55f | |||
| 0c4206c97d | |||
| a985dc7a37 | |||
| e7fa8d75bb | |||
| c10718ed2f | |||
| ec2ce3620f | |||
| 71757003c7 | |||
| 6bb7f09927 | |||
| e67ae7f0de | |||
| 8c1535c27b | |||
| fd245daa6f | |||
| 7fb7e8685f | |||
| 93617eef4e | |||
| 171cdf1758 | |||
| 3f8f016daa | |||
| 86d0c9bddb | |||
| 86d63ef27b | |||
| e33bcf7938 | |||
| c80a97b526 | |||
| 3c40cfe199 | |||
| e9efb73125 | |||
| 386c6d8ed8 | |||
| 8f086bf837 | |||
| ad167612dc | |||
| 3366f47d40 | |||
| 0b5ef91f44 | |||
| a162b0ceca | |||
| 8e6d652a21 | |||
| 1be9e6ce2d | |||
| b1f99aa852 | |||
| 4c5465229e | |||
| 9b24bb2319 | |||
| e1701b6b56 | |||
| 77d7d5d6bd | |||
| ee9232eda1 | |||
| da526595bb | |||
| 39a7d3b862 | |||
| 0245d4ce6b | |||
| a7f105c698 | |||
| d2a8670bef | |||
| e9de70a030 | |||
| aee647c6c0 | |||
| 2e4184e7e4 | |||
| 12b24b6c5b | |||
| 1b500b7d47 | |||
| ce4fc80e18 | |||
| 121971f54e | |||
| 6835537e3b | |||
| a2728928cf | |||
| 676f3a6983 | |||
| 0beaac228c | |||
| 9a7f75ad6b | |||
| cd56f92a7f | |||
| 1bd1359f43 | |||
| feec72bcbd | |||
| 0611906c6a | |||
| 72ac247dca | |||
| f2fd010c5f | |||
| 0619f264de | |||
| ddd44bdd36 | |||
| 1152519074 | |||
| 3a2fd1ec59 | |||
| a4c8b20697 | |||
| 6e353d6c9f | |||
| 247208edb1 | |||
| e08768cc5e | |||
| 5b38af9746 | |||
| 54907f80c5 | |||
| ae512f2b49 | |||
| 53c159b6cb | |||
| 2beca6ebe1 | |||
| 09da7a41e5 | |||
| bad20374ad | |||
| 40b507c3ec | |||
| 537cc995f6 | |||
| 5d27cb91b2 | |||
| c70a636ca9 | |||
| 13ff0ca798 | |||
| 44f49e35d6 | |||
| e1ee4058a6 | |||
| f06d0020ea | |||
| d399559d30 | |||
| 30735d5ff1 | |||
| 75c23e5853 | |||
| 347856b806 | |||
| 774a63bece | |||
| c481c87eac | |||
| 85b280a9d6 | |||
| db7b782d3c | |||
| 5f38445558 | |||
| df0a44d405 | |||
| f0806a6d62 | |||
| 3516f4c6ca | |||
| ca73583714 | |||
| 36560435f7 | |||
| 763c2b2564 | |||
| bafdb6138c | |||
| c9d6a610e1 | |||
| bd63f63bc9 | |||
| c035c23a15 | |||
| cb153a52b2 | |||
| b1c69d3005 | |||
| 841bd332e4 | |||
| 815d1bd7c9 | |||
| 78331ceebe | |||
| f945a35cbd | |||
| 459edb6816 | |||
| 00328b0b64 | |||
| 928d94d255 | |||
| 583c35a172 | |||
| 1791c599f4 | |||
| 1e48817a64 | |||
| 8d219503dd | |||
| 95367855c1 | |||
| 49389c4aa4 | |||
| 13dc2b5352 | |||
| 7afbf74128 | |||
| 06c3bd9d69 | |||
| 1ddaea60ce | |||
| a653d08768 | |||
| 2b6b0144a1 | |||
| 4cfe0be945 | |||
| a9a4814c3c | |||
| b1f73ec29d | |||
| 61a2141151 | |||
| dea38f27a5 | |||
| 04aaa18dc8 | |||
| d8455c038a | |||
| ca22ea3be7 | |||
| cf05593d66 | |||
| d011a1f851 | |||
| 1ec4661bf9 | |||
| d3b2999d2f | |||
| 72f6536efb | |||
| 646827a6bb | |||
| 1882931cd9 | |||
| c90cac5189 | |||
| c0d839d8d2 | |||
| 80471c6dad | |||
| 4b9d1cf271 | |||
| 55c07f3b28 | |||
| ef4eabd327 | |||
| a3302afdc1 | |||
| dfb4e9a668 | |||
| 92db0f6d3a | |||
| a3697ab1db | |||
| 052740db15 | |||
| faf547c154 | |||
| 0de7cd1c7d | |||
| 58953e5635 | |||
| 6406de405d | |||
| 727096dd3b | |||
| 2445230759 | |||
| 1cd2bdc808 | |||
| f8ed33a2aa | |||
| 25955893e0 | |||
| 3f0c69b70b | |||
| 9da98d42c7 | |||
| f539f60987 | |||
| aa187e6663 | |||
| ec10bf2a39 | |||
| 3ea80b763d | |||
| 2e0e86dab2 | |||
| 0ac7aebb27 | |||
| 634e5d4550 | |||
| 05d6c20520 | |||
| 63e7cfd31b | |||
| 9c24c99cbe | |||
| 62f84828f2 | |||
| 7bc72be7d3 | |||
| 2fbbbe4238 | |||
| f00208373e | |||
| a2dc662a92 | |||
| caeac2e9a3 | |||
| 3d5261640d | |||
| b57a6239a6 | |||
| 031424f6ce | |||
| c4c9609ac6 | |||
| 6fcd18e434 | |||
| 39cac5699a | |||
| e6e1ef014f | |||
| 942a443592 | |||
| 65e292dac4 | |||
| 1a82f83644 | |||
| 38fbd08c72 | |||
| b3854d2f1d | |||
| 00a56b115b | |||
| 2fefaafaa6 | |||
| 76a8f8cc71 | |||
| 13395e9c3d | |||
| c61219dd93 | |||
| 2e7c654cfe | |||
| f36aaa5ce1 | |||
| df38878278 | |||
| c5c1fe3b85 | |||
| 0cc4b15f6b | |||
| f16aca687d | |||
| 9b45663afd | |||
| c0c802262e | |||
| dda344bfc6 | |||
| 93adfa42d1 | |||
| 5dc6c3214b | |||
| da08f7210f | |||
| 8b7a85076a | |||
| a4ff68a120 | |||
| 5454cfa5ed | |||
| f9d9dc74a7 | |||
| ed796fff51 | |||
| 65e5be81ba | |||
| 4fa8e645b7 | |||
| 05a0abb8c2 | |||
| f0c0527c2b | |||
| 2490dfeb38 | |||
| 4a3dbafb6e | |||
| 97ca3e2c08 | |||
| d6fb328660 | |||
| edd508ed1f | |||
| a30a736291 | |||
| 8e1df48e81 | |||
| efd192b816 | |||
| 5e1451a465 | |||
| 64b1d152b9 | |||
| a8a4aa8c93 | |||
| 9fda2ecfcc | |||
| 21fc924457 | |||
| 30d5e08a8a | |||
| 560a30ca02 | |||
| 117f8377e2 | |||
| 8173ef2fa8 | |||
| 4e5677ae54 | |||
| 49958f4827 | |||
| 39b3af2ff2 | |||
| b805939320 | |||
| bd13300288 | |||
| 12e61e01f6 | |||
| 53ff494ab9 | |||
| 1cb081d20a | |||
| c1a018a60d | |||
| 4d2ff45a8b | |||
| 72682198eb | |||
| 87fa663ac1 | |||
| 1f970824b4 | |||
| 8d864e2687 | |||
| b0140cdb9e | |||
| 806817212e | |||
| 95c623e94d | |||
| 0a1a1fe0b6 | |||
| 4fe7d151a1 | |||
| edbf1e9150 | |||
| 69011a89d2 | |||
| 0ed11e4134 | |||
| 0ce599aff2 | |||
| 1ebb4b468a | |||
| 5ab97666d7 | |||
| e706ae4fcb | |||
| ae7cdcb934 | |||
| dacddfa967 | |||
| a01b032c35 | |||
| 18497f1528 | |||
| 28e8f56989 | |||
| c1f8abba9e | |||
| d1a587f49a | |||
| 5bbd23ed1a | |||
| 74b4601b48 | |||
| a89800b949 | |||
| 2b6172ef38 | |||
| 20f7ce097d | |||
| 6882e0434e | |||
| fca38a6637 | |||
| cdd6a99136 | |||
| 21d39a069d | |||
| 58965c6255 | |||
| 8574682ffc | |||
| 47bc372096 | |||
| d376cb9403 | |||
| ea5ecccf02 | |||
| cf71edc492 | |||
| 9caf3542d9 | |||
| cb45db05fa | |||
| d1cb2a9a96 | |||
| aa3f6ba46c | |||
| cc57bed4c8 | |||
| b5d38ab2e3 | |||
| cd4091f64d | |||
| 91e069a77e | |||
| cacd3dc70f | |||
| 6f6cda0099 | |||
| d51ce86142 | |||
| aa061bce6f | |||
| 1c6b6ad801 | |||
| 031854fa2a | |||
| 5fd96c7908 | |||
| 7a3f19b857 | |||
| 55a5d7ef10 | |||
| af31dbd180 | |||
| 9ae3cb0a7c | |||
| fc1c80c142 | |||
| ee7ced6334 | |||
| d8307d0e4c | |||
| bf9fcc5aca | |||
| 7ce6b97da9 | |||
| 4891a6ac10 | |||
| 4ef0d583fc | |||
| 30b0122f5d | |||
| c31c72076f | |||
| 3bfaee4ecc | |||
| 89b68e2a24 | |||
| cbf805f492 | |||
| c926327a6a | |||
| 7c099500d0 | |||
| 8c889cc353 | |||
| 958abd050e | |||
| 92a8203e1c | |||
| b34b90eca3 | |||
| 7aad0adcb4 | |||
| a3cd25db7a | |||
| a4bfeb7752 | |||
| 0fda512938 | |||
| 58e0661086 | |||
| c7094d470f | |||
| a7d0691e10 | |||
| 05778fbe6f | |||
| b34d67ec41 | |||
| 46ee7ea772 | |||
| 15738dda1f | |||
| 1f32754f05 | |||
| c2eab173c5 | |||
| bb311349ec | |||
| 928e1d9221 | |||
| 5b8681dcf2 | |||
| 4e9a17707b | |||
| 6066089cc1 | |||
| a8d5f23818 | |||
| 5ec4e0338a | |||
| d27d1365b5 | |||
| 76b896edcc | |||
| ddebf56b41 | |||
| 4f56575e05 | |||
| 35fa76263e | |||
| 446d63a77e | |||
| 8d8d521721 | |||
| 0d31a1caa6 | |||
| 3dc58cdfc9 | |||
| 5724b5f112 | |||
| d64d9719c6 | |||
| 75475fc9a8 | |||
| f8fe9246bb | |||
| 5c54361236 | |||
| ec227f9056 | |||
| 93a1a55aaa | |||
| a020b2b5b2 | |||
| 2c756e5958 | |||
| c702077028 | |||
| 08545224f4 | |||
| e122f90837 | |||
| c638d90b02 | |||
| 930fd9c00f | |||
| 2a8db87132 | |||
| cbae4fe59c | |||
| c68e3c4f41 | |||
| 02d4ceff34 | |||
| 98339c57e6 | |||
| 2331995e28 | |||
| c07bdce250 | |||
| 084a85c3d8 | |||
| 735aa22be9 | |||
| 5479546b27 | |||
| 179c54f297 | |||
| f9ae4bf05f | |||
| 9e16e18132 | |||
| 7535a23fa2 | |||
| 3787ff9e8c | |||
| 0a2a70c15a | |||
| 81d7c81532 | |||
| 0453029765 | |||
| 7b777d074e | |||
| c6cd1c53c3 | |||
| 669349d704 | |||
| c086c144d0 | |||
| 640cb2c182 | |||
| 03a4068d55 | |||
| 9f6c78532f | |||
| 8aecc83f53 | |||
| 4891b6535c | |||
| fa343c2c69 | |||
| 6d5e735bed | |||
| ac315fd80b | |||
| f95161c6e0 | |||
| 4bc846a119 | |||
| a3ca95fc8f | |||
| ae4897ab2e | |||
| 4ac87c7208 | |||
| 04d8106676 | |||
| b6cdf32f16 | |||
| ad9bc36764 | |||
| 4b8c26e682 | |||
| 7839c4438c | |||
| 529361fcbc | |||
| 4dddf3c18d | |||
| fb0c0d9ee9 | |||
| 235c32006c | |||
| b65901e444 | |||
| 91fe02da45 | |||
| 8274b5fa88 | |||
| 762e677a70 | |||
| 5b5f1e4669 | |||
| e582e7c57f | |||
| 3714da5ec8 | |||
| ca69be07ff | |||
| 16951e3628 | |||
| 8bb2b444ab | |||
| fc1570d2d7 | |||
| fce85381c6 | |||
| 3088516851 | |||
| 5162a0f46e | |||
| 640d27697d | |||
| da4404baa5 | |||
| 7c2e9b5a7c | |||
| 5db545e7b4 | |||
| b88228b3d4 | |||
| 8677b57847 | |||
| 7543b0674e | |||
| 8e111058c3 | |||
| e1c0aa8491 | |||
| 7957c6868d | |||
| 9c86eefb76 | |||
| 7272e40c23 | |||
| c6ef393ce9 | |||
| d25f2fc07c | |||
| 104e242ddd | |||
| 825bdbfa04 | |||
| 1634c43f0a | |||
| d6b27de34e | |||
| 4018a17e26 | |||
| 5ebbc0868c | |||
| 3774296835 | |||
| ece66c46bf | |||
| 66b4a865c2 | |||
| 21149106ee | |||
| 74bebe6da3 | |||
| 9891e86d16 | |||
| e3c5cfdf19 | |||
| 4977b91a98 | |||
| 6317b8e0c8 | |||
| ecc09c4387 | |||
| 7bfd32750d | |||
| 23d4e2519b | |||
| 2857cb76c6 | |||
| fdc50bffc9 | |||
| 9931709ecd | |||
| 8092f00930 | |||
| d2e87943ac | |||
| 26b9bdb362 | |||
| c58f67b140 | |||
| 0c08cdaf7c | |||
| 10999babe0 | |||
| f0a995a357 | |||
| aa47324ee9 | |||
| ac6a391426 | |||
| 8e14b6e40b | |||
| c117a4c1af | |||
| 4082b354fe | |||
| 3641c98959 | |||
| b7d170ab9b | |||
| 5acf9d758d | |||
| 833790967b | |||
| a86d6ab330 | |||
| 2f8755dcc7 | |||
| 94415065c0 | |||
| bba644e83f | |||
| d5173380e3 | |||
| d9941ef409 | |||
| c715aec1f7 | |||
| cd3f45f31f | |||
| b4892c228c | |||
| 7a75c73052 | |||
| 658f2a13ea | |||
| c1395ab543 | |||
| cd6d86a5ce | |||
| 8b2d067196 | |||
| 07a5538e50 | |||
| d17dc54645 | |||
| baa8895cfb | |||
| 550d6b2991 | |||
| b3649a44e0 | |||
| 313117095c | |||
| 7221051683 | |||
| 1eb2ecb3b0 | |||
| 24b0672d99 | |||
| 08c7429531 | |||
| aa05eb4c81 | |||
| 4aa178fcc0 | |||
| 98ca880f8a | |||
| fe21ef43ba |
@@ -6,18 +6,18 @@ jobs:
|
||||
name: coverage
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: xd009642/tarpaulin
|
||||
image: xd009642/tarpaulin:develop-nightly
|
||||
options: --security-opt seccomp=unconfined
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v3
|
||||
uses: actions/checkout@main
|
||||
|
||||
- name: Generate coverage report
|
||||
run: |
|
||||
cargo tarpaulin --out xml --tests --exclude-files benches/* --exclude-files mlua-sys/src/*/*
|
||||
cargo +nightly tarpaulin --verbose --out xml --tests --exclude-files benches/* --exclude-files mlua-sys/src/*/*
|
||||
|
||||
- name: Upload report to codecov.io
|
||||
uses: codecov/codecov-action@v3
|
||||
uses: codecov/codecov-action@v4
|
||||
with:
|
||||
token: ${{secrets.CODECOV_TOKEN}}
|
||||
fail_ci_if_error: false
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
name: Documentation (main)
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
workflow_dispatch:
|
||||
|
||||
# Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages
|
||||
permissions:
|
||||
contents: read
|
||||
pages: write
|
||||
id-token: write
|
||||
|
||||
# Allow only one concurrent deployment
|
||||
concurrency:
|
||||
group: pages
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
build:
|
||||
name: Build Documentation
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@main
|
||||
- uses: dtolnay/rust-toolchain@nightly
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
|
||||
- name: Build documentation
|
||||
env:
|
||||
RUSTDOCFLAGS: "--cfg docsrs"
|
||||
run: |
|
||||
cargo +nightly doc --no-deps \
|
||||
--features "lua55,vendored,async,send,serde,macros,anyhow,userdata-wrappers"
|
||||
|
||||
- name: Create index redirect
|
||||
run: |
|
||||
echo '<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>Redirecting to mlua documentation</title>
|
||||
<meta http-equiv="refresh" content="0; URL=mlua/index.html">
|
||||
<link rel="canonical" href="mlua/index.html">
|
||||
</head>
|
||||
<body>
|
||||
<p>Redirecting to <a href="mlua/index.html">mlua documentation</a>...</p>
|
||||
</body>
|
||||
</html>' > target/doc/index.html
|
||||
|
||||
- name: Setup Pages
|
||||
uses: actions/configure-pages@v5
|
||||
|
||||
- name: Upload artifact
|
||||
uses: actions/upload-pages-artifact@v4
|
||||
with:
|
||||
path: target/doc
|
||||
|
||||
deploy:
|
||||
name: Deploy to GitHub Pages
|
||||
environment:
|
||||
name: github-pages
|
||||
url: ${{ steps.deployment.outputs.page_url }}
|
||||
runs-on: ubuntu-latest
|
||||
needs: build
|
||||
steps:
|
||||
- name: Deploy to GitHub Pages
|
||||
id: deployment
|
||||
uses: actions/deploy-pages@v4
|
||||
+111
-66
@@ -7,18 +7,18 @@ jobs:
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
matrix:
|
||||
os: [ubuntu-22.04, macos-latest, windows-latest]
|
||||
os: [ubuntu-latest, macos-latest, windows-latest]
|
||||
rust: [stable]
|
||||
lua: [lua54, lua53, lua52, lua51, luajit, luau, luau-jit, luau-vector4]
|
||||
lua: [lua55, lua54, lua53, lua52, lua51, luajit, luau, luau-jit, luau-vector4]
|
||||
include:
|
||||
- os: ubuntu-22.04
|
||||
- os: ubuntu-latest
|
||||
target: x86_64-unknown-linux-gnu
|
||||
- os: macos-latest
|
||||
target: x86_64-apple-darwin
|
||||
target: aarch64-apple-darwin
|
||||
- os: windows-latest
|
||||
target: x86_64-pc-windows-msvc
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@main
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
toolchain: ${{ matrix.rust }}
|
||||
@@ -27,40 +27,25 @@ jobs:
|
||||
- name: Build ${{ matrix.lua }} vendored
|
||||
run: |
|
||||
cargo build --features "${{ matrix.lua }},vendored"
|
||||
cargo build --features "${{ matrix.lua }},vendored,async,send,serialize,macros,parking_lot,unstable"
|
||||
cargo build --features "${{ matrix.lua }},vendored,async,serde,macros,anyhow,userdata-wrappers"
|
||||
cargo build --features "${{ matrix.lua }},vendored,async,serde,macros,anyhow,userdata-wrappers,send"
|
||||
shell: bash
|
||||
- name: Build ${{ matrix.lua }} pkg-config
|
||||
if: ${{ matrix.os == 'ubuntu-22.04' }}
|
||||
if: ${{ matrix.os == 'ubuntu-latest' && matrix.lua != 'lua55' }}
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y --no-install-recommends liblua5.4-dev liblua5.3-dev liblua5.2-dev liblua5.1-0-dev libluajit-5.1-dev
|
||||
cargo build --features "${{ matrix.lua }}"
|
||||
|
||||
build_aarch64_cross_macos:
|
||||
name: Cross-compile to aarch64-apple-darwin
|
||||
runs-on: macos-latest
|
||||
needs: build
|
||||
strategy:
|
||||
matrix:
|
||||
lua: [lua54, lua53, lua52, lua51, luajit]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
toolchain: stable
|
||||
target: aarch64-apple-darwin
|
||||
- name: Cross-compile
|
||||
run: cargo build --target aarch64-apple-darwin --features "${{ matrix.lua }},vendored,async,send,serialize,macros,parking_lot,unstable"
|
||||
|
||||
build_aarch64_cross_ubuntu:
|
||||
name: Cross-compile to aarch64-unknown-linux-gnu
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-latest
|
||||
needs: build
|
||||
strategy:
|
||||
matrix:
|
||||
lua: [lua54, lua53, lua52, lua51, luajit]
|
||||
lua: [lua55, lua54, lua53, lua52, lua51, luajit]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@main
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
toolchain: stable
|
||||
@@ -71,18 +56,18 @@ jobs:
|
||||
sudo apt-get install -y --no-install-recommends gcc-aarch64-linux-gnu libc6-dev-arm64-cross
|
||||
shell: bash
|
||||
- name: Cross-compile
|
||||
run: cargo build --target aarch64-unknown-linux-gnu --features "${{ matrix.lua }},vendored,async,send,serialize,macros,parking_lot,unstable"
|
||||
run: cargo build --target aarch64-unknown-linux-gnu --features "${{ matrix.lua }},vendored,async,send,serde,macros,anyhow,userdata-wrappers"
|
||||
shell: bash
|
||||
|
||||
build_armv7_cross_ubuntu:
|
||||
name: Cross-compile to armv7-unknown-linux-gnueabihf
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-latest
|
||||
needs: build
|
||||
strategy:
|
||||
matrix:
|
||||
lua: [lua54, lua53, lua52, lua51]
|
||||
lua: [lua55, lua54, lua53, lua52, lua51]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@main
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
toolchain: stable
|
||||
@@ -93,7 +78,7 @@ jobs:
|
||||
sudo apt-get install -y --no-install-recommends gcc-arm-linux-gnueabihf libc-dev-armhf-cross
|
||||
shell: bash
|
||||
- name: Cross-compile
|
||||
run: cargo build --target armv7-unknown-linux-gnueabihf --features "${{ matrix.lua }},vendored,async,send,serialize,macros,parking_lot,unstable"
|
||||
run: cargo build --target armv7-unknown-linux-gnueabihf --features "${{ matrix.lua }},vendored,async,send,serde,macros,anyhow,userdata-wrappers"
|
||||
shell: bash
|
||||
|
||||
test:
|
||||
@@ -102,18 +87,18 @@ jobs:
|
||||
needs: build
|
||||
strategy:
|
||||
matrix:
|
||||
os: [ubuntu-22.04, macos-latest, windows-latest]
|
||||
os: [ubuntu-latest, macos-latest, windows-latest]
|
||||
rust: [stable, nightly]
|
||||
lua: [lua54, lua53, lua52, lua51, luajit, luajit52, luau, luau-jit, luau-vector4]
|
||||
lua: [lua55, lua54, lua53, lua52, lua51, luajit, luajit52, luau, luau-jit, luau-vector4]
|
||||
include:
|
||||
- os: ubuntu-22.04
|
||||
- os: ubuntu-latest
|
||||
target: x86_64-unknown-linux-gnu
|
||||
- os: macos-latest
|
||||
target: x86_64-apple-darwin
|
||||
target: aarch64-apple-darwin
|
||||
- os: windows-latest
|
||||
target: x86_64-pc-windows-msvc
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@main
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
toolchain: ${{ matrix.rust }}
|
||||
@@ -122,14 +107,14 @@ jobs:
|
||||
- name: Run ${{ matrix.lua }} tests
|
||||
run: |
|
||||
cargo test --features "${{ matrix.lua }},vendored"
|
||||
cargo test --features "${{ matrix.lua }},vendored,async,send,serialize,macros,parking_lot"
|
||||
cargo test --features "${{ matrix.lua }},vendored,async,serialize,macros,parking_lot,unstable"
|
||||
cargo test --features "${{ matrix.lua }},vendored,async,serde,macros,anyhow,userdata-wrappers"
|
||||
cargo test --features "${{ matrix.lua }},vendored,async,serde,macros,anyhow,userdata-wrappers,send"
|
||||
shell: bash
|
||||
- name: Run compile tests (macos lua54)
|
||||
if: ${{ matrix.os == 'macos-latest' && matrix.lua == 'lua54' }}
|
||||
- name: Run compile tests (macos lua55)
|
||||
if: ${{ matrix.os == 'macos-latest' && matrix.lua == 'lua55' }}
|
||||
run: |
|
||||
TRYBUILD=overwrite cargo test --features "${{ matrix.lua }},vendored" -- --ignored
|
||||
TRYBUILD=overwrite cargo test --features "${{ matrix.lua }},vendored,async,send,serialize,macros,parking_lot,unstable" -- --ignored
|
||||
TRYBUILD=overwrite cargo test --features "${{ matrix.lua }},vendored" --tests -- --ignored
|
||||
TRYBUILD=overwrite cargo test --features "${{ matrix.lua }},vendored,async,send,serde,macros" --tests -- --ignored
|
||||
shell: bash
|
||||
|
||||
test_with_sanitizer:
|
||||
@@ -138,14 +123,14 @@ jobs:
|
||||
needs: build
|
||||
strategy:
|
||||
matrix:
|
||||
os: [ubuntu-22.04]
|
||||
os: [ubuntu-latest]
|
||||
rust: [nightly]
|
||||
lua: [lua54, lua53, lua52, lua51, luajit, luau, luau-jit, luau-vector4]
|
||||
lua: [lua55, lua54, lua53, lua52, lua51, luajit, luau, luau-jit, luau-vector4]
|
||||
include:
|
||||
- os: ubuntu-22.04
|
||||
- os: ubuntu-latest
|
||||
target: x86_64-unknown-linux-gnu
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@main
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
toolchain: ${{ matrix.rust }}
|
||||
@@ -153,27 +138,54 @@ jobs:
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
- name: Run ${{ matrix.lua }} tests with address sanitizer
|
||||
run: |
|
||||
cargo test --tests --features "${{ matrix.lua }},vendored,async,send,serialize,macros,parking_lot,unstable" --target x86_64-unknown-linux-gnu -- --skip test_too_many_recursions
|
||||
cargo test --tests --features "${{ matrix.lua }},vendored,async,serde,macros,anyhow" --target x86_64-unknown-linux-gnu -- --skip test_too_many_recursions
|
||||
cargo test --tests --features "${{ matrix.lua }},vendored,async,serde,macros,anyhow,userdata-wrappers,send" --target x86_64-unknown-linux-gnu -- --skip test_too_many_recursions
|
||||
shell: bash
|
||||
env:
|
||||
RUSTFLAGS: -Z sanitizer=address
|
||||
|
||||
test_with_memory_limit:
|
||||
name: Test with memory limit
|
||||
runs-on: ${{ matrix.os }}
|
||||
needs: build
|
||||
strategy:
|
||||
matrix:
|
||||
os: [ubuntu-latest]
|
||||
rust: [nightly]
|
||||
lua: [lua55, lua54, lua53, lua52, lua51, luajit, luau, luau-jit, luau-vector4]
|
||||
include:
|
||||
- os: ubuntu-latest
|
||||
target: x86_64-unknown-linux-gnu
|
||||
steps:
|
||||
- uses: actions/checkout@main
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
toolchain: ${{ matrix.rust }}
|
||||
target: ${{ matrix.target }}
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
- name: Run ${{ matrix.lua }} tests with forced memory limit
|
||||
run: |
|
||||
cargo test --tests --features "${{ matrix.lua }},vendored,async,send,serde,macros,anyhow,userdata-wrappers"
|
||||
shell: bash
|
||||
env:
|
||||
RUSTFLAGS: --cfg=force_memory_limit
|
||||
|
||||
test_modules:
|
||||
name: Test modules
|
||||
runs-on: ${{ matrix.os }}
|
||||
needs: build
|
||||
strategy:
|
||||
matrix:
|
||||
os: [ubuntu-22.04, macos-latest]
|
||||
os: [ubuntu-latest, macos-latest]
|
||||
rust: [stable]
|
||||
lua: [lua54, lua53, lua52, lua51, luajit, luau]
|
||||
lua: [lua55, lua54, lua53, lua52, lua51, luajit]
|
||||
include:
|
||||
- os: ubuntu-22.04
|
||||
- os: ubuntu-latest
|
||||
target: x86_64-unknown-linux-gnu
|
||||
- os: macos-latest
|
||||
target: x86_64-apple-darwin
|
||||
target: aarch64-apple-darwin
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@main
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
toolchain: ${{ matrix.rust }}
|
||||
@@ -197,7 +209,7 @@ jobs:
|
||||
shell: msys2 {0}
|
||||
steps:
|
||||
- uses: msys2/setup-msys2@v2
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@main
|
||||
- name: Install Rust & Lua
|
||||
run: |
|
||||
pacman -S --noconfirm mingw-w64-x86_64-rust mingw-w64-x86_64-lua mingw-w64-x86_64-luajit mingw-w64-x86_64-pkg-config
|
||||
@@ -208,13 +220,13 @@ jobs:
|
||||
|
||||
test_wasm32_emscripten:
|
||||
name: Test on wasm32-unknown-emscripten
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-latest
|
||||
needs: build
|
||||
strategy:
|
||||
matrix:
|
||||
lua: [lua54, lua53, lua52, lua51, luau]
|
||||
lua: [lua55, lua54, lua53, lua52, lua51, luau]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@main
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
toolchain: stable
|
||||
@@ -226,28 +238,61 @@ jobs:
|
||||
- name: Run ${{ matrix.lua }} tests
|
||||
run: |
|
||||
cargo test --tests --features "${{ matrix.lua }},vendored"
|
||||
cargo test --tests --features "${{ matrix.lua }},vendored,async,send,serialize,macros,parking_lot"
|
||||
cargo test --tests --features "${{ matrix.lua }},vendored,async,serialize,macros,parking_lot,unstable"
|
||||
cargo test --tests --features "${{ matrix.lua }},vendored,async,serde,macros,anyhow,userdata-wrappers"
|
||||
|
||||
test_wasm32_wasip2:
|
||||
name: Test on wasm32-wasip2
|
||||
runs-on: ubuntu-latest
|
||||
needs: build
|
||||
strategy:
|
||||
matrix:
|
||||
lua: [lua55, lua54, lua53, lua52, lua51]
|
||||
steps:
|
||||
- uses: actions/checkout@main
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
toolchain: nightly-2025-10-02
|
||||
target: wasm32-wasip2
|
||||
- name: Install wasi-sdk/Wasmtime
|
||||
working-directory: ${{ runner.tool_cache }}
|
||||
run: |
|
||||
wasi_sdk=29
|
||||
wasmtime=v40.0.1
|
||||
|
||||
curl -LO https://github.com/WebAssembly/wasi-sdk/releases/download/wasi-sdk-$wasi_sdk/wasi-sdk-$wasi_sdk.0-x86_64-linux.tar.gz
|
||||
tar xf wasi-sdk-$wasi_sdk.0-x86_64-linux.tar.gz
|
||||
WASI_SDK_PATH=`pwd`/wasi-sdk-$wasi_sdk.0-x86_64-linux
|
||||
echo "WASI_SDK_PATH=$WASI_SDK_PATH" >> $GITHUB_ENV
|
||||
echo "CC_wasm32_wasip2=$WASI_SDK_PATH/bin/clang" >> $GITHUB_ENV
|
||||
echo "CARGO_TARGET_WASM32_WASIP2_LINKER=$WASI_SDK_PATH/bin/clang" >> $GITHUB_ENV
|
||||
echo "CARGO_TARGET_WASM32_WASIP2_RUSTFLAGS=-Clink-arg=-Wl,--export=cabi_realloc" >> $GITHUB_ENV
|
||||
|
||||
curl -LO https://github.com/bytecodealliance/wasmtime/releases/download/$wasmtime/wasmtime-$wasmtime-x86_64-linux.tar.xz
|
||||
tar xf wasmtime-$wasmtime-x86_64-linux.tar.xz
|
||||
echo "CARGO_TARGET_WASM32_WASIP2_RUNNER=`pwd`/wasmtime-$wasmtime-x86_64-linux/wasmtime -W exceptions" >> $GITHUB_ENV
|
||||
- name: Run ${{ matrix.lua }} tests
|
||||
run: |
|
||||
cargo test --target wasm32-wasip2 --tests --features "${{ matrix.lua }},vendored"
|
||||
cargo test --target wasm32-wasip2 --tests --features "${{ matrix.lua }},vendored,serde,macros,anyhow,userdata-wrappers"
|
||||
|
||||
rustfmt:
|
||||
name: Rustfmt
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- uses: actions/checkout@main
|
||||
- uses: dtolnay/rust-toolchain@nightly
|
||||
with:
|
||||
toolchain: stable
|
||||
components: rustfmt
|
||||
- run: cargo fmt -- --check
|
||||
|
||||
clippy:
|
||||
name: Clippy
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
lua: [lua54, lua53, lua52, lua51, luajit, luau, luau-jit, luau-vector4]
|
||||
lua: [lua55, lua54, lua53, lua52, lua51, luajit, luau, luau-jit, luau-vector4]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@main
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
toolchain: nightly
|
||||
@@ -255,4 +300,4 @@ jobs:
|
||||
- uses: giraffate/clippy-action@v1
|
||||
with:
|
||||
reporter: 'github-pr-review'
|
||||
clippy_flags: --features "${{ matrix.lua }},vendored,async,send,serialize,macros,parking_lot,unstable"
|
||||
clippy_flags: --features "${{ matrix.lua }},vendored,async,send,serde,macros,anyhow,userdata-wrappers"
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
name: Spelling Check
|
||||
on:
|
||||
pull_request:
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
env:
|
||||
CLICOLOR: 1
|
||||
|
||||
jobs:
|
||||
spelling:
|
||||
name: Spell Check with Typos
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout Actions Repository
|
||||
uses: actions/checkout@main
|
||||
- name: Check spelling
|
||||
uses: crate-ci/typos@v1.42.1
|
||||
with:
|
||||
config: ./typos.toml
|
||||
+221
-4
@@ -1,3 +1,220 @@
|
||||
## v0.12.0-rc.2 (Jun 06, 2026)
|
||||
|
||||
- Add `#[derive(UserData)]` and `#[mlua::userdata_impl]` macros
|
||||
- Support thread create/resume/yield callbacks for all Lua versions (including Luau)
|
||||
- Support `to_alias_override`/`to_alias_fallback` in `Require` trait (Luau)
|
||||
- Prevent `XRc` overflow when dropping `RawLua` with foreign Lua state
|
||||
- implement `Not` for `StdLib` (#699)
|
||||
- Fix `String::to_pointer` return NULL in Lua <5.4
|
||||
|
||||
## v0.12.0-rc.1 (Apr 21, 2026)
|
||||
|
||||
- Rust 2024 edition
|
||||
- Removed `Error::ToLuaConversionError` variant as it was unused (and not practically useful)
|
||||
- New modules to group data types: `chunk`, `debug`, `error`, `function`, `table`, `string`, `state`, `thread`, `userdata`, `luau`
|
||||
- Support `__todebugstring` metamethod for pretty formatting userdata value (for debugging)
|
||||
- New `MaybeSync` trait that is required for userdata types
|
||||
- Removed lifetime from `BorrowedStr` and `BorrowedBytes`
|
||||
- New `Thread` methods: `is_resumable`, `is_running`, `is_finished`, `is_error`
|
||||
- Added `Thread::state` to get raw Lua state pointer
|
||||
- Luau `TextRequirer` is renamed to `FsRequirer`
|
||||
- GC interface refactor: `Lua::gc_inc/Lua::gc_gen` is replaced with `gc_set_mode`
|
||||
- Added `GcIncParams` and `GcGenParams` for GC tuning
|
||||
- New `UserDataMethods::add_method_once` and `UserDataMethods::add_async_method_once`
|
||||
- Initial Luau integer64 type support
|
||||
- Changed interface of `Function::wrap/wrap_mut/wrap_async` to support any Error type
|
||||
- Changed `AnyUserData::type_name` to return `LuaString` instead
|
||||
- Added `UserDataOwned<T>` wrapper to take ownership of userdata `T` and implements `FromLua`
|
||||
|
||||
## v0.11.6 (Jan 27, 2026)
|
||||
|
||||
- Added Lua 5.5 support (`lua55` feature flag)
|
||||
- Luau updated to 0.705+
|
||||
- Added `AnyUserData::is_proxy` method to check if userdata is a proxy
|
||||
- Added `num_params`, `num_upvalues`, `is_vararg` to `FunctionInfo`
|
||||
|
||||
## v0.11.5 (Nov 22, 2025)
|
||||
|
||||
- Luau updated to 0.701
|
||||
- Added `Lua::set_memory_category` and `Lua::heap_dump` functions to profile (Luau) memory
|
||||
- Added `Lua::type_metatable` helper to get metatable of a primitive type
|
||||
- Added `Lua::traceback` function to generate stack traces at different levels
|
||||
- Added `add_method_once` /`add_async_method_once` UserData methods (experimental)
|
||||
- Make `AnyUserData::type_name` public
|
||||
- impl `IntoLuaMulti` for `&MultiValue`
|
||||
- Bugfixes and async perf improvements
|
||||
|
||||
## v0.11.4 (Sep 29, 2025)
|
||||
|
||||
- Make `Value::to_serializable` public
|
||||
- Add new serde option `detect_mixed_tables` (to encode mixed array+map tables)
|
||||
- Add `ObjectLike::get_path` helper (for tables and userdata)
|
||||
|
||||
## v0.11.3 (Aug 30, 2025)
|
||||
|
||||
- Add `Lua::yield_with` to use as `coroutine.yield` functional replacement in async functions for any Lua
|
||||
- Do not try to yield at non-yielable points in Luau interrupt (#632)
|
||||
- Add `Buffer::cursor` method (Luau)
|
||||
- Add `Lua::create_buffer_with_capacity` method (Luau)
|
||||
- Make Lua reference values cheap to clone (only increments ref count)
|
||||
- Fix panic on large (>67M entries) table creation
|
||||
|
||||
## v0.11.2 (Aug 10, 2025)
|
||||
|
||||
- Faster stack push for `Variadic<T>`
|
||||
- Fix handling Windows paths with drive letter in Luau require (#623)
|
||||
- Make Luau registered aliases ascii case-insensitive (#620)
|
||||
- Fix deserializing negative zeros `-0.0` (#618)
|
||||
|
||||
## v0.11.1 (Jul 15, 2025)
|
||||
|
||||
- Fixed bug exhausting Lua auxiliary stack and leaving it without reserve (#615)
|
||||
- `Lua::push_c_function` now correctly handles OOM for Lua 5.1 and Luau
|
||||
|
||||
## v0.11.0 (Jul 14, 2025)
|
||||
|
||||
Changes since v0.11.0-beta.3
|
||||
|
||||
- Allow linking external Lua libraries in a build script (e.g. pluto) using `external` mlua-sys feature flag
|
||||
- `Lua::inspect_stack` takes a callback with `&Debug` argument, instead of returning `Debug` directly
|
||||
- Added `Debug::function` method to get function running at a given level
|
||||
- `Debug::curr_line` is deprecated in favour of `Debug::current_line` that returns `Option<usize>`
|
||||
- Added `Lua::set_globals` method to replace global environment
|
||||
- `Table::set_metatable` now returns `Result<()>` (this operation can fail in sandboxed Luau mode)
|
||||
- `impl ToString` replaced with `Into<StdString>` in `UserData` registration
|
||||
- `Value::as_str` and `Value::as_string_lossy` methods are deprecated (as they are non-idiomatic)
|
||||
- Bugfixes and improvements
|
||||
|
||||
## v0.11.0-beta.3 (Jun 23, 2025)
|
||||
|
||||
- Luau in sandboxed mode has reduced options in `collectgarbage` function (to follow the official doc)
|
||||
- `Function::deep_clone` now returns `Result<Function>` as this operation can trigger memory errors
|
||||
- Luau "Require" resolves included Lua files relative to the current directory (#605)
|
||||
- Fixed bug when finalizing `AsyncThread` on drop (`call_async` methods family)
|
||||
|
||||
## v0.11.0-beta.2 (Jun 12, 2025)
|
||||
|
||||
- Lua 5.4 updated to 5.4.8
|
||||
- Terminate Rust `Future` when `AsyncThread` is dropped (without relying on Lua GC)
|
||||
- Added `loadstring` function to Luau
|
||||
- Make `AsChunk` trait dyn-friendly
|
||||
- Luau `Require` trait synced with Luau 0.674
|
||||
- Luau `Require` trait methods now can return `Error` variant (in `NavigateError` enum)
|
||||
- Added `__type` to `Error`'s userdata metatable (for `typeof` function)
|
||||
- `parking_log/send_guard` is moved to `userdata-wrappers` feature flag
|
||||
- New `serde` feature flag to replace `serialize` (the old one is still available)
|
||||
|
||||
## v0.11.0-beta.1 (May 7th, 2025)
|
||||
|
||||
- New "require-by-string" for Luau (with `Require` trait and async support)
|
||||
- Added `Thread::resume_error` support for Luau
|
||||
- 52 bit integers support for Luau (this is a breaking change)
|
||||
- New features for Luau compiler (constants, disabled builtins, known members)
|
||||
- `AsyncThread<A, R>` changed to `AsyncThread<R>` (`A` pushed to stack immediately)
|
||||
- Lifetime `'a` moved from `AsChunk<'a>` to `AsChunk::source where Self: 'a`
|
||||
- `Lua::scope` pass `&Scope` instead of `&mut Scope` to closure
|
||||
- Added global hooks support (Lua 5.1+)
|
||||
- Added per-thread hooks support (Lua 5.1+)
|
||||
- `Lua::init_from_ptr` renamed to `Lua::get_or_init_from_ptr` and returns `&Lua`
|
||||
- `Lua:load_from_function` is deprecated (this is `register_module` now)
|
||||
- Added `Lua::register_module` and `Lua::preload_module`
|
||||
|
||||
## v0.10.4 (May 5th, 2025)
|
||||
|
||||
- Luau updated to 0.672
|
||||
- New serde option `encode_empty_tables_as_array` to serialize empty tables as arrays
|
||||
- Added `WeakLua` and `Lua::weak()` to create weak references to Lua state
|
||||
- Trigger abort when Luau userdata destructors are panic (Luau GC does not support it)
|
||||
- Added `AnyUserData::type_id()` method to get the type id of the userdata
|
||||
- Added `Chunk::name()`, `Chunk::environment()` and `Chunk::mode()` functions
|
||||
- Support borrowing underlying wrapped types for `UserDataRef` and `UserDataRefMut` (under `userdata-wrappers` feature)
|
||||
- Added large (52bit) integers support for Luau
|
||||
- Enable `serde` for `bstr` if `serialize` feature flag is enabled
|
||||
- Recursive warnings (Lua 5.4) are no longer allowed
|
||||
- Implemented `IntoLua`/`FromLua` for `BorrowedString` and `BorrowedBytes`
|
||||
- Implemented `IntoLua`/`FromLua` for `char`
|
||||
- Enable `Thread::reset()` for all Lua versions (limited support for 5.1-5.3)
|
||||
- Bugfixes and improvements
|
||||
|
||||
## v0.10.3 (Jan 27th, 2025)
|
||||
|
||||
- Set `Default` for `Value` to be `Nil`
|
||||
- Allow exhaustive match on `Value` (#502)
|
||||
- Add `Table::set_safeenv` method (Luau)
|
||||
|
||||
## v0.10.2 (Dec 1st, 2024)
|
||||
|
||||
- Switch proc-macro-error to proc-macro-error2 (#493)
|
||||
- Do not allow Lua to run GC finalizers on ref thread (#491)
|
||||
- Fix chunks loading in Luau when memory limit is enforced (#488)
|
||||
- Added `String::wrap` method to wrap arbitrary `AsRef<[u8]>` into `impl IntoLua`
|
||||
- Better FreeBSD/OpenBSD support (thanks to cos)
|
||||
- Delay "any" userdata metatable creation until first instance is created (#482)
|
||||
- Reduce amount of generated code for `UserData` (less generics)
|
||||
|
||||
## v0.10.1 (Nov 9th, 2024)
|
||||
|
||||
- Minimal Luau updated to 0.650
|
||||
- Added Luau native vector library support (this can change behavior if you use `vector` function!)
|
||||
- Added Lua `String::display` method
|
||||
- Improved pretty-printing for Lua tables (#478)
|
||||
- Added `Scope::create_any_userdata` to create Lua objects from any non-`'static` Rust types
|
||||
- Added `AnyUserData::destroy` method
|
||||
- New `userdata-wrappers` feature to `impl UserData` for `Rc<T>`/`Arc<T>`/`Rc<RefCell<T>>`/`Arc<Mutex<T>>` (similar to v0.9)
|
||||
- `UserDataRef` in `send` mode now uses shared lock if `T: Sync` (and exclusive lock otherwise)
|
||||
- Added `Scope::add_destructor` to attach custom destructors
|
||||
- Added `Lua::try_app_data_ref` and `Lua::try_app_data_mut` methods
|
||||
- Added `From<Vec>` and `Into<Vec>` support to `MultiValue` and `Variadic` types
|
||||
- Bug fixes and improvements (#477 #479)
|
||||
|
||||
## v0.10.0 (Oct 25th, 2024)
|
||||
|
||||
Changes since v0.10.0-rc.1
|
||||
|
||||
- Added `error-send` feature flag (disabled by default) to require `Send + Sync` for `Error`
|
||||
- Some performance improvements
|
||||
|
||||
## v0.10.0-rc.1
|
||||
|
||||
- `Lua::scope` is back
|
||||
- Support yielding from hooks for Lua 5.3+
|
||||
- Support setting metatable for Lua builtin types (number/string/function/etc)
|
||||
- Added `LuaNativeFn`/`LuaNativeFnMut`/`LuaNativeAsyncFn` traits for using in `Function::wrap`
|
||||
- Added `Error::chain` method to return iterator over nested errors
|
||||
- Added `Lua::exec_raw` helper to execute low-level Lua C API code
|
||||
- Added `Either<L, R>` enum to combine two types into a single one
|
||||
- Added a new `Buffer` type for Luau
|
||||
- Added `Value::is_error` and `Value::as_error` helpers
|
||||
- Added `Value::Other` variant to represent unknown Lua types (eg LuaJIT CDATA)
|
||||
- Added (optional) `anyhow` feature to implement `IntoLua` for `anyhow::Error`
|
||||
- Added `IntoLua`/`FromLua` for `OsString`/`OsStr` and `PathBuf`/`Path`
|
||||
|
||||
## v0.10.0-beta.2
|
||||
|
||||
- Updated `ThreadStatus` enum to include `Running` and `Finished` variants.
|
||||
- `Error::CoroutineInactive` renamed to `Error::CoroutineUnresumable`.
|
||||
- `IntoLua`/`IntoLuaMulti` now uses `impl trait` syntax for args (shorten from `a.get::<_, T>` to `a.get::<T>`).
|
||||
- Removed undocumented `Lua::into_static`/`from_static` methods.
|
||||
- Futures now require `Send` bound if `send` feature is enabled.
|
||||
- Dropped lifetime from `UserDataMethods` and `UserDataFields` traits.
|
||||
- `Compiler::compile()` now returns `Result` (Luau).
|
||||
- Removed `Clone` requirement from `UserDataFields::add_field()`.
|
||||
- `TableExt` and `AnyUserDataExt` traits were combined into `ObjectLike` trait.
|
||||
- Disabled `send` feature in module mode (since we don't have exclusive access to Lua).
|
||||
- `Chunk::set_environment()` takes `Table` instead of `IntoLua` type.
|
||||
- Reduced the compile time contribution of `next_key_seed` and `next_value_seed`.
|
||||
- Reduced the compile time contribution of `serde_userdata`.
|
||||
- Performance improvements.
|
||||
|
||||
## v0.10.0-beta.1
|
||||
|
||||
- Dropped `'lua` lifetime (subtypes now store a weak reference to Lua)
|
||||
- Removed (experimental) owned types (they no longer needed)
|
||||
- Make Lua types truly `Send` and `Sync` (when enabling `send` feature flag)
|
||||
- Removed `UserData` impl for Rc/Arc types ("any" userdata functions can be used instead)
|
||||
- `Lua::replace_registry_value` takes `&mut RegistryKey`
|
||||
- `Lua::scope` temporary disabled (will be re-added in the next release)
|
||||
|
||||
## v0.9.9
|
||||
|
||||
- Minimal Luau updated to 0.629
|
||||
@@ -225,7 +442,7 @@ Other:
|
||||
|
||||
## v0.8.0
|
||||
Changes since 0.7.4
|
||||
- Roblox Luau support
|
||||
- Luau support
|
||||
- Removed C glue
|
||||
- Added async support to `__index` and `__newindex` metamethods
|
||||
- Added `Function::info()` to get information about functions (#149).
|
||||
@@ -275,7 +492,7 @@ Breaking changes:
|
||||
|
||||
## v0.8.0-beta.1
|
||||
|
||||
- Roblox Luau support
|
||||
- Luau support
|
||||
- Refactored ffi module. C glue is no longer required
|
||||
- Added async support to `__index` and `__newindex` metamethods
|
||||
|
||||
@@ -388,7 +605,7 @@ Breaking changes:
|
||||
- [**Breaking**] Removed `AnyUserData::has_metamethod()`
|
||||
- Added `Thread::reset()` for luajit/lua54 to recycle threads.
|
||||
It's possible to attach a new function to a thread (coroutine).
|
||||
- Added `chunk!` macro support to load chunks of Lua code using the Rust tokenizer and optinally capturing Rust variables.
|
||||
- Added `chunk!` macro support to load chunks of Lua code using the Rust tokenizer and optionally capturing Rust variables.
|
||||
- Improved error reporting (`Error`'s `__tostring` method formats full stacktraces). This is useful in the module mode.
|
||||
|
||||
## v0.6.0-beta.1
|
||||
@@ -444,7 +661,7 @@ Breaking changes:
|
||||
|
||||
- Lua 5.4 support with `MetaMethod::Close`.
|
||||
- `lua53` feature is disabled by default. Now preferred Lua version have to be chosen explicitly.
|
||||
- Provide safety guaraness for Lua state, which means that potenially unsafe operations, like loading C modules (using `require` or `package.loadlib`) are disabled. Equalient for the previous `Lua::new()` function is `Lua::unsafe_new()`.
|
||||
- Provide safety guarantees for Lua state, which means that potentially unsafe operations, like loading C modules (using `require` or `package.loadlib`) are disabled. Equivalent to the previous `Lua::new()` function is `Lua::unsafe_new()`.
|
||||
- New `send` feature to require `Send`.
|
||||
- New `module` feature, that disables linking to Lua Core Libraries. Required for modules.
|
||||
- Don't allow `'callback` outlive `'lua` in `Lua::create_function()` to fix [the unsoundness](tests/compile/static_callback_args.rs).
|
||||
|
||||
+39
-34
@@ -1,22 +1,22 @@
|
||||
[package]
|
||||
name = "mlua"
|
||||
version = "0.9.9" # remember to update mlua_derive
|
||||
version = "0.12.0-rc.2" # remember to update mlua_derive
|
||||
authors = ["Aleksandr Orlenko <zxteam@pm.me>", "kyren <catherine@kyju.org>"]
|
||||
rust-version = "1.71"
|
||||
edition = "2021"
|
||||
repository = "https://github.com/khvzak/mlua"
|
||||
rust-version = "1.88"
|
||||
edition = "2024"
|
||||
repository = "https://github.com/mlua-rs/mlua"
|
||||
documentation = "https://docs.rs/mlua"
|
||||
readme = "README.md"
|
||||
keywords = ["lua", "luajit", "luau", "async", "scripting"]
|
||||
categories = ["api-bindings", "asynchronous"]
|
||||
license = "MIT"
|
||||
description = """
|
||||
High level bindings to Lua 5.4/5.3/5.2/5.1 (including LuaJIT) and Roblox Luau
|
||||
High level bindings to Lua 5.5/5.4/5.3/5.2/5.1 (including LuaJIT) and Luau
|
||||
with async/await features and support of writing native Lua modules in Rust.
|
||||
"""
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
features = ["lua54", "vendored", "async", "send", "serialize", "macros", "parking_lot", "unstable"]
|
||||
features = ["lua55", "vendored", "async", "send", "serde", "macros"]
|
||||
rustdoc-args = ["--cfg", "docsrs"]
|
||||
|
||||
[workspace]
|
||||
@@ -26,57 +26,62 @@ members = [
|
||||
]
|
||||
|
||||
[features]
|
||||
lua55 = ["ffi/lua55"]
|
||||
lua54 = ["ffi/lua54"]
|
||||
lua53 = ["ffi/lua53"]
|
||||
lua52 = ["ffi/lua52"]
|
||||
lua51 = ["ffi/lua51"]
|
||||
luajit = ["ffi/luajit"]
|
||||
luajit52 = ["luajit", "ffi/luajit52"]
|
||||
luau = ["ffi/luau", "dep:libloading"]
|
||||
luau = ["ffi/luau"]
|
||||
luau-jit = ["luau", "ffi/luau-codegen"]
|
||||
luau-vector4 = ["luau", "ffi/luau-vector4"]
|
||||
vendored = ["ffi/vendored"]
|
||||
module = ["dep:mlua_derive", "ffi/module"]
|
||||
module = ["mlua_derive", "ffi/module"]
|
||||
async = ["dep:futures-util"]
|
||||
send = []
|
||||
serialize = ["dep:serde", "dep:erased-serde", "dep:serde-value"]
|
||||
macros = ["mlua_derive/macros"]
|
||||
unstable = []
|
||||
send = ["error-send"]
|
||||
error-send = []
|
||||
serde = ["dep:serde", "dep:erased-serde", "dep:serde-value", "bstr/serde"]
|
||||
macros = ["mlua_derive/macros", "dep:inventory"]
|
||||
anyhow = ["dep:anyhow", "error-send"]
|
||||
userdata-wrappers = ["parking_lot/send_guard"]
|
||||
|
||||
# deprecated features
|
||||
serialize = ["serde"]
|
||||
|
||||
[dependencies]
|
||||
mlua_derive = { version = "=0.9.3", optional = true, path = "mlua_derive" }
|
||||
mlua_derive = { version = "=0.12.0-rc.1", optional = true, path = "mlua_derive" }
|
||||
bstr = { version = "1.0", features = ["std"], default-features = false }
|
||||
once_cell = { version = "1.0" }
|
||||
either = "1.0"
|
||||
num-traits = { version = "0.2.14" }
|
||||
rustc-hash = "2.0"
|
||||
futures-util = { version = "0.3", optional = true, default-features = false, features = ["std"] }
|
||||
serde = { version = "1.0", optional = true }
|
||||
erased-serde = { version = "0.4", optional = true }
|
||||
serde-value = { version = "0.7", optional = true }
|
||||
parking_lot = { version = "0.12", optional = true }
|
||||
parking_lot = { version = "0.12", features = ["arc_lock"] }
|
||||
anyhow = { version = "1.0", optional = true }
|
||||
inventory = { version = "0.3", optional = true }
|
||||
libc = "0.2"
|
||||
|
||||
ffi = { package = "mlua-sys", version = "0.6.1", path = "mlua-sys" }
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
libloading = { version = "0.8", optional = true }
|
||||
ffi = { package = "mlua-sys", version = "0.11.0-rc.1", path = "mlua-sys" }
|
||||
|
||||
[dev-dependencies]
|
||||
trybuild = "1.0"
|
||||
futures = "0.3.5"
|
||||
hyper = { version = "1.2", features = ["full"] }
|
||||
hyper-util = { version = "0.1.3", features = ["full"] }
|
||||
http-body-util = "0.1.1"
|
||||
reqwest = { version = "0.12", features = ["json"] }
|
||||
tokio = { version = "1.0", features = ["macros", "rt", "time"] }
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = { version = "1.0", features = ["arbitrary_precision"] }
|
||||
maplit = "1.0"
|
||||
tempfile = "3"
|
||||
static_assertions = "1.0"
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies]
|
||||
criterion = { version = "0.5", features = ["async_tokio"] }
|
||||
rustyline = "14.0"
|
||||
[target.'cfg(not(target_family = "wasm"))'.dev-dependencies]
|
||||
hyper = { version = "1.2", features = ["full"] }
|
||||
hyper-util = { version = "0.1.3", features = ["full"] }
|
||||
http-body-util = "0.1.1"
|
||||
reqwest = { version = "0.13", features = ["json"] }
|
||||
tempfile = "3"
|
||||
criterion = { version = "0.8", features = ["async_tokio"] }
|
||||
rustyline = "18.0"
|
||||
tokio = { version = "1.0", features = ["full"] }
|
||||
|
||||
[lints.rust]
|
||||
@@ -90,7 +95,7 @@ required-features = ["async"]
|
||||
[[bench]]
|
||||
name = "serde"
|
||||
harness = false
|
||||
required-features = ["serialize"]
|
||||
required-features = ["serde"]
|
||||
|
||||
[[example]]
|
||||
name = "async_http_client"
|
||||
@@ -98,23 +103,23 @@ required-features = ["async", "macros"]
|
||||
|
||||
[[example]]
|
||||
name = "async_http_reqwest"
|
||||
required-features = ["async", "serialize", "macros"]
|
||||
required-features = ["async", "serde", "macros"]
|
||||
|
||||
[[example]]
|
||||
name = "async_http_server"
|
||||
required-features = ["async", "macros"]
|
||||
required-features = ["async", "macros", "send"]
|
||||
|
||||
[[example]]
|
||||
name = "async_tcp_server"
|
||||
required-features = ["async", "macros"]
|
||||
required-features = ["async", "macros", "send"]
|
||||
|
||||
[[example]]
|
||||
name = "guided_tour"
|
||||
required-features = ["macros"]
|
||||
|
||||
[[example]]
|
||||
name = "serialize"
|
||||
required-features = ["serialize"]
|
||||
name = "serde"
|
||||
required-features = ["serde"]
|
||||
|
||||
[[example]]
|
||||
name = "userdata"
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
# mlua
|
||||
[![Build Status]][github-actions] [![Latest Version]][crates.io] [![API Documentation]][docs.rs] [![Coverage Status]][codecov.io] ![MSRV]
|
||||
|
||||
[Build Status]: https://github.com/khvzak/mlua/workflows/CI/badge.svg
|
||||
[github-actions]: https://github.com/khvzak/mlua/actions
|
||||
[Build Status]: https://github.com/mlua-rs/mlua/workflows/CI/badge.svg
|
||||
[github-actions]: https://github.com/mlua-rs/mlua/actions
|
||||
[Latest Version]: https://img.shields.io/crates/v/mlua.svg
|
||||
[crates.io]: https://crates.io/crates/mlua
|
||||
[API Documentation]: https://docs.rs/mlua/badge.svg
|
||||
[docs.rs]: https://docs.rs/mlua
|
||||
[Coverage Status]: https://codecov.io/gh/mlua-rs/mlua/branch/main/graph/badge.svg?token=99339FS1CG
|
||||
[codecov.io]: https://codecov.io/gh/mlua-rs/mlua
|
||||
[MSRV]: https://img.shields.io/badge/rust-1.71+-brightgreen.svg?&logo=rust
|
||||
[MSRV]: https://img.shields.io/badge/rust-1.79+-brightgreen.svg?&logo=rust
|
||||
|
||||
[Guided Tour] | [Benchmarks] | [FAQ]
|
||||
|
||||
@@ -17,66 +17,66 @@
|
||||
[Benchmarks]: https://github.com/khvzak/script-bench-rs
|
||||
[FAQ]: FAQ.md
|
||||
|
||||
> **Note**
|
||||
>
|
||||
> See v0.9 [release notes](https://github.com/khvzak/mlua/blob/main/docs/release_notes/v0.9.md).
|
||||
## The main branch is the development version of `mlua`. Please see the [v0.11](https://github.com/mlua-rs/mlua/tree/v0.11) branch for the stable versions of `mlua`.
|
||||
|
||||
`mlua` is bindings to [Lua](https://www.lua.org) programming language for Rust with a goal to provide
|
||||
_safe_ (as far as it's possible), high level, easy to use, practical and flexible API.
|
||||
`mlua` is a set of bindings to the [Lua](https://www.lua.org) programming language for Rust with a goal of providing a
|
||||
_safe_ (as much as possible), high level, easy to use, practical and flexible API.
|
||||
|
||||
Started as `rlua` fork, `mlua` supports Lua 5.4, 5.3, 5.2, 5.1 (including LuaJIT) and [Roblox Luau] and allows to write native Lua modules in Rust as well as use Lua in a standalone mode.
|
||||
Started as an `rlua` fork, `mlua` supports Lua 5.5, 5.4, 5.3, 5.2, 5.1 (including LuaJIT) and [Luau] and allows writing native Lua modules in Rust as well as using Lua in a standalone mode.
|
||||
|
||||
`mlua` tested on Windows/macOS/Linux including module mode in [GitHub Actions] on `x86_64` platform and cross-compilation to `aarch64` (other targets are also supported).
|
||||
`mlua` is tested on Windows/macOS/Linux including module mode in [GitHub Actions] on `x86_64` platforms and cross-compilation to `aarch64` (other targets are also supported).
|
||||
|
||||
WebAssembly (WASM) is supported through `wasm32-unknown-emscripten` target for all Lua versions excluding JIT.
|
||||
WebAssembly (WASM) is supported through the `wasm32-unknown-emscripten` target for all Lua/Luau versions excluding JIT.
|
||||
|
||||
[GitHub Actions]: https://github.com/khvzak/mlua/actions
|
||||
[Roblox Luau]: https://luau-lang.org
|
||||
[GitHub Actions]: https://github.com/mlua-rs/mlua/actions
|
||||
[Luau]: https://luau.org
|
||||
|
||||
## Usage
|
||||
|
||||
### Feature flags
|
||||
|
||||
`mlua` uses feature flags to reduce the amount of dependencies, compiled code and allow to choose only required set of features.
|
||||
`mlua` uses feature flags to reduce the number of dependencies and compiled code, and allow choosing only the required set of features.
|
||||
Below is a list of the available feature flags. By default `mlua` does not enable any features.
|
||||
|
||||
* `lua54`: activate Lua [5.4] support
|
||||
* `lua53`: activate Lua [5.3] support
|
||||
* `lua52`: activate Lua [5.2] support
|
||||
* `lua51`: activate Lua [5.1] support
|
||||
* `luajit`: activate [LuaJIT] support
|
||||
* `luajit52`: activate [LuaJIT] support with partial compatibility with Lua 5.2
|
||||
* `luau`: activate [Luau] support (auto vendored mode)
|
||||
* `luau-jit`: activate [Luau] support with JIT backend.
|
||||
* `luau-vector4`: activate [Luau] support with 4-dimensional vector.
|
||||
* `vendored`: build static Lua(JIT) library from sources during `mlua` compilation using [lua-src] or [luajit-src] crates
|
||||
* `lua55`: enable Lua [5.5] support
|
||||
* `lua54`: enable Lua [5.4] support
|
||||
* `lua53`: enable Lua [5.3] support
|
||||
* `lua52`: enable Lua [5.2] support
|
||||
* `lua51`: enable Lua [5.1] support
|
||||
* `luajit`: enable [LuaJIT] support
|
||||
* `luajit52`: enable [LuaJIT] support with partial compatibility with Lua 5.2
|
||||
* `luau`: enable [Luau] support (auto vendored mode)
|
||||
* `luau-jit`: enable [Luau] support with JIT backend.
|
||||
* `luau-vector4`: enable [Luau] support with 4-dimensional vector.
|
||||
* `vendored`: build static Lua(JIT) libraries from sources during `mlua` compilation using [lua-src] or [luajit-src]
|
||||
* `module`: enable module mode (building loadable `cdylib` library for Lua)
|
||||
* `async`: enable async/await support (any executor can be used, eg. [tokio] or [async-std])
|
||||
* `send`: make `mlua::Lua` transferable across thread boundaries (adds [`Send`] requirement to `mlua::Function` and `mlua::UserData`)
|
||||
* `serialize`: add serialization and deserialization support to `mlua` types using [serde] framework
|
||||
* `send`: make `mlua::Lua: Send + Sync` (adds [`Send`] requirement to `mlua::Function` and `mlua::UserData`)
|
||||
* `error-send`: make `mlua:Error: Send + Sync`
|
||||
* `serde`: add serialization and deserialization support to `mlua` types using [serde]
|
||||
* `macros`: enable procedural macros (such as `chunk!`)
|
||||
* `parking_lot`: support UserData types wrapped in [parking_lot]'s primitives (`Arc<Mutex>` and `Arc<RwLock>`)
|
||||
* `unstable`: enable **unstable** features. The public API of these features may break between releases.
|
||||
* `anyhow`: enable `anyhow::Error` conversion into Lua
|
||||
* `userdata-wrappers`: opt into `impl UserData` for `Rc<T>`/`Arc<T>`/`Rc<RefCell<T>>`/`Arc<Mutex<T>>` where `T: UserData`
|
||||
|
||||
[5.5]: https://www.lua.org/manual/5.5/manual.html
|
||||
[5.4]: https://www.lua.org/manual/5.4/manual.html
|
||||
[5.3]: https://www.lua.org/manual/5.3/manual.html
|
||||
[5.2]: https://www.lua.org/manual/5.2/manual.html
|
||||
[5.1]: https://www.lua.org/manual/5.1/manual.html
|
||||
[LuaJIT]: https://luajit.org/
|
||||
[Luau]: https://github.com/Roblox/luau
|
||||
[lua-src]: https://github.com/khvzak/lua-src-rs
|
||||
[luajit-src]: https://github.com/khvzak/luajit-src-rs
|
||||
[Luau]: https://github.com/luau-lang/luau
|
||||
[lua-src]: https://github.com/mlua-rs/lua-src-rs
|
||||
[luajit-src]: https://github.com/mlua-rs/luajit-src-rs
|
||||
[tokio]: https://github.com/tokio-rs/tokio
|
||||
[async-std]: https://github.com/async-rs/async-std
|
||||
[`Send`]: https://doc.rust-lang.org/std/marker/trait.Send.html
|
||||
[serde]: https://github.com/serde-rs/serde
|
||||
[parking_lot]: https://github.com/Amanieu/parking_lot
|
||||
|
||||
### Async/await support
|
||||
|
||||
`mlua` supports async/await for all Lua versions including Luau.
|
||||
|
||||
This works using Lua [coroutines](https://www.lua.org/manual/5.3/manual.html#2.6) and require running [Thread](https://docs.rs/mlua/latest/mlua/struct.Thread.html) along with enabling `feature = "async"` in `Cargo.toml`.
|
||||
This works using Lua [coroutines](https://www.lua.org/manual/5.3/manual.html#2.6) and requires running [Thread](https://docs.rs/mlua/latest/mlua/struct.Thread.html) along with enabling `feature = "async"` in `Cargo.toml`.
|
||||
|
||||
**Examples**:
|
||||
- [HTTP Client](examples/async_http_client.rs)
|
||||
@@ -91,18 +91,18 @@ This works using Lua [coroutines](https://www.lua.org/manual/5.3/manual.html#2.6
|
||||
cargo run --example async_http_client --features=lua54,async,macros
|
||||
|
||||
# async http client (reqwest)
|
||||
cargo run --example async_http_reqwest --features=lua54,async,macros,serialize
|
||||
cargo run --example async_http_reqwest --features=lua54,async,macros,serde
|
||||
|
||||
# async http server
|
||||
cargo run --example async_http_server --features=lua54,async,macros
|
||||
cargo run --example async_http_server --features=lua54,async,macros,send
|
||||
curl -v http://localhost:3000
|
||||
```
|
||||
|
||||
### Serialization (serde) support
|
||||
### Serde support
|
||||
|
||||
With `serialize` feature flag enabled, `mlua` allows you to serialize/deserialize any type that implements [`serde::Serialize`] and [`serde::Deserialize`] into/from [`mlua::Value`]. In addition `mlua` provides [`serde::Serialize`] trait implementation for it (including `UserData` support).
|
||||
With the `serde` feature flag enabled, `mlua` allows you to serialize/deserialize any type that implements [`serde::Serialize`] and [`serde::Deserialize`] into/from [`mlua::Value`]. In addition, `mlua` provides the [`serde::Serialize`] trait implementation for `mlua::Value` (including `UserData` support).
|
||||
|
||||
[Example](examples/serialize.rs)
|
||||
[Example](examples/serde.rs)
|
||||
|
||||
[`serde::Serialize`]: https://docs.serde.rs/serde/ser/trait.Serialize.html
|
||||
[`serde::Deserialize`]: https://docs.serde.rs/serde/de/trait.Deserialize.html
|
||||
@@ -112,28 +112,28 @@ With `serialize` feature flag enabled, `mlua` allows you to serialize/deserializ
|
||||
|
||||
You have to enable one of the features: `lua54`, `lua53`, `lua52`, `lua51`, `luajit(52)` or `luau`, according to the chosen Lua version.
|
||||
|
||||
By default `mlua` uses `pkg-config` tool to find lua includes and libraries for the chosen Lua version.
|
||||
In most cases it works as desired, although sometimes could be more preferable to use a custom lua library.
|
||||
To achieve this, mlua supports `LUA_LIB`, `LUA_LIB_NAME` and `LUA_LINK` environment variables.
|
||||
By default `mlua` uses `pkg-config` to find Lua includes and libraries for the chosen Lua version.
|
||||
In most cases it works as desired, although sometimes it may be preferable to use a custom Lua library.
|
||||
To achieve this, mlua supports the `LUA_LIB`, `LUA_LIB_NAME` and `LUA_LINK` environment variables.
|
||||
`LUA_LINK` is optional and may be `dylib` (a dynamic library) or `static` (a static library, `.a` archive).
|
||||
|
||||
An example how to use them:
|
||||
An example of how to use them:
|
||||
``` sh
|
||||
my_project $ LUA_LIB=$HOME/tmp/lua-5.2.4/src LUA_LIB_NAME=lua LUA_LINK=static cargo build
|
||||
```
|
||||
|
||||
`mlua` also supports vendored lua/luajit using the auxiliary crates [lua-src](https://crates.io/crates/lua-src) and
|
||||
`mlua` also supports vendored Lua/LuaJIT using the auxiliary crates [lua-src](https://crates.io/crates/lua-src) and
|
||||
[luajit-src](https://crates.io/crates/luajit-src).
|
||||
Just enable the `vendored` feature and cargo will automatically build and link specified lua/luajit version. This is the easiest way to get started with `mlua`.
|
||||
Just enable the `vendored` feature and cargo will automatically build and link the specified Lua/LuaJIT version. This is the easiest way to get started with `mlua`.
|
||||
|
||||
### Standalone mode
|
||||
In a standalone mode `mlua` allows to add to your application scripting support with a gently configured Lua runtime to ensure safety and soundness.
|
||||
In standalone mode, `mlua` allows adding scripting support to your application with a properly configured Lua runtime to ensure safety and soundness.
|
||||
|
||||
Add to `Cargo.toml` :
|
||||
Add to `Cargo.toml`:
|
||||
|
||||
``` toml
|
||||
[dependencies]
|
||||
mlua = { version = "0.9.9", features = ["lua54", "vendored"] }
|
||||
mlua = { version = "0.11", features = ["lua54", "vendored"] }
|
||||
```
|
||||
|
||||
`main.rs`
|
||||
@@ -157,21 +157,21 @@ fn main() -> LuaResult<()> {
|
||||
```
|
||||
|
||||
### Module mode
|
||||
In a module mode `mlua` allows to create a compiled Lua module that can be loaded from Lua code using [`require`](https://www.lua.org/manual/5.4/manual.html#pdf-require). In this case `mlua` uses an external Lua runtime which could lead to potential unsafety due to unpredictability of the Lua environment and usage of libraries such as [`debug`](https://www.lua.org/manual/5.4/manual.html#6.10).
|
||||
In module mode, `mlua` allows creating a compiled Lua module that can be loaded from Lua code using [`require`](https://www.lua.org/manual/5.4/manual.html#pdf-require). In this case `mlua` uses an external Lua runtime which could lead to potential unsafety due to the unpredictability of the Lua environment and usage of libraries such as [`debug`](https://www.lua.org/manual/5.4/manual.html#6.10).
|
||||
|
||||
[Example](examples/module)
|
||||
|
||||
Add to `Cargo.toml` :
|
||||
Add to `Cargo.toml`:
|
||||
|
||||
``` toml
|
||||
[lib]
|
||||
crate-type = ["cdylib"]
|
||||
|
||||
[dependencies]
|
||||
mlua = { version = "0.9.9", features = ["lua54", "module"] }
|
||||
mlua = { version = "0.11", features = ["lua54", "module"] }
|
||||
```
|
||||
|
||||
`lib.rs` :
|
||||
`lib.rs`:
|
||||
|
||||
``` rust
|
||||
use mlua::prelude::*;
|
||||
@@ -198,7 +198,7 @@ $ lua5.4 -e 'require("my_module").hello("world")'
|
||||
hello, world!
|
||||
```
|
||||
|
||||
On macOS, you need to set additional linker arguments. One option is to compile with `cargo rustc --release -- -C link-arg=-undefined -C link-arg=dynamic_lookup`, the other is to create a `.cargo/config` with the following content:
|
||||
On macOS, you need to set additional linker arguments. One option is to compile with `cargo rustc --release -- -C link-arg=-undefined -C link-arg=dynamic_lookup`, the other is to create a `.cargo/config.toml` with the following content:
|
||||
``` toml
|
||||
[target.x86_64-apple-darwin]
|
||||
rustflags = [
|
||||
@@ -214,14 +214,14 @@ rustflags = [
|
||||
```
|
||||
On Linux you can build modules normally with `cargo build --release`.
|
||||
|
||||
On Windows the target module will be linked with `lua5x.dll` library (depending on your feature flags).
|
||||
On Windows the target module will be linked with the `lua5x.dll` library (depending on your feature flags).
|
||||
Your main application should provide this library.
|
||||
|
||||
Module builds don't require Lua lib or headers to be installed on the system.
|
||||
Module builds don't require Lua binaries or headers to be installed on the system.
|
||||
|
||||
### Publishing to luarocks.org
|
||||
|
||||
There is a LuaRocks build backend for mlua modules [`luarocks-build-rust-mlua`].
|
||||
There is a LuaRocks build backend for mlua modules: [`luarocks-build-rust-mlua`].
|
||||
|
||||
Modules written in Rust and published to luarocks:
|
||||
- [`decasify`](https://github.com/alerque/decasify)
|
||||
@@ -234,10 +234,10 @@ Modules written in Rust and published to luarocks:
|
||||
|
||||
## Safety
|
||||
|
||||
One of the `mlua` goals is to provide *safe* API between Rust and Lua.
|
||||
Every place where the Lua C API may trigger an error longjmp in any way is protected by `lua_pcall`,
|
||||
and the user of the library is protected from directly interacting with unsafe things like the Lua stack,
|
||||
and there is overhead associated with this safety.
|
||||
One of `mlua`'s goals is to provide a *safe* API between Rust and Lua.
|
||||
Every place where the Lua C API may trigger an error longjmp is protected by `lua_pcall`,
|
||||
and the user of the library is protected from directly interacting with unsafe things like the Lua stack.
|
||||
There is overhead associated with this safety.
|
||||
|
||||
Unfortunately, `mlua` does not provide absolute safety even without using `unsafe` .
|
||||
This library contains a huge amount of unsafe code. There are almost certainly bugs still lurking in this library!
|
||||
@@ -245,8 +245,8 @@ It is surprisingly, fiendishly difficult to use the Lua C API without the potent
|
||||
|
||||
## Panic handling
|
||||
|
||||
`mlua` wraps panics that are generated inside Rust callbacks in a regular Lua error. Panics could be
|
||||
resumed then by returning or propagating the Lua error to Rust code.
|
||||
`mlua` wraps panics that are generated inside Rust callbacks in a regular Lua error. Panics can then be
|
||||
resumed by returning or propagating the Lua error to Rust code.
|
||||
|
||||
For example:
|
||||
``` rust
|
||||
@@ -265,16 +265,16 @@ let _ = lua.load(r#"
|
||||
unreachable!()
|
||||
```
|
||||
|
||||
Optionally `mlua` can disable Rust panics catching in Lua via `pcall`/`xpcall` and automatically resume
|
||||
Optionally, `mlua` can disable Rust panic catching in Lua via `pcall`/`xpcall` and automatically resume
|
||||
them across the Lua API boundary. This is controlled via `LuaOptions` and done by wrapping the Lua `pcall`/`xpcall`
|
||||
functions on a way to prevent catching errors that are wrapped Rust panics.
|
||||
functions to prevent catching errors that are wrapped Rust panics.
|
||||
|
||||
`mlua` should also be panic safe in another way as well, which is that any `Lua` instances or handles
|
||||
remains usable after a user generated panic, and such panics should not break internal invariants or
|
||||
remain usable after a user generated panic, and such panics should not break internal invariants or
|
||||
leak Lua stack space. This is mostly important to safely use `mlua` types in Drop impls, as you should not be
|
||||
using panics for general error handling.
|
||||
|
||||
Below is a list of `mlua` behaviors that should be considered a bug.
|
||||
Below is a list of `mlua` behaviors that should be considered bugs.
|
||||
If you encounter them, a bug report would be very welcome:
|
||||
|
||||
+ If you can cause UB with `mlua` without typing the word "unsafe", this is a bug.
|
||||
@@ -287,12 +287,12 @@ If you encounter them, a bug report would be very welcome:
|
||||
|
||||
## Sandboxing
|
||||
|
||||
Please check the [Luau Sandboxing] page if you are interested in running untrusted Lua scripts in controlled environment.
|
||||
Please check the [Luau Sandboxing] page if you are interested in running untrusted Lua scripts in a controlled environment.
|
||||
|
||||
`mlua` provides `Lua::sandbox` method for enabling sandbox mode (Luau only).
|
||||
`mlua` provides the `Lua::sandbox` method for enabling sandbox mode (Luau only).
|
||||
|
||||
[Luau Sandboxing]: https://luau-lang.org/sandbox
|
||||
[Luau Sandboxing]: https://luau.org/sandbox
|
||||
|
||||
## License
|
||||
|
||||
This project is licensed under the [MIT license](LICENSE)
|
||||
This project is licensed under the [MIT license](LICENSE).
|
||||
|
||||
+69
-30
@@ -1,7 +1,7 @@
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::time::Duration;
|
||||
|
||||
use criterion::{criterion_group, criterion_main, BatchSize, Criterion};
|
||||
use criterion::{BatchSize, Criterion, criterion_group, criterion_main};
|
||||
use tokio::runtime::Runtime;
|
||||
use tokio::task;
|
||||
|
||||
@@ -74,7 +74,7 @@ fn table_get_set(c: &mut Criterion) {
|
||||
.enumerate()
|
||||
{
|
||||
table.raw_set(s, i).unwrap();
|
||||
assert_eq!(table.raw_get::<_, usize>(s).unwrap(), i);
|
||||
assert_eq!(table.raw_get::<usize>(s).unwrap(), i);
|
||||
}
|
||||
},
|
||||
BatchSize::SmallInput,
|
||||
@@ -128,6 +128,22 @@ fn table_traversal_sequence(c: &mut Criterion) {
|
||||
});
|
||||
}
|
||||
|
||||
fn table_ref_clone(c: &mut Criterion) {
|
||||
let lua = Lua::new();
|
||||
|
||||
let t = lua.create_table().unwrap();
|
||||
|
||||
c.bench_function("table [ref clone]", |b| {
|
||||
b.iter_batched(
|
||||
|| collect_gc_twice(&lua),
|
||||
|_| {
|
||||
let _t2 = t.clone();
|
||||
},
|
||||
BatchSize::SmallInput,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
fn function_create(c: &mut Criterion) {
|
||||
let lua = Lua::new();
|
||||
|
||||
@@ -153,7 +169,7 @@ fn function_call_sum(c: &mut Criterion) {
|
||||
b.iter_batched(
|
||||
|| collect_gc_twice(&lua),
|
||||
|_| {
|
||||
assert_eq!(sum.call::<_, i64>((10, 20, 30)).unwrap(), 0);
|
||||
assert_eq!(sum.call::<i64>((10, 20, 30)).unwrap(), 0);
|
||||
},
|
||||
BatchSize::SmallInput,
|
||||
);
|
||||
@@ -172,7 +188,7 @@ fn function_call_lua_sum(c: &mut Criterion) {
|
||||
b.iter_batched(
|
||||
|| collect_gc_twice(&lua),
|
||||
|_| {
|
||||
assert_eq!(sum.call::<_, i64>((10, 20, 30)).unwrap(), 0);
|
||||
assert_eq!(sum.call::<i64>((10, 20, 30)).unwrap(), 0);
|
||||
},
|
||||
BatchSize::SmallInput,
|
||||
);
|
||||
@@ -183,9 +199,7 @@ fn function_call_concat(c: &mut Criterion) {
|
||||
let lua = Lua::new();
|
||||
|
||||
let concat = lua
|
||||
.create_function(|_, (a, b): (LuaString, LuaString)| {
|
||||
Ok(format!("{}{}", a.to_str()?, b.to_str()?))
|
||||
})
|
||||
.create_function(|_, (a, b): (LuaString, LuaString)| Ok(format!("{}{}", a.to_str()?, b.to_str()?)))
|
||||
.unwrap();
|
||||
let i = AtomicUsize::new(0);
|
||||
|
||||
@@ -196,10 +210,7 @@ fn function_call_concat(c: &mut Criterion) {
|
||||
i.fetch_add(1, Ordering::Relaxed)
|
||||
},
|
||||
|i| {
|
||||
assert_eq!(
|
||||
concat.call::<_, LuaString>(("num:", i)).unwrap(),
|
||||
format!("num:{i}")
|
||||
);
|
||||
assert_eq!(concat.call::<LuaString>(("num:", i)).unwrap(), format!("num:{i}"));
|
||||
},
|
||||
BatchSize::SmallInput,
|
||||
);
|
||||
@@ -222,10 +233,7 @@ fn function_call_lua_concat(c: &mut Criterion) {
|
||||
i.fetch_add(1, Ordering::Relaxed)
|
||||
},
|
||||
|i| {
|
||||
assert_eq!(
|
||||
concat.call::<_, LuaString>(("num:", i)).unwrap(),
|
||||
format!("num:{i}")
|
||||
);
|
||||
assert_eq!(concat.call::<LuaString>(("num:", i)).unwrap(), format!("num:{i}"));
|
||||
},
|
||||
BatchSize::SmallInput,
|
||||
);
|
||||
@@ -248,7 +256,7 @@ fn function_async_call_sum(c: &mut Criterion) {
|
||||
b.to_async(rt).iter_batched(
|
||||
|| collect_gc_twice(&lua),
|
||||
|_| async {
|
||||
assert_eq!(sum.call_async::<_, i64>((10, 20, 30)).await.unwrap(), 0);
|
||||
assert_eq!(sum.call_async::<i64>((10, 20, 30)).await.unwrap(), 0);
|
||||
},
|
||||
BatchSize::SmallInput,
|
||||
);
|
||||
@@ -305,7 +313,7 @@ fn userdata_create(c: &mut Criterion) {
|
||||
fn userdata_call_index(c: &mut Criterion) {
|
||||
struct UserData(#[allow(unused)] i64);
|
||||
impl LuaUserData for UserData {
|
||||
fn add_methods<'lua, M: LuaUserDataMethods<'lua, Self>>(methods: &mut M) {
|
||||
fn add_methods<M: LuaUserDataMethods<Self>>(methods: &mut M) {
|
||||
methods.add_meta_method(LuaMetaMethod::Index, move |_, _, key: LuaString| Ok(key));
|
||||
}
|
||||
}
|
||||
@@ -321,7 +329,7 @@ fn userdata_call_index(c: &mut Criterion) {
|
||||
b.iter_batched(
|
||||
|| collect_gc_twice(&lua),
|
||||
|_| {
|
||||
assert_eq!(index.call::<_, LuaString>(&ud).unwrap(), "test");
|
||||
assert_eq!(index.call::<LuaString>(&ud).unwrap(), "test");
|
||||
},
|
||||
BatchSize::SmallInput,
|
||||
);
|
||||
@@ -331,7 +339,7 @@ fn userdata_call_index(c: &mut Criterion) {
|
||||
fn userdata_call_method(c: &mut Criterion) {
|
||||
struct UserData(i64);
|
||||
impl LuaUserData for UserData {
|
||||
fn add_methods<'lua, M: LuaUserDataMethods<'lua, Self>>(methods: &mut M) {
|
||||
fn add_methods<M: LuaUserDataMethods<Self>>(methods: &mut M) {
|
||||
methods.add_method("add", |_, this, i: i64| Ok(this.0 + i));
|
||||
}
|
||||
}
|
||||
@@ -351,7 +359,43 @@ fn userdata_call_method(c: &mut Criterion) {
|
||||
i.fetch_add(1, Ordering::Relaxed)
|
||||
},
|
||||
|i| {
|
||||
assert_eq!(method.call::<_, usize>((&ud, i)).unwrap(), 123 + i);
|
||||
assert_eq!(method.call::<usize>((&ud, i)).unwrap(), 123 + i);
|
||||
},
|
||||
BatchSize::SmallInput,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
// A userdata method call that goes through an implicit `__index` function
|
||||
fn userdata_call_method_complex(c: &mut Criterion) {
|
||||
struct UserData(u64);
|
||||
impl LuaUserData for UserData {
|
||||
fn register(registry: &mut LuaUserDataRegistry<Self>) {
|
||||
registry.add_field_method_get("val", |_, this| Ok(this.0));
|
||||
registry.add_method_mut("inc_by", |_, this, by: u64| {
|
||||
this.0 += by;
|
||||
Ok(this.0)
|
||||
});
|
||||
|
||||
#[cfg(feature = "luau")]
|
||||
registry.enable_namecall();
|
||||
}
|
||||
}
|
||||
|
||||
let lua = Lua::new();
|
||||
let ud = lua.create_userdata(UserData(0)).unwrap();
|
||||
let inc_by = lua
|
||||
.load("function(ud, s) return ud:inc_by(s) end")
|
||||
.eval::<LuaFunction>()
|
||||
.unwrap();
|
||||
|
||||
c.bench_function("userdata [call method complex]", |b| {
|
||||
b.iter_batched(
|
||||
|| {
|
||||
collect_gc_twice(&lua);
|
||||
},
|
||||
|_| {
|
||||
inc_by.call::<()>((&ud, 1)).unwrap();
|
||||
},
|
||||
BatchSize::SmallInput,
|
||||
);
|
||||
@@ -361,7 +405,7 @@ fn userdata_call_method(c: &mut Criterion) {
|
||||
fn userdata_async_call_method(c: &mut Criterion) {
|
||||
struct UserData(i64);
|
||||
impl LuaUserData for UserData {
|
||||
fn add_methods<'lua, M: LuaUserDataMethods<'lua, Self>>(methods: &mut M) {
|
||||
fn add_methods<M: LuaUserDataMethods<Self>>(methods: &mut M) {
|
||||
methods.add_async_method("add", |_, this, i: i64| async move {
|
||||
task::yield_now().await;
|
||||
Ok(this.0 + i)
|
||||
@@ -383,17 +427,10 @@ fn userdata_async_call_method(c: &mut Criterion) {
|
||||
b.to_async(rt).iter_batched(
|
||||
|| {
|
||||
collect_gc_twice(&lua);
|
||||
(
|
||||
method.clone(),
|
||||
ud.clone(),
|
||||
i.fetch_add(1, Ordering::Relaxed),
|
||||
)
|
||||
(method.clone(), ud.clone(), i.fetch_add(1, Ordering::Relaxed))
|
||||
},
|
||||
|(method, ud, i)| async move {
|
||||
assert_eq!(
|
||||
method.call_async::<_, usize>((ud, i)).await.unwrap(),
|
||||
123 + i
|
||||
);
|
||||
assert_eq!(method.call_async::<usize>((ud, i)).await.unwrap(), 123 + i);
|
||||
},
|
||||
BatchSize::SmallInput,
|
||||
);
|
||||
@@ -414,6 +451,7 @@ criterion_group! {
|
||||
table_traversal_pairs,
|
||||
table_traversal_for_each,
|
||||
table_traversal_sequence,
|
||||
table_ref_clone,
|
||||
|
||||
function_create,
|
||||
function_call_sum,
|
||||
@@ -428,6 +466,7 @@ criterion_group! {
|
||||
userdata_create,
|
||||
userdata_call_index,
|
||||
userdata_call_method,
|
||||
userdata_call_method_complex,
|
||||
userdata_async_call_method,
|
||||
}
|
||||
|
||||
|
||||
+3
-3
@@ -1,6 +1,6 @@
|
||||
use std::time::Duration;
|
||||
|
||||
use criterion::{criterion_group, criterion_main, BatchSize, Criterion};
|
||||
use criterion::{BatchSize, Criterion, criterion_group, criterion_main};
|
||||
|
||||
use mlua::prelude::*;
|
||||
|
||||
@@ -37,7 +37,7 @@ fn encode_json(c: &mut Criterion) {
|
||||
b.iter_batched(
|
||||
|| collect_gc_twice(&lua),
|
||||
|_| {
|
||||
encode.call::<_, LuaString>(&table).unwrap();
|
||||
encode.call::<LuaString>(&table).unwrap();
|
||||
},
|
||||
BatchSize::SmallInput,
|
||||
);
|
||||
@@ -69,7 +69,7 @@ fn decode_json(c: &mut Criterion) {
|
||||
b.iter_batched(
|
||||
|| collect_gc_twice(&lua),
|
||||
|_| {
|
||||
decode.call::<_, LuaTable>(json).unwrap();
|
||||
decode.call::<LuaTable>(json).unwrap();
|
||||
},
|
||||
BatchSize::SmallInput,
|
||||
);
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
Implements the [`UserData`] trait for a Rust type.
|
||||
|
||||
This derive macro generates an implementation of [`UserData`] that exposes
|
||||
struct fields to Lua and integrates with `#[mlua::userdata_impl]` for
|
||||
registering methods.
|
||||
|
||||
Named fields are exposed as readable and writable fields in Lua by default.
|
||||
Use `#[lua(...)]` on individual fields or methods to control how they are
|
||||
registered.
|
||||
|
||||
```rust,ignore
|
||||
use mlua::{Lua, Result, UserData};
|
||||
|
||||
#[derive(UserData)]
|
||||
struct Rectangle {
|
||||
length: u32,
|
||||
width: u32,
|
||||
}
|
||||
|
||||
#[mlua::userdata_impl]
|
||||
impl Rectangle {
|
||||
#[lua(infallible)]
|
||||
fn new(length: u32, width: u32) -> Self {
|
||||
Self { length, width }
|
||||
}
|
||||
|
||||
#[lua(getter, name = "area", infallible)]
|
||||
fn calculate_area(&self) -> u32 {
|
||||
self.length * self.width
|
||||
}
|
||||
|
||||
fn diagonal(&self) -> Result<f64> {
|
||||
Ok(((self.length.pow(2) + self.width.pow(2)) as f64).sqrt())
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
# Struct field attributes
|
||||
|
||||
Each named field can be annotated with `#[lua(...)]`:
|
||||
|
||||
| Attribute | Description |
|
||||
| -------------- | ----------------------------------------------------- |
|
||||
| `get` | Expose a getter. The field becomes readable from Lua. |
|
||||
| `set` | Expose a setter. The field becomes writable from Lua. |
|
||||
| `skip` | Do not expose this field. |
|
||||
| `name = "..."` | Override the Lua-facing name for the field. |
|
||||
|
||||
If neither `get` nor `set` is specified, both are enabled.
|
||||
|
||||
Fields exposed as readable (via `get` or by default) must implement `Clone`.
|
||||
The generated getter clones the field value when accessed from Lua.
|
||||
|
||||
# Methods registration
|
||||
|
||||
Use `#[mlua::userdata_impl]` on an `impl` block to register methods,
|
||||
metamethods, and constants. All public items in the block are registered
|
||||
automatically.
|
||||
|
||||
## Method detection
|
||||
|
||||
The receiver type determines how a method is registered:
|
||||
|
||||
| Receiver | Registration |
|
||||
| ----------- | ----------------- |
|
||||
| `&self` | `add_method` |
|
||||
| `&mut self` | `add_method_mut` |
|
||||
| `self` | `add_method_once` |
|
||||
| None | `add_function` |
|
||||
|
||||
A first parameter of type `&Lua` (or `&mlua::Lua`) is treated as the
|
||||
Lua state reference and passed automatically.
|
||||
|
||||
## Method and constant attributes
|
||||
|
||||
Each item in the impl block can be annotated with `#[lua(...)]`:
|
||||
|
||||
| Attribute | Applies to | Description |
|
||||
| -------------- | ------------------ | -------------------------------------------------------------------------------------- |
|
||||
| `skip` | Methods, constants | Exclude this item from registration. |
|
||||
| `name = "..."` | Methods, constants | Override the Lua-facing name. |
|
||||
| `infallible` | Methods | Wrap the return value in `Ok(...)`. |
|
||||
| `getter` | Methods | Register as a field getter. Must take `&self` and no Lua-facing arguments. |
|
||||
| `setter` | Methods | Register as a field setter. Must take `&[mut] self` and one value argument. |
|
||||
| `field` | Methods, constants | Register as a static field. Methods must take no receiver and no Lua-facing arguments. |
|
||||
| `meta` | Methods, constants | Register as a metamethod. May be combined with `field` for meta static fields. |
|
||||
|
||||
At most one of `getter`, `setter`, `field` may be specified on a method.
|
||||
|
||||
## Constants
|
||||
|
||||
Constants in an `#[mlua::userdata_impl]` block are registered as static
|
||||
fields:
|
||||
|
||||
```rust,ignore
|
||||
#[mlua::userdata_impl]
|
||||
impl MyType {
|
||||
const VERSION: &str = "1.0";
|
||||
const COUNT: u32 = 42;
|
||||
}
|
||||
```
|
||||
|
||||
Use `#[lua(meta)]` on a constant to register it as a meta static field.
|
||||
|
||||
## Metamethods
|
||||
|
||||
Annotate a method with `#[lua(meta)]` to register it as a Lua metamethod.
|
||||
The metamethod name is inferred from the function name when it starts with
|
||||
`__`. Use `name = "..."` to specify the name explicitly.
|
||||
|
||||
```rust,ignore
|
||||
#[mlua::userdata_impl]
|
||||
impl MyType {
|
||||
#[lua(meta, infallible)]
|
||||
fn __add(&self, other: &Self) -> Self { ... }
|
||||
|
||||
#[lua(meta, name = "__call", infallible)]
|
||||
fn construct(lua: &Lua, value: u32) -> Self { ... }
|
||||
}
|
||||
```
|
||||
|
||||
## Reference parameters
|
||||
|
||||
Reference parameters in method signatures are automatically mapped to
|
||||
the appropriate callback wrapper types:
|
||||
|
||||
| Parameter type | Callback type |
|
||||
| -------------- | ------------------- |
|
||||
| `&str` | `BorrowedStr` |
|
||||
| `&[u8]` | `BorrowedBytes` |
|
||||
| `&T` | `UserDataRef<T>` |
|
||||
| `&mut T` | `UserDataRefMut<T>` |
|
||||
|
||||
## Async methods
|
||||
|
||||
Async methods are supported and registered via the corresponding async
|
||||
variants (`add_async_method`, `add_async_method_mut`, etc.).
|
||||
|
||||
# Limitations
|
||||
|
||||
Generics are not supported. Wrap a generic type in a concrete newtype
|
||||
instead.
|
||||
|
||||
Union types cannot derive `UserData`.
|
||||
|
||||
Enum types are accepted but generate no field registrations. All method
|
||||
registration must be done via `#[mlua::userdata_impl]`.
|
||||
|
||||
[`UserData`]: crate::UserData
|
||||
@@ -0,0 +1,52 @@
|
||||
Create a type that implements [`AsChunk`] and can capture Rust variables.
|
||||
|
||||
This macro allows to write Lua code directly in Rust code.
|
||||
|
||||
Rust variables can be referenced from Lua using `$` prefix, as shown in the example below.
|
||||
User's Rust types needs to implement [`UserData`] or [`IntoLua`] traits.
|
||||
|
||||
Captured variables are **moved** into the chunk.
|
||||
|
||||
```rust
|
||||
use mlua::{Lua, Result, chunk};
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let lua = Lua::new();
|
||||
let name = "Rustacean";
|
||||
lua.load(chunk! {
|
||||
print("hello, " .. $name)
|
||||
}).exec()
|
||||
}
|
||||
```
|
||||
|
||||
## Syntax issues
|
||||
|
||||
Since the Rust tokenizer will tokenize Lua code, this imposes some restrictions.
|
||||
The main thing to remember is:
|
||||
|
||||
- Use double quoted strings (`""`) instead of single quoted strings (`''`).
|
||||
|
||||
(Single quoted strings only work if they contain a single character, since in Rust,
|
||||
`'a'` is a character literal).
|
||||
|
||||
- Using Lua comments `--` is not desirable in **stable** Rust and can have bad side effects.
|
||||
|
||||
This is because procedural macros have Line/Column information available only in
|
||||
**nightly** Rust. Instead, Lua chunks represented as a big single line of code in stable Rust.
|
||||
|
||||
As workaround, Rust comments `//` can be used.
|
||||
|
||||
Other minor limitations:
|
||||
|
||||
- Certain escape codes in string literals don't work. (Specifically: `\a`, `\b`, `\f`, `\v`,
|
||||
`\123` (octal escape codes), `\u`, and `\U`).
|
||||
|
||||
These are accepted: : `\\`, `\n`, `\t`, `\r`, `\xAB` (hex escape codes), and `\0`.
|
||||
|
||||
- The `//` (floor division) operator is unusable, as its start a comment.
|
||||
|
||||
Everything else should work.
|
||||
|
||||
[`AsChunk`]: crate::chunk::AsChunk
|
||||
[`UserData`]: crate::UserData
|
||||
[`IntoLua`]: crate::IntoLua
|
||||
@@ -0,0 +1,41 @@
|
||||
Registers Lua module entrypoint.
|
||||
|
||||
You can register multiple entrypoints as required.
|
||||
|
||||
```rust,ignore
|
||||
use mlua::{Lua, Result, Table};
|
||||
|
||||
#[mlua::lua_module]
|
||||
fn my_module(lua: &Lua) -> Result<Table> {
|
||||
let exports = lua.create_table()?;
|
||||
exports.set("hello", "world")?;
|
||||
Ok(exports)
|
||||
}
|
||||
```
|
||||
|
||||
Internally in the code above the compiler defines C function `luaopen_my_module`.
|
||||
|
||||
You can also pass options to the attribute:
|
||||
|
||||
* name - name of the module, defaults to the name of the function
|
||||
|
||||
```rust,ignore
|
||||
#[mlua::lua_module(name = "alt_module")]
|
||||
fn my_module(lua: &Lua) -> Result<Table> {
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
* skip_memory_check - skip memory allocation checks for some operations.
|
||||
|
||||
In module mode, mlua runs in an unknown environment and cannot tell whether there are any memory
|
||||
limits or not. As a result, some operations that require memory allocation run in protected
|
||||
mode. Setting this attribute will improve performance of such operations with risk of having
|
||||
uncaught exceptions and memory leaks.
|
||||
|
||||
```rust,ignore
|
||||
#[mlua::lua_module(skip_memory_check)]
|
||||
fn my_module(lua: &Lua) -> Result<Table> {
|
||||
...
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,195 @@
|
||||
## mlua v0.10 release notes
|
||||
|
||||
The v0.10 version of mlua has a goal to improve the user experience while keeping the same performance and safety guarantees.
|
||||
This document highlights the most notable features. For a full list of changes, see the [CHANGELOG].
|
||||
|
||||
[CHANGELOG]: https://github.com/mlua-rs/mlua/blob/main/CHANGELOG.md
|
||||
|
||||
### New features
|
||||
|
||||
#### `'static` Lua types
|
||||
|
||||
In previous mlua versions, it was required to have a `'lua` lifetime attached to every Lua value. v0.9 introduced (experimental) owned types that are `'static` without a lifetime attached, but they kept strong references to the Lua instance.
|
||||
In v0.10 all Lua types are `'static` and have only weak reference to the Lua instance. It means they are more flexible and can be used in more places without worrying about memory leaks.
|
||||
|
||||
#### Truly `send` feature
|
||||
|
||||
In this version Lua is `Send + Sync` when the `send` feature flag is enabled (previously was only `Send`). It means Lua instance and their values can be safely shared between threads and used in multi threaded async contexts.
|
||||
|
||||
```rust
|
||||
let lua = Lua::new();
|
||||
|
||||
lua.globals().set("i", 0)?;
|
||||
let func = lua.load("i = i + ...").into_function()?;
|
||||
|
||||
std::thread::scope(|s| {
|
||||
s.spawn(|| {
|
||||
for i in 0..5 {
|
||||
func.call::<()>(i).unwrap();
|
||||
}
|
||||
});
|
||||
s.spawn(|| {
|
||||
for i in 0..5 {
|
||||
func.call::<()>(i).unwrap();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
assert_eq!(lua.globals().get::<i32>("i")?, 20);
|
||||
```
|
||||
|
||||
Under the hood, to synchronize access to the Lua state, mlua uses [`ReentrantMutex`] which can be recursively locked by a single thread. Only one thread can execute Lua code at a time, but it's possible to share Lua values between threads.
|
||||
|
||||
This has some performance penalties (about 10-20%) compared to the lock free mode. This flag is disabled by default and is not supported in module mode.
|
||||
|
||||
[`ReentrantMutex`]: https://docs.rs/parking_lot/latest/parking_lot/type.ReentrantMutex.html
|
||||
|
||||
#### Register Rust functions with variable number of arguments
|
||||
|
||||
The new traits `LuaNativeFn`/`LuaNativeFnMut`/`LuaNativeAsyncFn` have been introduced to provide a way to register Rust functions with variable number of arguments in Lua, without needing to pass all arguments as a tuple.
|
||||
|
||||
They are used by `Function::wrap`/`Function::wrap_mut`/`Function::wrap_async` methods:
|
||||
|
||||
```rust
|
||||
let add = Function::wrap(|a: i64, b: i64| Ok(a + b));
|
||||
|
||||
lua.globals().set("add", add).unwrap();
|
||||
|
||||
// Prints 50
|
||||
lua.load(r#"print(add(5, 45))"#).exec().unwrap();
|
||||
```
|
||||
|
||||
To wrap functions that return direct value (non-`Result`) you can use `Function::wrap_raw` method.
|
||||
|
||||
#### Setting metatable for Lua builtin types
|
||||
|
||||
For Lua builtin types (like `string`, `function`, `number`, etc.) that have a shared metatable for all instances, it's now possible to set a custom metatable for them.
|
||||
|
||||
```rust
|
||||
let mt = lua.create_table()?;
|
||||
mt.set("__tostring", lua.create_function(|_, b: bool| Ok(if b { "2" } else { "0" }))?)?;
|
||||
lua.set_type_metatable::<bool>(Some(mt));
|
||||
lua.load("assert(tostring(true) == '2')").exec().unwrap();
|
||||
```
|
||||
|
||||
### Improvements
|
||||
|
||||
#### New `ObjectLike` trait
|
||||
|
||||
The `ObjectLike` trait is a combination of the `AnyUserDataExt` and `TableExt` traits used in previous versions. It provides a unified interface for working with Lua tables and userdata.
|
||||
|
||||
#### `Either<L, R>` enum
|
||||
|
||||
The `Either<L, R>` enum is a simple enum that can hold either `L` or `R` value. It's useful when you need to return or receive one of two types in a function.
|
||||
This type implements `IntoLua` and `FromLua` traits and can generate a meaningful error message when conversion fails.
|
||||
|
||||
```rust
|
||||
let func = Function::wrap(|x: Either<i32, String>| Ok(format!("received: {x}")));
|
||||
|
||||
lua.globals().set("func", func).unwrap();
|
||||
|
||||
// Prints: received: 123
|
||||
lua.load(r#"print(func(123))"#).exec().unwrap();
|
||||
|
||||
// Prints: bad argument #1: error converting Lua table to Either<i32, String>
|
||||
lua.load(r#"print(pcall(func, {}))"#).exec().unwrap();
|
||||
```
|
||||
|
||||
#### `Lua::exec_raw` helper to execute low-level Lua C API code
|
||||
|
||||
For advanced users, it's now possible to execute low-level Lua C API code using the `Lua::exec_raw` method.
|
||||
|
||||
```rust
|
||||
let t = lua.create_sequence_from([1, 2, 3, 4, 5])?;
|
||||
let sum: i64 = unsafe {
|
||||
lua.exec_raw(&t, |state| {
|
||||
// top of the stack: table `t`
|
||||
let mut sum = 0;
|
||||
// push nil as the first key
|
||||
mlua::ffi::lua_pushnil(state);
|
||||
while mlua::ffi::lua_next(state, -2) != 0 {
|
||||
sum += mlua::ffi::lua_tointeger(state, -1);
|
||||
// Remove the value, keep the key for the next iteration
|
||||
mlua::ffi::lua_pop(state, 1);
|
||||
}
|
||||
mlua::ffi::lua_pop(state, 1);
|
||||
mlua::ffi::lua_pushinteger(state, sum);
|
||||
// top of the stack: sum
|
||||
})
|
||||
}?;
|
||||
assert_eq!(sum, 15);
|
||||
```
|
||||
|
||||
The `exec_raw` method is longjmp-safe. It's not recommended to move `Drop` types into the closure to avoid possible memory leaks.
|
||||
|
||||
#### `anyhow` feature flag
|
||||
|
||||
The new `anyhow` feature flag adds `IntoLua` and `Into<mlua::Error>` implementation for the `anyhow::Error` type.
|
||||
|
||||
```rust
|
||||
let f = lua.create_function(|_, ()| {
|
||||
Err(anyhow!("error message"))?;
|
||||
Ok(())
|
||||
})?;
|
||||
```
|
||||
|
||||
### Breaking changes
|
||||
|
||||
#### Scope changes
|
||||
|
||||
The following `Scope` methods were changed:
|
||||
- Removed `Scope::create_any_userdata`
|
||||
- `Scope::create_nonstatic_userdata` is renamed to `Scope::create_userdata`
|
||||
|
||||
Instead, scope has comprehensive support for borrowed userdata: `create_any_userdata_ref`, `create_any_userdata_ref_mut`, `create_userdata_ref`, `create_userdata_ref_mut`.
|
||||
|
||||
`UserDataRef` and `UserDataRefMut` are no longer acceptable for scoped userdata access as they require owned underlying data.
|
||||
In mlua v0.9 this could cause a read-after-free bug in some edge cases.
|
||||
|
||||
To temporarily borrow underlying data, the `AnyUserData::borrow_scoped` and `AnyUserData::borrow_mut_scoped` methods were introduced:
|
||||
|
||||
```rust
|
||||
let data = "hello".to_string();
|
||||
lua.scope(|scope| {
|
||||
let ud = scope.create_any_userdata_ref(&data)?;
|
||||
|
||||
// We can only borrow scoped userdata using this method
|
||||
ud.borrow_scoped::<String, ()>(|s| {
|
||||
assert_eq!(s, "hello");
|
||||
})?;
|
||||
|
||||
Ok(())
|
||||
})?;
|
||||
```
|
||||
|
||||
Those methods work for scoped and regular userdata objects (but still require `T: 'static`).
|
||||
|
||||
#### String changes
|
||||
|
||||
Since `mlua::String` holds a weak reference to Lua without any guarantees about the lifetime of the underlying data, getting a `&str` or `&[u8]` from it is no longer safe.
|
||||
Lua instance can be destroyed while reference to the data is still alive:
|
||||
|
||||
```rust
|
||||
let lua = Lua::new();
|
||||
let s: mlua::String = lua.create_string("hello, world")?; // only weak reference to Lua!
|
||||
let s_ref: &str = s.to_str()?; // this is not safe!
|
||||
drop(lua);
|
||||
println!("{s_ref}"); // use after free!
|
||||
```
|
||||
|
||||
To solve this issue, return types of `mlua::String::to_str` and `mlua::String::as_bytes` methods changed to `BorrowedStr` and `BorrowedBytes` respectively.
|
||||
|
||||
These new types hold a strong reference to the Lua instance and can be safely converted to `&str` or `&[u8]`:
|
||||
|
||||
```rust
|
||||
let lua = Lua::new();
|
||||
let s: mlua::String = lua.create_string("hello, world")?;
|
||||
let s_ref: mlua::BorrowedStr = s.to_str()?; // The strong reference to Lua is held here
|
||||
drop(lua);
|
||||
println!("{s_ref}"); // ok
|
||||
```
|
||||
|
||||
The good news is that `BorrowedStr` implements `Deref<Target = str>`/`AsRef<str>` as well as `Display`, `Debug`, `Eq`, `PartialEq` and other traits for easy usage.
|
||||
The same applies to `BorrowedBytes`.
|
||||
|
||||
Unfortunately, `mlua::String::to_string_lossy` cannot return `Cow<'a, str>` anymore, because it requires a strong reference to Lua. It now returns Rust `String` instead.
|
||||
@@ -3,7 +3,7 @@
|
||||
The v0.9 version of mlua is a major release that includes a number of API changes and improvements. This release is a stepping stone towards the v1.0.
|
||||
This document highlights the most important changes. For a full list of changes, see the [CHANGELOG].
|
||||
|
||||
[CHANGELOG]: https://github.com/khvzak/mlua/blob/main/CHANGELOG.md
|
||||
[CHANGELOG]: https://github.com/mlua-rs/mlua/blob/main/CHANGELOG.md
|
||||
|
||||
### New features
|
||||
|
||||
@@ -152,9 +152,9 @@ It will automatically trigger JIT compilation for new Lua chunks. To disable it,
|
||||
|
||||
#### 1. Better error reporting
|
||||
|
||||
When calling a Rust function from Lua and passing wrong arguments, previous mlua versions reported a error message without any context or reference to the particular argument.
|
||||
When calling a Rust function from Lua and passing wrong arguments, previous mlua versions reported an error message without any context or reference to the particular argument.
|
||||
|
||||
In v0.9 it reports a error message with the argument index and expected type:
|
||||
In v0.9 it reports an error message with the argument index and expected type:
|
||||
|
||||
```rust
|
||||
let func = lua.create_function(|_, _a: i32| Ok(()))?;
|
||||
@@ -304,7 +304,7 @@ assert_eq!(f.call::<_, mlua::String>(())?, "hello");
|
||||
|
||||
The new mlua version has a number of performance improvements. Please check the [benchmarks results] to see how mlua compares to rlua and rhai.
|
||||
|
||||
[benchmarks results]: https://github.com/khvzak/script-bench-rs
|
||||
[benchmarks results]: https://github.com/mlua-rs/script-bench-rs
|
||||
|
||||
### Changes in `module` mode
|
||||
|
||||
@@ -327,7 +327,7 @@ Under the hood a new function `luaopen_alt_module` will be created for the Lua m
|
||||
|
||||
- `skip_memory_check` - skip memory allocation checks for some operations.
|
||||
|
||||
In module mode, mlua runs in unknown environment and cannot say are there any memory limits or not. As result, some operations that require memory allocation runs in
|
||||
In module mode, mlua runs in an unknown environment and cannot tell whether there are any memory limits or not. As a result, some operations that require memory allocation run in
|
||||
protected mode. Setting this attribute will improve performance of such operations with risk of having uncaught exceptions and memory leaks.
|
||||
|
||||
#### Improved Windows target
|
||||
@@ -336,7 +336,7 @@ In previous mlua versions, building a Lua module for Windows requires having Lua
|
||||
In contrast, on Linux and macOS, modules can be built without any external dependencies using the `-undefined=dynamic_lookup` linker flag.
|
||||
|
||||
With Rust 1.71+ it's now possible to lift this restriction for Windows as well. You can build modules normally and they will be linked with
|
||||
`lua54.dll`/`lua53.dll`/`lua52.dll`/`lua51.dll` depending on the enabled Lua version.
|
||||
`lua5x.dll` depending on the enabled Lua version.
|
||||
|
||||
You still need to have the dll although, linked to application where the module will be loaded.
|
||||
|
||||
|
||||
@@ -5,14 +5,14 @@ use hyper::body::Incoming;
|
||||
use hyper_util::client::legacy::Client as HyperClient;
|
||||
use hyper_util::rt::TokioExecutor;
|
||||
|
||||
use mlua::{chunk, ExternalResult, Lua, Result, UserData, UserDataMethods};
|
||||
use mlua::{ExternalResult, Lua, Result, UserData, UserDataMethods, chunk};
|
||||
|
||||
struct BodyReader(Incoming);
|
||||
|
||||
impl UserData for BodyReader {
|
||||
fn add_methods<'lua, M: UserDataMethods<'lua, Self>>(methods: &mut M) {
|
||||
fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) {
|
||||
// Every call returns a next chunk
|
||||
methods.add_async_method_mut("read", |lua, reader, ()| async move {
|
||||
methods.add_async_method_mut("read", |lua, mut reader, ()| async move {
|
||||
if let Some(bytes) = reader.0.frame().await {
|
||||
if let Some(bytes) = bytes.into_lua_err()?.data_ref() {
|
||||
return Some(lua.create_string(&bytes)).transpose();
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use mlua::{chunk, ExternalResult, Lua, LuaSerdeExt, Result, Value};
|
||||
use mlua::{ExternalResult, Lua, LuaSerdeExt, Result, Value, chunk};
|
||||
|
||||
#[tokio::main(flavor = "current_thread")]
|
||||
async fn main() -> Result<()> {
|
||||
|
||||
@@ -1,27 +1,23 @@
|
||||
use std::convert::Infallible;
|
||||
use std::future::Future;
|
||||
use std::net::SocketAddr;
|
||||
use std::rc::Rc;
|
||||
use std::pin::Pin;
|
||||
|
||||
use futures::future::LocalBoxFuture;
|
||||
use http_body_util::{combinators::BoxBody, BodyExt as _, Empty, Full};
|
||||
use http_body_util::combinators::BoxBody;
|
||||
use http_body_util::{BodyExt as _, Empty, Full};
|
||||
use hyper::body::{Bytes, Incoming};
|
||||
use hyper::server::conn::http1;
|
||||
use hyper::{Request, Response};
|
||||
use hyper_util::rt::TokioIo;
|
||||
use hyper_util::server::conn::auto::Builder as ServerConnBuilder;
|
||||
use tokio::net::TcpListener;
|
||||
use tokio::task::LocalSet;
|
||||
|
||||
use mlua::{
|
||||
chunk, Error as LuaError, Function, Lua, RegistryKey, String as LuaString, Table, UserData,
|
||||
UserDataMethods,
|
||||
};
|
||||
use mlua::{Error as LuaError, Function, Lua, String as LuaString, Table, UserData, UserDataMethods, chunk};
|
||||
|
||||
/// Wrapper around incoming request that implements UserData
|
||||
struct LuaRequest(SocketAddr, Request<Incoming>);
|
||||
|
||||
impl UserData for LuaRequest {
|
||||
fn add_methods<'lua, M: UserDataMethods<'lua, Self>>(methods: &mut M) {
|
||||
fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) {
|
||||
methods.add_method("remote_addr", |_, req, ()| Ok((req.0).to_string()));
|
||||
methods.add_method("method", |_, req, ()| Ok((req.1).method().to_string()));
|
||||
methods.add_method("path", |_, req, ()| Ok(req.1.uri().path().to_string()));
|
||||
@@ -31,50 +27,43 @@ impl UserData for LuaRequest {
|
||||
/// Service that handles incoming requests
|
||||
#[derive(Clone)]
|
||||
pub struct Svc {
|
||||
lua: Rc<Lua>,
|
||||
handler: Rc<RegistryKey>,
|
||||
handler: Function,
|
||||
peer_addr: SocketAddr,
|
||||
}
|
||||
|
||||
impl Svc {
|
||||
pub fn new(lua: Rc<Lua>, handler: Rc<RegistryKey>, peer_addr: SocketAddr) -> Self {
|
||||
Self {
|
||||
lua,
|
||||
handler,
|
||||
peer_addr,
|
||||
}
|
||||
pub fn new(handler: Function, peer_addr: SocketAddr) -> Self {
|
||||
Self { handler, peer_addr }
|
||||
}
|
||||
}
|
||||
|
||||
impl hyper::service::Service<Request<Incoming>> for Svc {
|
||||
type Response = Response<BoxBody<Bytes, Infallible>>;
|
||||
type Error = LuaError;
|
||||
type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;
|
||||
type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
|
||||
|
||||
fn call(&self, req: Request<Incoming>) -> Self::Future {
|
||||
// If handler returns an error then generate 5xx response
|
||||
let lua = self.lua.clone();
|
||||
let handler_key = self.handler.clone();
|
||||
let handler = self.handler.clone();
|
||||
let lua_req = LuaRequest(self.peer_addr, req);
|
||||
Box::pin(async move {
|
||||
let handler: Function = lua.registry_value(&handler_key)?;
|
||||
match handler.call_async::<_, Table>(lua_req).await {
|
||||
match handler.call_async::<Table>(lua_req).await {
|
||||
Ok(lua_resp) => {
|
||||
let status = lua_resp.get::<_, Option<u16>>("status")?.unwrap_or(200);
|
||||
let status = lua_resp.get::<Option<u16>>("status")?.unwrap_or(200);
|
||||
let mut resp = Response::builder().status(status);
|
||||
|
||||
// Set headers
|
||||
if let Some(headers) = lua_resp.get::<_, Option<Table>>("headers")? {
|
||||
if let Some(headers) = lua_resp.get::<Option<Table>>("headers")? {
|
||||
for pair in headers.pairs::<String, LuaString>() {
|
||||
let (h, v) = pair?;
|
||||
resp = resp.header(&h, v.as_bytes());
|
||||
resp = resp.header(&h, &*v.as_bytes());
|
||||
}
|
||||
}
|
||||
|
||||
// Set body
|
||||
let body = lua_resp
|
||||
.get::<_, Option<LuaString>>("body")?
|
||||
.map(|b| Full::new(Bytes::copy_from_slice(b.as_bytes())).boxed())
|
||||
.get::<Option<LuaString>>("body")?
|
||||
.map(|b| Full::new(Bytes::copy_from_slice(&b.as_bytes())).boxed())
|
||||
.unwrap_or_else(|| Empty::<Bytes>::new().boxed());
|
||||
|
||||
Ok(resp.body(body).unwrap())
|
||||
@@ -93,10 +82,10 @@ impl hyper::service::Service<Request<Incoming>> for Svc {
|
||||
|
||||
#[tokio::main(flavor = "current_thread")]
|
||||
async fn main() {
|
||||
let lua = Rc::new(Lua::new());
|
||||
let lua = Lua::new();
|
||||
|
||||
// Create Lua handler function
|
||||
let handler: RegistryKey = lua
|
||||
let handler = lua
|
||||
.load(chunk! {
|
||||
function(req)
|
||||
return {
|
||||
@@ -110,15 +99,13 @@ async fn main() {
|
||||
}
|
||||
end
|
||||
})
|
||||
.eval()
|
||||
.eval::<Function>()
|
||||
.expect("Failed to create Lua handler");
|
||||
let handler = Rc::new(handler);
|
||||
|
||||
let listen_addr = "127.0.0.1:3000";
|
||||
let listener = TcpListener::bind(listen_addr).await.unwrap();
|
||||
println!("Listening on http://{listen_addr}");
|
||||
|
||||
let local = LocalSet::new();
|
||||
loop {
|
||||
let (stream, peer_addr) = match listener.accept().await {
|
||||
Ok(x) => x,
|
||||
@@ -128,29 +115,14 @@ async fn main() {
|
||||
}
|
||||
};
|
||||
|
||||
let svc = Svc::new(lua.clone(), handler.clone(), peer_addr);
|
||||
local
|
||||
.run_until(async move {
|
||||
let result = ServerConnBuilder::new(LocalExec)
|
||||
.http1()
|
||||
.serve_connection(TokioIo::new(stream), svc)
|
||||
.await;
|
||||
if let Err(err) = result {
|
||||
eprintln!("Error serving connection: {err:?}");
|
||||
}
|
||||
})
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct LocalExec;
|
||||
|
||||
impl<F> hyper::rt::Executor<F> for LocalExec
|
||||
where
|
||||
F: Future + 'static, // not requiring `Send`
|
||||
{
|
||||
fn execute(&self, fut: F) {
|
||||
tokio::task::spawn_local(fut);
|
||||
let svc = Svc::new(handler.clone(), peer_addr);
|
||||
tokio::task::spawn(async move {
|
||||
if let Err(err) = http1::Builder::new()
|
||||
.serve_connection(TokioIo::new(stream), svc)
|
||||
.await
|
||||
{
|
||||
eprintln!("Error serving connection: {:?}", err);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,48 +1,42 @@
|
||||
use std::io;
|
||||
use std::net::SocketAddr;
|
||||
use std::rc::Rc;
|
||||
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::{TcpListener, TcpStream};
|
||||
use tokio::task;
|
||||
|
||||
use mlua::{chunk, Function, Lua, RegistryKey, String as LuaString, UserData, UserDataMethods};
|
||||
use mlua::{BString, Function, Lua, UserData, UserDataMethods, chunk};
|
||||
|
||||
struct LuaTcpStream(TcpStream);
|
||||
|
||||
impl UserData for LuaTcpStream {
|
||||
fn add_methods<'lua, M: UserDataMethods<'lua, Self>>(methods: &mut M) {
|
||||
methods.add_method("peer_addr", |_, this, ()| {
|
||||
Ok(this.0.peer_addr()?.to_string())
|
||||
});
|
||||
fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) {
|
||||
methods.add_method("peer_addr", |_, this, ()| Ok(this.0.peer_addr()?.to_string()));
|
||||
|
||||
methods.add_async_method_mut("read", |lua, this, size| async move {
|
||||
methods.add_async_method_mut("read", |lua, mut this, size| async move {
|
||||
let mut buf = vec![0; size];
|
||||
let n = this.0.read(&mut buf).await?;
|
||||
buf.truncate(n);
|
||||
lua.create_string(&buf)
|
||||
});
|
||||
|
||||
methods.add_async_method_mut("write", |_, this, data: LuaString| async move {
|
||||
let n = this.0.write(&data.as_bytes()).await?;
|
||||
methods.add_async_method_mut("write", |_, mut this, data: BString| async move {
|
||||
let n = this.0.write(&data).await?;
|
||||
Ok(n)
|
||||
});
|
||||
|
||||
methods.add_async_method_mut("close", |_, this, ()| async move {
|
||||
methods.add_async_method_mut("close", |_, mut this, ()| async move {
|
||||
this.0.shutdown().await?;
|
||||
Ok(())
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async fn run_server(lua: Lua, handler: RegistryKey) -> io::Result<()> {
|
||||
async fn run_server(handler: Function) -> io::Result<()> {
|
||||
let addr: SocketAddr = ([127, 0, 0, 1], 3000).into();
|
||||
let listener = TcpListener::bind(addr).await.expect("cannot bind addr");
|
||||
|
||||
println!("Listening on {}", addr);
|
||||
|
||||
let lua = Rc::new(lua);
|
||||
let handler = Rc::new(handler);
|
||||
loop {
|
||||
let (stream, _) = match listener.accept().await {
|
||||
Ok(res) => res,
|
||||
@@ -50,15 +44,10 @@ async fn run_server(lua: Lua, handler: RegistryKey) -> io::Result<()> {
|
||||
Err(err) => return Err(err),
|
||||
};
|
||||
|
||||
let lua = lua.clone();
|
||||
let handler = handler.clone();
|
||||
task::spawn_local(async move {
|
||||
let handler: Function = lua
|
||||
.registry_value(&handler)
|
||||
.expect("cannot get Lua handler");
|
||||
|
||||
tokio::task::spawn(async move {
|
||||
let stream = LuaTcpStream(stream);
|
||||
if let Err(err) = handler.call_async::<_, ()>(stream).await {
|
||||
if let Err(err) = handler.call_async::<()>(stream).await {
|
||||
eprintln!("{}", err);
|
||||
}
|
||||
});
|
||||
@@ -70,7 +59,7 @@ async fn main() {
|
||||
let lua = Lua::new();
|
||||
|
||||
// Create Lua handler function
|
||||
let handler_fn = lua
|
||||
let handler = lua
|
||||
.load(chunk! {
|
||||
function(stream)
|
||||
local peer_addr = stream:peer_addr()
|
||||
@@ -92,15 +81,7 @@ async fn main() {
|
||||
.eval::<Function>()
|
||||
.expect("cannot create Lua handler");
|
||||
|
||||
// Store it in the Registry
|
||||
let handler = lua
|
||||
.create_registry_value(handler_fn)
|
||||
.expect("cannot store Lua handler");
|
||||
|
||||
task::LocalSet::new()
|
||||
.run_until(run_server(lua, handler))
|
||||
.await
|
||||
.expect("cannot run server")
|
||||
run_server(handler).await.expect("cannot run server")
|
||||
}
|
||||
|
||||
fn is_transient_error(e: &io::Error) -> bool {
|
||||
|
||||
+14
-19
@@ -1,9 +1,7 @@
|
||||
use std::f32;
|
||||
use std::iter::FromIterator;
|
||||
|
||||
use mlua::{
|
||||
chunk, FromLua, Function, Lua, MetaMethod, Result, UserData, UserDataMethods, Value, Variadic,
|
||||
};
|
||||
use mlua::{FromLua, Function, Lua, MetaMethod, Result, UserData, UserDataMethods, Value, Variadic, chunk};
|
||||
|
||||
fn main() -> Result<()> {
|
||||
// You can create a new Lua state with `Lua::new()`. This loads the default Lua std library
|
||||
@@ -19,8 +17,8 @@ fn main() -> Result<()> {
|
||||
globals.set("string_var", "hello")?;
|
||||
globals.set("int_var", 42)?;
|
||||
|
||||
assert_eq!(globals.get::<_, String>("string_var")?, "hello");
|
||||
assert_eq!(globals.get::<_, i64>("int_var")?, 42);
|
||||
assert_eq!(globals.get::<String>("string_var")?, "hello");
|
||||
assert_eq!(globals.get::<i64>("int_var")?, 42);
|
||||
|
||||
// You can load and evaluate Lua code. The returned type of `Lua::load` is a builder
|
||||
// that allows you to change settings before running Lua code. Here, we are using it to set
|
||||
@@ -34,7 +32,7 @@ fn main() -> Result<()> {
|
||||
)
|
||||
.set_name("example code")
|
||||
.exec()?;
|
||||
assert_eq!(globals.get::<_, String>("global")?, "foobar");
|
||||
assert_eq!(globals.get::<String>("global")?, "foobar");
|
||||
|
||||
assert_eq!(lua.load("1 + 1").eval::<i32>()?, 2);
|
||||
assert_eq!(lua.load("false == false").eval::<bool>()?, true);
|
||||
@@ -87,16 +85,16 @@ fn main() -> Result<()> {
|
||||
// You can load Lua functions
|
||||
|
||||
let print: Function = globals.get("print")?;
|
||||
print.call::<_, ()>("hello from rust")?;
|
||||
print.call::<()>("hello from rust")?;
|
||||
|
||||
// This API generally handles variadic using tuples. This is one way to call a function with
|
||||
// multiple parameters:
|
||||
|
||||
print.call::<_, ()>(("hello", "again", "from", "rust"))?;
|
||||
print.call::<()>(("hello", "again", "from", "rust"))?;
|
||||
|
||||
// But, you can also pass variadic arguments with the `Variadic` type.
|
||||
|
||||
print.call::<_, ()>(Variadic::from_iter(
|
||||
print.call::<()>(Variadic::from_iter(
|
||||
["hello", "yet", "again", "from", "rust"].iter().cloned(),
|
||||
))?;
|
||||
|
||||
@@ -154,8 +152,8 @@ fn main() -> Result<()> {
|
||||
struct Vec2(f32, f32);
|
||||
|
||||
// We can implement `FromLua` trait for our `Vec2` to return a copy
|
||||
impl<'lua> FromLua<'lua> for Vec2 {
|
||||
fn from_lua(value: Value<'lua>, _: &'lua Lua) -> Result<Self> {
|
||||
impl FromLua for Vec2 {
|
||||
fn from_lua(value: Value, _: &Lua) -> Result<Self> {
|
||||
match value {
|
||||
Value::UserData(ud) => Ok(*ud.borrow::<Self>()?),
|
||||
_ => unreachable!(),
|
||||
@@ -164,7 +162,7 @@ fn main() -> Result<()> {
|
||||
}
|
||||
|
||||
impl UserData for Vec2 {
|
||||
fn add_methods<'lua, M: UserDataMethods<'lua, Self>>(methods: &mut M) {
|
||||
fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) {
|
||||
methods.add_method("magnitude", |_, vec, ()| {
|
||||
let mag_squared = vec.0 * vec.0 + vec.1 * vec.1;
|
||||
Ok(mag_squared.sqrt())
|
||||
@@ -179,19 +177,15 @@ fn main() -> Result<()> {
|
||||
let vec2_constructor = lua.create_function(|_, (x, y): (f32, f32)| Ok(Vec2(x, y)))?;
|
||||
globals.set("vec2", vec2_constructor)?;
|
||||
|
||||
assert!(
|
||||
(lua.load("(vec2(1, 2) + vec2(2, 2)):magnitude()")
|
||||
.eval::<f32>()?
|
||||
- 5.0)
|
||||
.abs()
|
||||
< f32::EPSILON
|
||||
);
|
||||
assert!((lua.load("(vec2(1, 2) + vec2(2, 2)):magnitude()").eval::<f32>()? - 5.0).abs() < f32::EPSILON);
|
||||
|
||||
// Normally, Rust types passed to `Lua` must be `'static`, because there is no way to be
|
||||
// sure of their lifetime inside the Lua state. There is, however, a limited way to lift this
|
||||
// requirement. You can call `Lua::scope` to create userdata and callbacks types that only live
|
||||
// for as long as the call to scope, but do not have to be `'static` (and `Send`).
|
||||
|
||||
// TODO: Re-enable this
|
||||
/*
|
||||
{
|
||||
let mut rust_val = 0;
|
||||
|
||||
@@ -213,6 +207,7 @@ fn main() -> Result<()> {
|
||||
|
||||
assert_eq!(rust_val, 42);
|
||||
}
|
||||
*/
|
||||
|
||||
// We were able to run our 'sketchy' function inside the scope just fine. However, if we
|
||||
// try to run our 'sketchy' function outside of the scope, the function we created will have
|
||||
|
||||
@@ -10,6 +10,7 @@ crate-type = ["cdylib"]
|
||||
[workspace]
|
||||
|
||||
[features]
|
||||
lua55 = ["mlua/lua55"]
|
||||
lua54 = ["mlua/lua54"]
|
||||
lua53 = ["mlua/lua53"]
|
||||
lua52 = ["mlua/lua52"]
|
||||
|
||||
+10
-8
@@ -20,14 +20,16 @@ fn main() {
|
||||
match lua.load(&line).eval::<MultiValue>() {
|
||||
Ok(values) => {
|
||||
editor.add_history_entry(line).unwrap();
|
||||
println!(
|
||||
"{}",
|
||||
values
|
||||
.iter()
|
||||
.map(|value| format!("{:#?}", value))
|
||||
.collect::<Vec<_>>()
|
||||
.join("\t")
|
||||
);
|
||||
if values.len() > 0 {
|
||||
println!(
|
||||
"{}",
|
||||
values
|
||||
.iter()
|
||||
.map(|value| format!("{:#?}", value))
|
||||
.collect::<Vec<_>>()
|
||||
.join("\t")
|
||||
);
|
||||
}
|
||||
break;
|
||||
}
|
||||
Err(Error::SyntaxError {
|
||||
|
||||
@@ -28,9 +28,14 @@ fn main() -> Result<()> {
|
||||
let globals = lua.globals();
|
||||
|
||||
// Create Car struct from a Lua table
|
||||
let car: Car = lua.from_value(lua.load(r#"
|
||||
let car: Car = lua.from_value(
|
||||
lua.load(
|
||||
r#"
|
||||
{active = true, model = "Volkswagen Golf", transmission = "Automatic", engine = {v = 1499, kw = 90}}
|
||||
"#).eval()?)?;
|
||||
"#,
|
||||
)
|
||||
.eval()?,
|
||||
)?;
|
||||
|
||||
// Set it as (serializable) userdata
|
||||
globals.set("null", lua.null())?;
|
||||
+28
-27
@@ -1,45 +1,46 @@
|
||||
use mlua::{chunk, Lua, MetaMethod, Result, UserData};
|
||||
use mlua::{Lua, Result, UserData, chunk};
|
||||
|
||||
#[derive(Default)]
|
||||
#[derive(Default, UserData)]
|
||||
struct Rectangle {
|
||||
length: u32,
|
||||
width: u32,
|
||||
}
|
||||
|
||||
impl UserData for Rectangle {
|
||||
fn add_fields<'lua, F: mlua::UserDataFields<'lua, Self>>(fields: &mut F) {
|
||||
fields.add_field_method_get("length", |_, this| Ok(this.length));
|
||||
fields.add_field_method_set("length", |_, this, val| {
|
||||
this.length = val;
|
||||
Ok(())
|
||||
});
|
||||
fields.add_field_method_get("width", |_, this| Ok(this.width));
|
||||
fields.add_field_method_set("width", |_, this, val| {
|
||||
this.width = val;
|
||||
Ok(())
|
||||
});
|
||||
#[mlua::userdata_impl]
|
||||
impl Rectangle {
|
||||
const NAME: &str = "Rectangle";
|
||||
|
||||
#[lua(infallible)]
|
||||
fn new(length: u32, width: u32) -> Self {
|
||||
Self { length, width }
|
||||
}
|
||||
|
||||
fn add_methods<'lua, M: mlua::UserDataMethods<'lua, Self>>(methods: &mut M) {
|
||||
methods.add_method("area", |_, this, ()| Ok(this.length * this.width));
|
||||
methods.add_method("diagonal", |_, this, ()| {
|
||||
Ok((this.length.pow(2) as f64 + this.width.pow(2) as f64).sqrt())
|
||||
});
|
||||
#[lua(getter, name = "area", infallible)]
|
||||
fn calculate_area(&self) -> u32 {
|
||||
self.length * self.width
|
||||
}
|
||||
|
||||
// Constructor
|
||||
methods.add_meta_function(MetaMethod::Call, |_, ()| Ok(Rectangle::default()));
|
||||
fn diagonal(&self) -> Result<f64> {
|
||||
Ok((self.length.pow(2) as f64 + self.width.pow(2) as f64).sqrt())
|
||||
}
|
||||
|
||||
// Constructor via `__call` metamethod
|
||||
#[lua(meta, infallible)]
|
||||
fn __call(length: u32, width: u32) -> Self {
|
||||
Rectangle::new(length, width)
|
||||
}
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let lua = Lua::new();
|
||||
let rectangle = Rectangle::default();
|
||||
lua.globals().set("Rectangle", lua.create_proxy::<Rectangle>()?)?;
|
||||
lua.load(chunk! {
|
||||
local rect = $rectangle()
|
||||
rect.width = 10
|
||||
rect.length = 5
|
||||
assert(rect:area() == 50)
|
||||
assert(rect:diagonal() - 11.1803 < 0.0001)
|
||||
local rect = Rectangle(10, 5)
|
||||
rect.width = rect.width + 5
|
||||
rect.length = rect.length + 5
|
||||
assert(rect.NAME == "Rectangle")
|
||||
assert(rect.area == 150)
|
||||
assert(math.floor(rect:diagonal()) == 18)
|
||||
})
|
||||
.exec()
|
||||
}
|
||||
|
||||
+12
-9
@@ -1,10 +1,10 @@
|
||||
[package]
|
||||
name = "mlua-sys"
|
||||
version = "0.6.2"
|
||||
version = "0.11.0-rc.1"
|
||||
authors = ["Aleksandr Orlenko <zxteam@pm.me>"]
|
||||
rust-version = "1.71"
|
||||
edition = "2021"
|
||||
repository = "https://github.com/khvzak/mlua"
|
||||
rust-version = "1.88"
|
||||
edition = "2024"
|
||||
repository = "https://github.com/mlua-rs/mlua"
|
||||
documentation = "https://docs.rs/mlua-sys"
|
||||
readme = "README.md"
|
||||
categories = ["external-ffi-bindings"]
|
||||
@@ -12,14 +12,15 @@ license = "MIT"
|
||||
links = "lua"
|
||||
build = "build/main.rs"
|
||||
description = """
|
||||
Low level (FFI) bindings to Lua 5.4/5.3/5.2/5.1 (including LuaJIT) and Roblox Luau
|
||||
Low level (FFI) bindings to Lua 5.5/5.4/5.3/5.2/5.1 (including LuaJIT) and Luau
|
||||
"""
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
features = ["lua54", "vendored"]
|
||||
features = ["lua55", "vendored"]
|
||||
rustdoc-args = ["--cfg", "docsrs"]
|
||||
|
||||
[features]
|
||||
lua55 = []
|
||||
lua54 = []
|
||||
lua53 = []
|
||||
lua52 = []
|
||||
@@ -30,17 +31,19 @@ luau = ["luau0-src"]
|
||||
luau-codegen = ["luau"]
|
||||
luau-vector4 = ["luau"]
|
||||
vendored = ["lua-src", "luajit-src"]
|
||||
external = []
|
||||
module = []
|
||||
|
||||
[dependencies]
|
||||
libc = "0.2"
|
||||
|
||||
[build-dependencies]
|
||||
cc = "1.0"
|
||||
cfg-if = "1.0"
|
||||
pkg-config = "0.3.17"
|
||||
lua-src = { version = ">= 547.0.0, < 547.1.0", optional = true }
|
||||
luajit-src = { version = ">= 210.5.0, < 210.6.0", optional = true }
|
||||
luau0-src = { version = "0.10.0", optional = true }
|
||||
lua-src = { version = ">= 550.1.0, < 550.2.0", optional = true }
|
||||
luajit-src = { version = ">= 210.7.0, < 210.8.0", optional = true }
|
||||
luau0-src = { version = "0.20.0", optional = true }
|
||||
|
||||
[lints.rust]
|
||||
unexpected_cfgs = { level = "allow", check-cfg = ['cfg(raw_dylib)'] }
|
||||
|
||||
+3
-2
@@ -1,8 +1,9 @@
|
||||
# mlua-sys
|
||||
|
||||
Low level (FFI) bindings to Lua 5.4/5.3/5.2/5.1 (including LuaJIT) and Roblox [Luau].
|
||||
Low level (FFI) bindings to Lua 5.5/5.4/5.3/5.2/5.1 (including [LuaJIT]) and [Luau].
|
||||
|
||||
Intended to be consumed by the [mlua] crate.
|
||||
|
||||
[Luau]: https://github.com/Roblox/luau
|
||||
[LuaJIT]: https://github.com/LuaJIT/LuaJIT
|
||||
[Luau]: https://github.com/luau-lang/luau
|
||||
[mlua]: https://crates.io/crates/mlua
|
||||
|
||||
@@ -31,16 +31,18 @@ pub fn probe_lua() {
|
||||
|
||||
// Find using `pkg-config`
|
||||
|
||||
#[cfg(feature = "lua55")]
|
||||
let (incl_bound, excl_bound, alt_probe, ver) = ("5.5", "5.6", ["lua5.5", "lua-5.5", "lua55"], "5.5");
|
||||
#[cfg(feature = "lua54")]
|
||||
let (incl_bound, excl_bound, alt_probe, ver) = ("5.4", "5.5", Some("lua5.4"), "5.4");
|
||||
let (incl_bound, excl_bound, alt_probe, ver) = ("5.4", "5.5", ["lua5.4", "lua-5.4", "lua54"], "5.4");
|
||||
#[cfg(feature = "lua53")]
|
||||
let (incl_bound, excl_bound, alt_probe, ver) = ("5.3", "5.4", Some("lua5.3"), "5.3");
|
||||
let (incl_bound, excl_bound, alt_probe, ver) = ("5.3", "5.4", ["lua5.3", "lua-5.3", "lua53"], "5.3");
|
||||
#[cfg(feature = "lua52")]
|
||||
let (incl_bound, excl_bound, alt_probe, ver) = ("5.2", "5.3", Some("lua5.2"), "5.2");
|
||||
let (incl_bound, excl_bound, alt_probe, ver) = ("5.2", "5.3", ["lua5.2", "lua-5.2", "lua52"], "5.2");
|
||||
#[cfg(feature = "lua51")]
|
||||
let (incl_bound, excl_bound, alt_probe, ver) = ("5.1", "5.2", Some("lua5.1"), "5.1");
|
||||
let (incl_bound, excl_bound, alt_probe, ver) = ("5.1", "5.2", ["lua5.1", "lua-5.1", "lua51"], "5.1");
|
||||
#[cfg(feature = "luajit")]
|
||||
let (incl_bound, excl_bound, alt_probe, ver) = ("2.0.4", "2.2", None, "JIT");
|
||||
let (incl_bound, excl_bound, alt_probe, ver) = ("2.0.4", "2.2", [], "JIT");
|
||||
|
||||
#[rustfmt::skip]
|
||||
let mut lua = pkg_config::Config::new()
|
||||
@@ -48,10 +50,14 @@ pub fn probe_lua() {
|
||||
.cargo_metadata(true)
|
||||
.probe(if cfg!(feature = "luajit") { "luajit" } else { "lua" });
|
||||
|
||||
if lua.is_err() && alt_probe.is_some() {
|
||||
lua = pkg_config::Config::new()
|
||||
.cargo_metadata(true)
|
||||
.probe(alt_probe.unwrap());
|
||||
if lua.is_err() {
|
||||
for pkg in alt_probe {
|
||||
lua = pkg_config::Config::new().cargo_metadata(true).probe(pkg);
|
||||
|
||||
if lua.is_ok() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
lua.unwrap_or_else(|err| panic!("cannot find Lua{ver} using `pkg-config`: {err}"));
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
#![allow(dead_code)]
|
||||
|
||||
pub fn probe_lua() {
|
||||
#[cfg(feature = "lua55")]
|
||||
let artifacts = lua_src::Build::new().build(lua_src::Lua55);
|
||||
|
||||
#[cfg(feature = "lua54")]
|
||||
let artifacts = lua_src::Build::new().build(lua_src::Lua54);
|
||||
|
||||
|
||||
@@ -1,19 +1,21 @@
|
||||
cfg_if::cfg_if! {
|
||||
if #[cfg(all(feature = "lua54", not(any(feature = "lua53", feature = "lua52", feature = "lua51", feature = "luajit", feature = "luau"))))] {
|
||||
if #[cfg(all(feature = "lua55", not(any(feature = "lua54", feature = "lua53", feature = "lua52", feature = "lua51", feature = "luajit", feature = "luau"))))] {
|
||||
include!("main_inner.rs");
|
||||
} else if #[cfg(all(feature = "lua53", not(any(feature = "lua54", feature = "lua52", feature = "lua51", feature = "luajit", feature = "luau"))))] {
|
||||
} else if #[cfg(all(feature = "lua54", not(any(feature = "lua55", feature = "lua53", feature = "lua52", feature = "lua51", feature = "luajit", feature = "luau"))))] {
|
||||
include!("main_inner.rs");
|
||||
} else if #[cfg(all(feature = "lua52", not(any(feature = "lua54", feature = "lua53", feature = "lua51", feature = "luajit", feature = "luau"))))] {
|
||||
} else if #[cfg(all(feature = "lua53", not(any(feature = "lua55", feature = "lua54", feature = "lua52", feature = "lua51", feature = "luajit", feature = "luau"))))] {
|
||||
include!("main_inner.rs");
|
||||
} else if #[cfg(all(feature = "lua51", not(any(feature = "lua54", feature = "lua53", feature = "lua52", feature = "luajit", feature = "luau"))))] {
|
||||
} else if #[cfg(all(feature = "lua52", not(any(feature = "lua55", feature = "lua54", feature = "lua53", feature = "lua51", feature = "luajit", feature = "luau"))))] {
|
||||
include!("main_inner.rs");
|
||||
} else if #[cfg(all(feature = "luajit", not(any(feature = "lua54", feature = "lua53", feature = "lua52", feature = "lua51", feature = "luau"))))] {
|
||||
} else if #[cfg(all(feature = "lua51", not(any(feature = "lua55", feature = "lua54", feature = "lua53", feature = "lua52", feature = "luajit", feature = "luau"))))] {
|
||||
include!("main_inner.rs");
|
||||
} else if #[cfg(all(feature = "luau", not(any(feature = "lua54", feature = "lua53", feature = "lua52", feature = "lua51", feature = "luajit"))))] {
|
||||
} else if #[cfg(all(feature = "luajit", not(any(feature = "lua55", feature = "lua54", feature = "lua53", feature = "lua52", feature = "lua51", feature = "luau"))))] {
|
||||
include!("main_inner.rs");
|
||||
} else if #[cfg(all(feature = "luau", not(any(feature = "lua55", feature = "lua54", feature = "lua53", feature = "lua52", feature = "lua51", feature = "luajit"))))] {
|
||||
include!("main_inner.rs");
|
||||
} else {
|
||||
fn main() {
|
||||
compile_error!("You can enable only one of the features: lua54, lua53, lua52, lua51, luajit, luajit52, luau");
|
||||
compile_error!("You can enable only one of the features: lua55, lua54, lua53, lua52, lua51, luajit, luajit52, luau");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,22 +14,29 @@ fn main() {
|
||||
#[cfg(all(feature = "luau", feature = "module", windows))]
|
||||
compile_error!("Luau does not support `module` mode on Windows");
|
||||
|
||||
#[cfg(all(feature = "module", feature = "vendored"))]
|
||||
compile_error!("`vendored` and `module` features are mutually exclusive");
|
||||
#[cfg(any(
|
||||
all(feature = "vendored", any(feature = "external", feature = "module")),
|
||||
all(feature = "external", any(feature = "vendored", feature = "module")),
|
||||
all(feature = "module", any(feature = "vendored", feature = "external"))
|
||||
))]
|
||||
compile_error!("`vendored`, `external` and `module` features are mutually exclusive");
|
||||
|
||||
println!("cargo:rerun-if-changed=build");
|
||||
|
||||
let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap();
|
||||
if target_os == "windows" && cfg!(feature = "module") {
|
||||
if !std::env::var("LUA_LIB_NAME").unwrap_or_default().is_empty() {
|
||||
// Don't use raw-dylib linking
|
||||
find::probe_lua();
|
||||
return;
|
||||
// Check if compilation and linking is handled by external crate
|
||||
if cfg!(not(feature = "external")) {
|
||||
let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap();
|
||||
if target_os == "windows" && cfg!(feature = "module") {
|
||||
if !std::env::var("LUA_LIB_NAME").unwrap_or_default().is_empty() {
|
||||
// Don't use raw-dylib linking
|
||||
find::probe_lua();
|
||||
return;
|
||||
}
|
||||
|
||||
println!("cargo:rustc-cfg=raw_dylib");
|
||||
}
|
||||
|
||||
println!("cargo:rustc-cfg=raw_dylib");
|
||||
#[cfg(not(feature = "module"))]
|
||||
find::probe_lua();
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "module"))]
|
||||
find::probe_lua();
|
||||
}
|
||||
|
||||
+33
-26
@@ -1,12 +1,16 @@
|
||||
//! Low level bindings to Lua 5.4/5.3/5.2/5.1 (including LuaJIT) and Roblox Luau.
|
||||
//! Low level bindings to Lua 5.5/5.4/5.3/5.2/5.1 (including LuaJIT) and Luau.
|
||||
|
||||
#![allow(non_camel_case_types, non_snake_case, dead_code)]
|
||||
#![allow(non_camel_case_types, non_snake_case)]
|
||||
#![allow(clippy::missing_safety_doc)]
|
||||
#![allow(unsafe_op_in_unsafe_fn)]
|
||||
#![doc(test(attr(deny(warnings))))]
|
||||
#![cfg_attr(docsrs, feature(doc_cfg))]
|
||||
|
||||
use std::os::raw::c_int;
|
||||
|
||||
#[cfg(any(feature = "lua55", doc))]
|
||||
pub use lua55::*;
|
||||
|
||||
#[cfg(any(feature = "lua54", doc))]
|
||||
pub use lua54::*;
|
||||
|
||||
@@ -22,7 +26,7 @@ pub use lua51::*;
|
||||
#[cfg(any(feature = "luau", doc))]
|
||||
pub use luau::*;
|
||||
|
||||
#[cfg(any(feature = "lua54", feature = "lua53", feature = "lua52"))]
|
||||
#[cfg(any(feature = "lua55", feature = "lua54", feature = "lua53", feature = "lua52"))]
|
||||
#[doc(hidden)]
|
||||
pub const LUA_MAX_UPVALUES: c_int = 255;
|
||||
|
||||
@@ -39,14 +43,22 @@ pub const LUA_MAX_UPVALUES: c_int = 200;
|
||||
#[doc(hidden)]
|
||||
pub const LUA_TRACEBACK_STACK: c_int = 11;
|
||||
|
||||
// Copied from https://github.com/rust-lang/rust/blob/master/library/std/src/sys/pal/common/alloc.rs
|
||||
// The minimum alignment guaranteed by the architecture. This value is used to
|
||||
// add fast paths for low alignment values.
|
||||
#[cfg(any(
|
||||
// The minimum alignment guaranteed by the architecture.
|
||||
// Copied from https://github.com/rust-lang/rust/blob/main/library/std/src/sys/alloc/mod.rs
|
||||
#[doc(hidden)]
|
||||
#[rustfmt::skip]
|
||||
pub const SYS_MIN_ALIGN: usize = if cfg!(any(
|
||||
all(target_arch = "riscv32", any(target_os = "espidf", target_os = "zkvm")),
|
||||
all(target_arch = "xtensa", target_os = "espidf"),
|
||||
)) {
|
||||
// The allocator on the esp-idf and zkvm platforms guarantees 4 byte alignment.
|
||||
4
|
||||
} else if cfg!(any(
|
||||
target_arch = "x86",
|
||||
target_arch = "arm",
|
||||
target_arch = "m68k",
|
||||
target_arch = "csky",
|
||||
target_arch = "loongarch32",
|
||||
target_arch = "mips",
|
||||
target_arch = "mips32r6",
|
||||
target_arch = "powerpc",
|
||||
@@ -54,15 +66,11 @@ pub const LUA_TRACEBACK_STACK: c_int = 11;
|
||||
target_arch = "sparc",
|
||||
target_arch = "wasm32",
|
||||
target_arch = "hexagon",
|
||||
all(
|
||||
target_arch = "riscv32",
|
||||
not(any(target_os = "espidf", target_os = "zkvm"))
|
||||
),
|
||||
all(target_arch = "xtensa", not(target_os = "espidf")),
|
||||
))]
|
||||
#[doc(hidden)]
|
||||
pub const SYS_MIN_ALIGN: usize = 8;
|
||||
#[cfg(any(
|
||||
target_arch = "riscv32",
|
||||
target_arch = "xtensa",
|
||||
)) {
|
||||
8
|
||||
} else if cfg!(any(
|
||||
target_arch = "x86_64",
|
||||
target_arch = "aarch64",
|
||||
target_arch = "arm64ec",
|
||||
@@ -73,20 +81,19 @@ pub const SYS_MIN_ALIGN: usize = 8;
|
||||
target_arch = "sparc64",
|
||||
target_arch = "riscv64",
|
||||
target_arch = "wasm64",
|
||||
))]
|
||||
#[doc(hidden)]
|
||||
pub const SYS_MIN_ALIGN: usize = 16;
|
||||
// The allocator on the esp-idf and zkvm platforms guarantee 4 byte alignment.
|
||||
#[cfg(any(
|
||||
all(target_arch = "riscv32", any(target_os = "espidf", target_os = "zkvm")),
|
||||
all(target_arch = "xtensa", target_os = "espidf"),
|
||||
))]
|
||||
#[doc(hidden)]
|
||||
pub const SYS_MIN_ALIGN: usize = 4;
|
||||
)) {
|
||||
16
|
||||
} else {
|
||||
panic!("no value for SYS_MIN_ALIGN")
|
||||
};
|
||||
|
||||
#[macro_use]
|
||||
mod macros;
|
||||
|
||||
#[cfg(any(feature = "lua55", doc))]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "lua55")))]
|
||||
pub mod lua55;
|
||||
|
||||
#[cfg(any(feature = "lua54", doc))]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "lua54")))]
|
||||
pub mod lua54;
|
||||
|
||||
@@ -2,9 +2,9 @@
|
||||
//!
|
||||
//! Based on github.com/keplerproject/lua-compat-5.3
|
||||
|
||||
use std::mem;
|
||||
use std::ffi::CStr;
|
||||
use std::os::raw::{c_char, c_int, c_void};
|
||||
use std::ptr;
|
||||
use std::{mem, ptr};
|
||||
|
||||
use super::lauxlib::*;
|
||||
use super::lua::*;
|
||||
@@ -21,8 +21,8 @@ unsafe fn compat53_reverse(L: *mut lua_State, mut a: c_int, mut b: c_int) {
|
||||
}
|
||||
}
|
||||
|
||||
const COMPAT53_LEVELS1: c_int = 12; // size of the first part of the stack
|
||||
const COMPAT53_LEVELS2: c_int = 10; // size of the second part of the stack
|
||||
const COMPAT53_LEVELS1: c_int = 10; // size of the first part of the stack
|
||||
const COMPAT53_LEVELS2: c_int = 11; // size of the second part of the stack
|
||||
|
||||
unsafe fn compat53_countlevels(L: *mut lua_State) -> c_int {
|
||||
let mut ar: lua_Debug = mem::zeroed();
|
||||
@@ -55,11 +55,7 @@ unsafe fn compat53_checkmode(
|
||||
while *st != 0 && *st != c {
|
||||
st = st.offset(1);
|
||||
}
|
||||
if *st == c {
|
||||
st
|
||||
} else {
|
||||
ptr::null()
|
||||
}
|
||||
if *st == c { st } else { ptr::null() }
|
||||
}
|
||||
|
||||
if !mode.is_null() && strchr(mode, *modename).is_null() {
|
||||
@@ -89,11 +85,10 @@ unsafe fn compat53_findfield(L: *mut lua_State, objidx: c_int, level: c_int) ->
|
||||
lua_pop(L, 1); // remove value (but keep name)
|
||||
return 1;
|
||||
} else if compat53_findfield(L, objidx, level - 1) != 0 {
|
||||
// try recursively
|
||||
lua_remove(L, -2); // remove table (but keep name)
|
||||
lua_pushliteral(L, ".");
|
||||
lua_insert(L, -2); // place '.' between the two names
|
||||
lua_concat(L, 3);
|
||||
// stack: lib_name, lib_table, field_name (top)
|
||||
lua_pushliteral(L, c"."); // place '.' between the two names
|
||||
lua_replace(L, -3); // (in the slot occupied by table)
|
||||
lua_concat(L, 3); // lib_name.field_name
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
@@ -102,13 +97,20 @@ unsafe fn compat53_findfield(L: *mut lua_State, objidx: c_int, level: c_int) ->
|
||||
0 // not found
|
||||
}
|
||||
|
||||
unsafe fn compat53_pushglobalfuncname(L: *mut lua_State, ar: *mut lua_Debug) -> c_int {
|
||||
unsafe fn compat53_pushglobalfuncname(L: *mut lua_State, L1: *mut lua_State, ar: *mut lua_Debug) -> c_int {
|
||||
let top = lua_gettop(L);
|
||||
lua_getinfo(L, cstr!("f"), ar); // push function
|
||||
lua_getinfo(L1, cstr!("f"), ar); // push function
|
||||
lua_xmove(L1, L, 1); // and move onto L
|
||||
lua_pushvalue(L, LUA_GLOBALSINDEX);
|
||||
luaL_checkstack(L, 6, cstr!("not enough stack")); // slots for 'findfield'
|
||||
if compat53_findfield(L, top + 1, 2) != 0 {
|
||||
let name = lua_tostring(L, -1);
|
||||
if CStr::from_ptr(name).to_bytes().starts_with(b"_G.") {
|
||||
lua_pushstring(L, name.add(3)); // push name without prefix
|
||||
lua_remove(L, -2); // remove original name
|
||||
}
|
||||
lua_copy(L, -1, top + 1); // move name to proper place
|
||||
lua_pop(L, 2); // remove pushed values
|
||||
lua_settop(L, top + 1); // remove pushed values
|
||||
1
|
||||
} else {
|
||||
lua_settop(L, top); // remove function and global table
|
||||
@@ -116,27 +118,23 @@ unsafe fn compat53_pushglobalfuncname(L: *mut lua_State, ar: *mut lua_Debug) ->
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn compat53_pushfuncname(L: *mut lua_State, ar: *mut lua_Debug) {
|
||||
if *(*ar).namewhat != b'\0' as c_char {
|
||||
// is there a name?
|
||||
lua_pushfstring(L, cstr!("function '%s'"), (*ar).name);
|
||||
unsafe fn compat53_pushfuncname(L: *mut lua_State, L1: *mut lua_State, ar: *mut lua_Debug) {
|
||||
// try first a global name
|
||||
if compat53_pushglobalfuncname(L, L1, ar) != 0 {
|
||||
lua_pushfstring(L, cstr!("function '%s'"), lua_tostring(L, -1));
|
||||
lua_remove(L, -2); // remove name
|
||||
} else if *(*ar).namewhat != b'\0' as c_char {
|
||||
// use name from code
|
||||
lua_pushfstring(L, cstr!("%s '%s'"), (*ar).namewhat, (*ar).name);
|
||||
} else if *(*ar).what == b'm' as c_char {
|
||||
// main?
|
||||
lua_pushliteral(L, "main chunk");
|
||||
} else if *(*ar).what == b'C' as c_char {
|
||||
if compat53_pushglobalfuncname(L, ar) != 0 {
|
||||
lua_pushfstring(L, cstr!("function '%s'"), lua_tostring(L, -1));
|
||||
lua_remove(L, -2); // remove name
|
||||
} else {
|
||||
lua_pushliteral(L, "?");
|
||||
}
|
||||
lua_pushliteral(L, c"main chunk");
|
||||
} else if *(*ar).what != b'C' as c_char {
|
||||
// for Lua functions, use <file:line>
|
||||
let short_src = (*ar).short_src.as_ptr();
|
||||
lua_pushfstring(L, cstr!("function <%s:%d>"), short_src, (*ar).linedefined);
|
||||
} else {
|
||||
lua_pushfstring(
|
||||
L,
|
||||
cstr!("function <%s:%d>"),
|
||||
(*ar).short_src.as_ptr(),
|
||||
(*ar).linedefined,
|
||||
);
|
||||
lua_pushliteral(L, c"?");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -177,7 +175,7 @@ pub unsafe fn lua_rotate(L: *mut lua_State, mut idx: c_int, mut n: c_int) {
|
||||
#[inline(always)]
|
||||
pub unsafe fn lua_copy(L: *mut lua_State, fromidx: c_int, toidx: c_int) {
|
||||
let abs_to = lua_absindex(L, toidx);
|
||||
luaL_checkstack(L, 1, cstr!("not enough stack slots"));
|
||||
luaL_checkstack(L, 1, cstr!("not enough stack slots available"));
|
||||
lua_pushvalue(L, fromidx);
|
||||
lua_replace(L, abs_to);
|
||||
}
|
||||
@@ -187,7 +185,8 @@ pub unsafe fn lua_isinteger(L: *mut lua_State, idx: c_int) -> c_int {
|
||||
if lua_type(L, idx) == LUA_TNUMBER {
|
||||
let n = lua_tonumber(L, idx);
|
||||
let i = lua_tointeger(L, idx);
|
||||
if (n - i as lua_Number).abs() < lua_Number::EPSILON {
|
||||
// Lua 5.3+ returns "false" for `-0.0`
|
||||
if n.to_bits() == (i as lua_Number).to_bits() {
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
@@ -315,7 +314,7 @@ pub unsafe fn lua_rawseti(L: *mut lua_State, idx: c_int, n: lua_Integer) {
|
||||
#[inline(always)]
|
||||
pub unsafe fn lua_rawsetp(L: *mut lua_State, idx: c_int, p: *const c_void) {
|
||||
let abs_i = lua_absindex(L, idx);
|
||||
luaL_checkstack(L, 1, cstr!("not enough stack slots"));
|
||||
luaL_checkstack(L, 1, cstr!("not enough stack slots available"));
|
||||
lua_pushlightuserdata(L, p as *mut c_void);
|
||||
lua_insert(L, -2);
|
||||
lua_rawset(L, abs_i);
|
||||
@@ -328,12 +327,7 @@ pub unsafe fn lua_setuservalue(L: *mut lua_State, idx: c_int) {
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn lua_dump(
|
||||
L: *mut lua_State,
|
||||
writer: lua_Writer,
|
||||
data: *mut c_void,
|
||||
_strip: c_int,
|
||||
) -> c_int {
|
||||
pub unsafe fn lua_dump(L: *mut lua_State, writer: lua_Writer, data: *mut c_void, _strip: c_int) -> c_int {
|
||||
lua_dump_(L, writer, data)
|
||||
}
|
||||
|
||||
@@ -365,12 +359,7 @@ pub unsafe fn lua_pushglobaltable(L: *mut lua_State) {
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn lua_resume(
|
||||
L: *mut lua_State,
|
||||
_from: *mut lua_State,
|
||||
narg: c_int,
|
||||
nres: *mut c_int,
|
||||
) -> c_int {
|
||||
pub unsafe fn lua_resume(L: *mut lua_State, _from: *mut lua_State, narg: c_int, nres: *mut c_int) -> c_int {
|
||||
let ret = lua_resume_(L, narg);
|
||||
if (ret == LUA_OK || ret == LUA_YIELD) && !(nres.is_null()) {
|
||||
*nres = lua_gettop(L);
|
||||
@@ -388,7 +377,7 @@ pub unsafe fn luaL_checkstack(L: *mut lua_State, sz: c_int, msg: *const c_char)
|
||||
if !msg.is_null() {
|
||||
luaL_error(L, cstr!("stack overflow (%s)"), msg);
|
||||
} else {
|
||||
lua_pushliteral(L, "stack overflow");
|
||||
lua_pushliteral(L, c"stack overflow");
|
||||
lua_error(L);
|
||||
}
|
||||
}
|
||||
@@ -414,6 +403,25 @@ pub unsafe fn luaL_newmetatable(L: *mut lua_State, tname: *const c_char) -> c_in
|
||||
}
|
||||
}
|
||||
|
||||
pub unsafe fn luaL_loadbufferenv(
|
||||
L: *mut lua_State,
|
||||
data: *const c_char,
|
||||
size: usize,
|
||||
name: *const c_char,
|
||||
mode: *const c_char,
|
||||
mut env: c_int,
|
||||
) -> c_int {
|
||||
if env != 0 {
|
||||
env = lua_absindex(L, env);
|
||||
}
|
||||
let status = luaL_loadbufferx(L, data, size, name, mode);
|
||||
if status == LUA_OK && env != 0 {
|
||||
lua_pushvalue(L, env);
|
||||
lua_setfenv(L, -2);
|
||||
}
|
||||
status
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn luaL_loadbufferx(
|
||||
L: *mut lua_State,
|
||||
@@ -436,7 +444,7 @@ pub unsafe fn luaL_loadbufferx(
|
||||
#[inline(always)]
|
||||
pub unsafe fn luaL_len(L: *mut lua_State, idx: c_int) -> lua_Integer {
|
||||
let mut isnum = 0;
|
||||
luaL_checkstack(L, 1, cstr!("not enough stack slots"));
|
||||
luaL_checkstack(L, 1, cstr!("not enough stack slots available"));
|
||||
lua_len(L, idx);
|
||||
let res = lua_tointegerx(L, -1, &mut isnum);
|
||||
lua_pop(L, 1);
|
||||
@@ -446,41 +454,40 @@ pub unsafe fn luaL_len(L: *mut lua_State, idx: c_int) -> lua_Integer {
|
||||
res
|
||||
}
|
||||
|
||||
pub unsafe fn luaL_traceback(
|
||||
L: *mut lua_State,
|
||||
L1: *mut lua_State,
|
||||
msg: *const c_char,
|
||||
mut level: c_int,
|
||||
) {
|
||||
pub unsafe fn luaL_traceback(L: *mut lua_State, L1: *mut lua_State, msg: *const c_char, mut level: c_int) {
|
||||
let mut ar: lua_Debug = mem::zeroed();
|
||||
let top = lua_gettop(L);
|
||||
let numlevels = compat53_countlevels(L1);
|
||||
let mark = if numlevels > COMPAT53_LEVELS1 + COMPAT53_LEVELS2 {
|
||||
COMPAT53_LEVELS1
|
||||
} else {
|
||||
0
|
||||
};
|
||||
#[rustfmt::skip]
|
||||
let mut limit = if numlevels - level > COMPAT53_LEVELS1 + COMPAT53_LEVELS2 { COMPAT53_LEVELS1 } else { -1 };
|
||||
|
||||
if !msg.is_null() {
|
||||
lua_pushfstring(L, cstr!("%s\n"), msg);
|
||||
}
|
||||
lua_pushliteral(L, "stack traceback:");
|
||||
lua_pushliteral(L, c"stack traceback:");
|
||||
while lua_getstack(L1, level, &mut ar) != 0 {
|
||||
level += 1;
|
||||
if level == mark {
|
||||
if limit == 0 {
|
||||
// too many levels?
|
||||
lua_pushliteral(L, "\n\t..."); // add a '...'
|
||||
level = numlevels - COMPAT53_LEVELS2; // and skip to last ones
|
||||
let n = numlevels - level - COMPAT53_LEVELS2;
|
||||
// add warning about skip ("n + 1" because we skip current level too)
|
||||
lua_pushfstring(L, cstr!("\n\t...\t(skipping %d levels)"), n + 1); // add warning about skip
|
||||
level += n; // and skip to last levels
|
||||
} else {
|
||||
lua_getinfo(L1, cstr!("Slnt"), &mut ar);
|
||||
lua_pushfstring(L, cstr!("\n\t%s:"), ar.short_src.as_ptr());
|
||||
if ar.currentline > 0 {
|
||||
lua_pushfstring(L, cstr!("%d:"), ar.currentline);
|
||||
lua_getinfo(L1, cstr!("Sln"), &mut ar);
|
||||
if *ar.what != b't' as c_char {
|
||||
if ar.currentline <= 0 {
|
||||
lua_pushfstring(L, cstr!("\n\t%s: in "), ar.short_src.as_ptr());
|
||||
} else {
|
||||
lua_pushfstring(L, cstr!("\n\t%s:%d: in "), ar.short_src.as_ptr(), ar.currentline);
|
||||
}
|
||||
compat53_pushfuncname(L, L1, &mut ar);
|
||||
lua_concat(L, lua_gettop(L) - top);
|
||||
} else {
|
||||
lua_pushstring(L, cstr!("\n\t(...tail calls...)"));
|
||||
}
|
||||
lua_pushliteral(L, " in ");
|
||||
compat53_pushfuncname(L, &mut ar);
|
||||
lua_concat(L, lua_gettop(L) - top);
|
||||
}
|
||||
level += 1;
|
||||
limit -= 1;
|
||||
}
|
||||
lua_concat(L, lua_gettop(L) - top);
|
||||
}
|
||||
@@ -490,16 +497,16 @@ pub unsafe fn luaL_tolstring(L: *mut lua_State, mut idx: c_int, len: *mut usize)
|
||||
if luaL_callmeta(L, idx, cstr!("__tostring")) == 0 {
|
||||
match lua_type(L, idx) {
|
||||
LUA_TNIL => {
|
||||
lua_pushliteral(L, "nil");
|
||||
lua_pushliteral(L, c"nil");
|
||||
}
|
||||
LUA_TSTRING | LUA_TNUMBER => {
|
||||
lua_pushvalue(L, idx);
|
||||
}
|
||||
LUA_TBOOLEAN => {
|
||||
if lua_toboolean(L, idx) == 0 {
|
||||
lua_pushliteral(L, "false");
|
||||
lua_pushliteral(L, c"false");
|
||||
} else {
|
||||
lua_pushliteral(L, "true");
|
||||
lua_pushliteral(L, c"true");
|
||||
}
|
||||
}
|
||||
t => {
|
||||
@@ -523,14 +530,14 @@ pub unsafe fn luaL_tolstring(L: *mut lua_State, mut idx: c_int, len: *mut usize)
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn luaL_setmetatable(L: *mut lua_State, tname: *const c_char) {
|
||||
luaL_checkstack(L, 1, cstr!("not enough stack slots"));
|
||||
luaL_checkstack(L, 1, cstr!("not enough stack slots available"));
|
||||
luaL_getmetatable(L, tname);
|
||||
lua_setmetatable(L, -2);
|
||||
}
|
||||
|
||||
pub unsafe fn luaL_getsubtable(L: *mut lua_State, idx: c_int, fname: *const c_char) -> c_int {
|
||||
let abs_i = lua_absindex(L, idx);
|
||||
luaL_checkstack(L, 3, cstr!("not enough stack slots"));
|
||||
luaL_checkstack(L, 3, cstr!("not enough stack slots available"));
|
||||
lua_pushstring_(L, fname);
|
||||
if lua_gettable(L, abs_i) == LUA_TTABLE {
|
||||
return 1;
|
||||
@@ -543,14 +550,9 @@ pub unsafe fn luaL_getsubtable(L: *mut lua_State, idx: c_int, fname: *const c_ch
|
||||
0
|
||||
}
|
||||
|
||||
pub unsafe fn luaL_requiref(
|
||||
L: *mut lua_State,
|
||||
modname: *const c_char,
|
||||
openf: lua_CFunction,
|
||||
glb: c_int,
|
||||
) {
|
||||
pub unsafe fn luaL_requiref(L: *mut lua_State, modname: *const c_char, openf: lua_CFunction, glb: c_int) {
|
||||
luaL_checkstack(L, 3, cstr!("not enough stack slots available"));
|
||||
luaL_getsubtable(L, LUA_REGISTRYINDEX, cstr!("_LOADED"));
|
||||
luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE);
|
||||
if lua_getfield(L, -1, modname) == LUA_TNIL {
|
||||
lua_pop(L, 1);
|
||||
lua_pushcfunction(L, openf);
|
||||
|
||||
@@ -8,6 +8,9 @@ use super::lua::{self, lua_CFunction, lua_Integer, lua_Number, lua_State};
|
||||
// Extra error code for 'luaL_load'
|
||||
pub const LUA_ERRFILE: c_int = lua::LUA_ERRERR + 1;
|
||||
|
||||
// Key, in the registry, for table of loaded modules
|
||||
pub const LUA_LOADED_TABLE: *const c_char = cstr!("_LOADED");
|
||||
|
||||
#[repr(C)]
|
||||
pub struct luaL_Reg {
|
||||
pub name: *const c_char,
|
||||
@@ -15,7 +18,7 @@ pub struct luaL_Reg {
|
||||
}
|
||||
|
||||
#[cfg_attr(all(windows, raw_dylib), link(name = "lua51", kind = "raw-dylib"))]
|
||||
extern "C-unwind" {
|
||||
unsafe extern "C-unwind" {
|
||||
pub fn luaL_register(L: *mut lua_State, libname: *const c_char, l: *const luaL_Reg);
|
||||
#[link_name = "luaL_getmetafield"]
|
||||
pub fn luaL_getmetafield_(L: *mut lua_State, obj: c_int, e: *const c_char) -> c_int;
|
||||
@@ -58,17 +61,12 @@ pub const LUA_NOREF: c_int = -2;
|
||||
pub const LUA_REFNIL: c_int = -1;
|
||||
|
||||
#[cfg_attr(all(windows, raw_dylib), link(name = "lua51", kind = "raw-dylib"))]
|
||||
extern "C-unwind" {
|
||||
unsafe extern "C-unwind" {
|
||||
pub fn luaL_ref(L: *mut lua_State, t: c_int) -> c_int;
|
||||
pub fn luaL_unref(L: *mut lua_State, t: c_int, r#ref: c_int);
|
||||
|
||||
pub fn luaL_loadfile(L: *mut lua_State, filename: *const c_char) -> c_int;
|
||||
pub fn luaL_loadbuffer(
|
||||
L: *mut lua_State,
|
||||
buff: *const c_char,
|
||||
sz: usize,
|
||||
name: *const c_char,
|
||||
) -> c_int;
|
||||
pub fn luaL_loadbuffer(L: *mut lua_State, buff: *const c_char, sz: usize, name: *const c_char) -> c_int;
|
||||
pub fn luaL_loadstring(L: *mut lua_State, s: *const c_char) -> c_int;
|
||||
|
||||
pub fn luaL_newstate() -> *mut lua_State;
|
||||
@@ -109,8 +107,6 @@ pub unsafe fn luaL_optstring(L: *mut lua_State, n: c_int, d: *const c_char) -> *
|
||||
luaL_optlstring(L, n, d, ptr::null_mut())
|
||||
}
|
||||
|
||||
// Deprecated from 5.3: luaL_checkint, luaL_optint, luaL_checklong, luaL_optlong
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn luaL_typename(L: *mut lua_State, i: c_int) -> *const c_char {
|
||||
lua::lua_typename(L, lua::lua_type(L, i))
|
||||
@@ -140,8 +136,62 @@ pub unsafe fn luaL_getmetatable(L: *mut lua_State, n: *const c_char) {
|
||||
lua::lua_getfield_(L, lua::LUA_REGISTRYINDEX, n);
|
||||
}
|
||||
|
||||
// TODO: luaL_opt
|
||||
#[inline(always)]
|
||||
pub unsafe fn luaL_opt<T>(
|
||||
L: *mut lua_State,
|
||||
f: unsafe extern "C-unwind" fn(*mut lua_State, c_int) -> T,
|
||||
n: c_int,
|
||||
d: T,
|
||||
) -> T {
|
||||
if lua::lua_isnoneornil(L, n) != 0 {
|
||||
d
|
||||
} else {
|
||||
f(L, n)
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// TODO: Generic Buffer Manipulation
|
||||
// Generic Buffer Manipulation
|
||||
//
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
const BUFSIZ: usize = 1024; // WASI libc's BUFSIZ is 1024
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const BUFSIZ: usize = libc::BUFSIZ as usize;
|
||||
|
||||
// The buffer size used by the lauxlib buffer system.
|
||||
// The "16384" workaround is taken from the LuaJIT source code.
|
||||
pub const LUAL_BUFFERSIZE: usize = if BUFSIZ > 16384 { 8192 } else { BUFSIZ };
|
||||
|
||||
#[repr(C)]
|
||||
pub struct luaL_Buffer {
|
||||
pub p: *mut c_char, // current position in buffer
|
||||
pub lvl: c_int, // number of strings in the stack
|
||||
pub L: *mut lua_State,
|
||||
pub buffer: [c_char; LUAL_BUFFERSIZE],
|
||||
}
|
||||
|
||||
#[cfg_attr(all(windows, raw_dylib), link(name = "lua51", kind = "raw-dylib"))]
|
||||
unsafe extern "C-unwind" {
|
||||
pub fn luaL_buffinit(L: *mut lua_State, B: *mut luaL_Buffer);
|
||||
pub fn luaL_prepbuffer(B: *mut luaL_Buffer) -> *mut c_char;
|
||||
pub fn luaL_addlstring(B: *mut luaL_Buffer, s: *const c_char, l: usize);
|
||||
pub fn luaL_addstring(B: *mut luaL_Buffer, s: *const c_char);
|
||||
pub fn luaL_addvalue(B: *mut luaL_Buffer);
|
||||
pub fn luaL_pushresult(B: *mut luaL_Buffer);
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn luaL_addchar(B: *mut luaL_Buffer, c: c_char) {
|
||||
let buffer_end = (*B).buffer.as_mut_ptr().add(LUAL_BUFFERSIZE);
|
||||
if (*B).p >= buffer_end {
|
||||
luaL_prepbuffer(B);
|
||||
}
|
||||
*(*B).p = c;
|
||||
(*B).p = (*B).p.add(1);
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn luaL_addsize(B: *mut luaL_Buffer, n: usize) {
|
||||
(*B).p = (*B).p.add(n);
|
||||
}
|
||||
|
||||
+14
-17
@@ -1,5 +1,6 @@
|
||||
//! Contains definitions from `lua.h`.
|
||||
|
||||
use std::ffi::CStr;
|
||||
use std::marker::{PhantomData, PhantomPinned};
|
||||
use std::os::raw::{c_char, c_double, c_int, c_void};
|
||||
use std::ptr;
|
||||
@@ -83,13 +84,13 @@ pub type lua_Reader =
|
||||
pub type lua_Writer =
|
||||
unsafe extern "C-unwind" fn(L: *mut lua_State, p: *const c_void, sz: usize, ud: *mut c_void) -> c_int;
|
||||
|
||||
/// Type for memory-allocation functions
|
||||
/// Type for memory-allocation functions (no unwinding)
|
||||
#[rustfmt::skip]
|
||||
pub type lua_Alloc =
|
||||
unsafe extern "C-unwind" fn(ud: *mut c_void, ptr: *mut c_void, osize: usize, nsize: usize) -> *mut c_void;
|
||||
unsafe extern "C" fn(ud: *mut c_void, ptr: *mut c_void, osize: usize, nsize: usize) -> *mut c_void;
|
||||
|
||||
#[cfg_attr(all(windows, raw_dylib), link(name = "lua51", kind = "raw-dylib"))]
|
||||
extern "C-unwind" {
|
||||
unsafe extern "C-unwind" {
|
||||
//
|
||||
// State manipulation
|
||||
//
|
||||
@@ -219,7 +220,7 @@ pub const LUA_GCSETPAUSE: c_int = 6;
|
||||
pub const LUA_GCSETSTEPMUL: c_int = 7;
|
||||
|
||||
#[cfg_attr(all(windows, raw_dylib), link(name = "lua51", kind = "raw-dylib"))]
|
||||
extern "C-unwind" {
|
||||
unsafe extern "C-unwind" {
|
||||
pub fn lua_gc(L: *mut lua_State, what: c_int, data: c_int) -> c_int;
|
||||
}
|
||||
|
||||
@@ -227,7 +228,7 @@ extern "C-unwind" {
|
||||
// Miscellaneous functions
|
||||
//
|
||||
#[cfg_attr(all(windows, raw_dylib), link(name = "lua51", kind = "raw-dylib"))]
|
||||
extern "C-unwind" {
|
||||
unsafe extern "C-unwind" {
|
||||
#[link_name = "lua_error"]
|
||||
fn lua_error_(L: *mut lua_State) -> c_int;
|
||||
pub fn lua_next(L: *mut lua_State, idx: c_int) -> c_int;
|
||||
@@ -269,7 +270,10 @@ pub unsafe fn lua_pushcfunction(L: *mut lua_State, f: lua_CFunction) {
|
||||
lua_pushcclosure(L, f, 0)
|
||||
}
|
||||
|
||||
// TODO: lua_strlen
|
||||
#[inline(always)]
|
||||
pub unsafe fn lua_strlen(L: *mut lua_State, i: c_int) -> usize {
|
||||
lua_objlen(L, i)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn lua_isfunction(L: *mut lua_State, n: c_int) -> c_int {
|
||||
@@ -312,10 +316,8 @@ pub unsafe fn lua_isnoneornil(L: *mut lua_State, n: c_int) -> c_int {
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn lua_pushliteral(L: *mut lua_State, s: &'static str) {
|
||||
use std::ffi::CString;
|
||||
let c_str = CString::new(s).unwrap();
|
||||
lua_pushlstring_(L, c_str.as_ptr(), c_str.as_bytes().len())
|
||||
pub unsafe fn lua_pushliteral(L: *mut lua_State, s: &'static CStr) {
|
||||
lua_pushstring_(L, s.as_ptr());
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
@@ -371,7 +373,7 @@ pub const LUA_MASKCOUNT: c_int = 1 << (LUA_HOOKCOUNT as usize);
|
||||
pub type lua_Hook = unsafe extern "C-unwind" fn(L: *mut lua_State, ar: *mut lua_Debug);
|
||||
|
||||
#[cfg_attr(all(windows, raw_dylib), link(name = "lua51", kind = "raw-dylib"))]
|
||||
extern "C-unwind" {
|
||||
unsafe extern "C-unwind" {
|
||||
pub fn lua_getstack(L: *mut lua_State, level: c_int, ar: *mut lua_Debug) -> c_int;
|
||||
pub fn lua_getinfo(L: *mut lua_State, what: *const c_char, ar: *mut lua_Debug) -> c_int;
|
||||
pub fn lua_getlocal(L: *mut lua_State, ar: *const lua_Debug, n: c_int) -> *const c_char;
|
||||
@@ -379,12 +381,7 @@ extern "C-unwind" {
|
||||
pub fn lua_getupvalue(L: *mut lua_State, funcindex: c_int, n: c_int) -> *const c_char;
|
||||
pub fn lua_setupvalue(L: *mut lua_State, funcindex: c_int, n: c_int) -> *const c_char;
|
||||
|
||||
pub fn lua_sethook(
|
||||
L: *mut lua_State,
|
||||
func: Option<lua_Hook>,
|
||||
mask: c_int,
|
||||
count: c_int,
|
||||
) -> c_int;
|
||||
pub fn lua_sethook(L: *mut lua_State, func: Option<lua_Hook>, mask: c_int, count: c_int) -> c_int;
|
||||
pub fn lua_gethook(L: *mut lua_State) -> Option<lua_Hook>;
|
||||
pub fn lua_gethookmask(L: *mut lua_State) -> c_int;
|
||||
pub fn lua_gethookcount(L: *mut lua_State) -> c_int;
|
||||
|
||||
@@ -1,27 +1,27 @@
|
||||
//! Contains definitions from `lualib.h`.
|
||||
|
||||
use std::os::raw::c_int;
|
||||
use std::os::raw::{c_char, c_int};
|
||||
|
||||
use super::lua::lua_State;
|
||||
|
||||
pub const LUA_COLIBNAME: &str = "coroutine";
|
||||
pub const LUA_TABLIBNAME: &str = "table";
|
||||
pub const LUA_IOLIBNAME: &str = "io";
|
||||
pub const LUA_OSLIBNAME: &str = "os";
|
||||
pub const LUA_STRLIBNAME: &str = "string";
|
||||
pub const LUA_MATHLIBNAME: &str = "math";
|
||||
pub const LUA_DBLIBNAME: &str = "debug";
|
||||
pub const LUA_LOADLIBNAME: &str = "package";
|
||||
pub const LUA_COLIBNAME: *const c_char = cstr!("coroutine");
|
||||
pub const LUA_TABLIBNAME: *const c_char = cstr!("table");
|
||||
pub const LUA_IOLIBNAME: *const c_char = cstr!("io");
|
||||
pub const LUA_OSLIBNAME: *const c_char = cstr!("os");
|
||||
pub const LUA_STRLIBNAME: *const c_char = cstr!("string");
|
||||
pub const LUA_MATHLIBNAME: *const c_char = cstr!("math");
|
||||
pub const LUA_DBLIBNAME: *const c_char = cstr!("debug");
|
||||
pub const LUA_LOADLIBNAME: *const c_char = cstr!("package");
|
||||
|
||||
#[cfg(feature = "luajit")]
|
||||
pub const LUA_BITLIBNAME: &str = "bit";
|
||||
pub const LUA_BITLIBNAME: *const c_char = cstr!("bit");
|
||||
#[cfg(feature = "luajit")]
|
||||
pub const LUA_JITLIBNAME: &str = "jit";
|
||||
pub const LUA_JITLIBNAME: *const c_char = cstr!("jit");
|
||||
#[cfg(feature = "luajit")]
|
||||
pub const LUA_FFILIBNAME: &str = "ffi";
|
||||
pub const LUA_FFILIBNAME: *const c_char = cstr!("ffi");
|
||||
|
||||
#[cfg_attr(all(windows, raw_dylib), link(name = "lua51", kind = "raw-dylib"))]
|
||||
extern "C-unwind" {
|
||||
unsafe extern "C-unwind" {
|
||||
pub fn luaopen_base(L: *mut lua_State) -> c_int;
|
||||
pub fn luaopen_table(L: *mut lua_State) -> c_int;
|
||||
pub fn luaopen_io(L: *mut lua_State) -> c_int;
|
||||
|
||||
@@ -51,7 +51,8 @@ pub unsafe fn lua_isinteger(L: *mut lua_State, idx: c_int) -> c_int {
|
||||
if lua_type(L, idx) == LUA_TNUMBER {
|
||||
let n = lua_tonumber(L, idx);
|
||||
let i = lua_tointeger(L, idx);
|
||||
if (n - i as lua_Number).abs() < lua_Number::EPSILON {
|
||||
// Lua 5.3+ returns "false" for `-0.0`
|
||||
if n.to_bits() == (i as lua_Number).to_bits() {
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
@@ -124,7 +125,7 @@ pub unsafe fn lua_rawget(L: *mut lua_State, idx: c_int) -> c_int {
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn lua_rawgeti(L: *mut lua_State, idx: c_int, n: lua_Integer) -> c_int {
|
||||
let n = n.try_into().expect("cannot convert index to lua_Integer");
|
||||
let n = n.try_into().expect("cannot convert index to c_int");
|
||||
lua_rawgeti_(L, idx, n);
|
||||
lua_type(L, -1)
|
||||
}
|
||||
@@ -152,27 +153,17 @@ pub unsafe fn lua_seti(L: *mut lua_State, mut idx: c_int, n: lua_Integer) {
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn lua_rawseti(L: *mut lua_State, idx: c_int, n: lua_Integer) {
|
||||
let n = n.try_into().expect("cannot convert index from lua_Integer");
|
||||
let n = n.try_into().expect("cannot convert index to c_int");
|
||||
lua_rawseti_(L, idx, n)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn lua_dump(
|
||||
L: *mut lua_State,
|
||||
writer: lua_Writer,
|
||||
data: *mut c_void,
|
||||
_strip: c_int,
|
||||
) -> c_int {
|
||||
pub unsafe fn lua_dump(L: *mut lua_State, writer: lua_Writer, data: *mut c_void, _strip: c_int) -> c_int {
|
||||
lua_dump_(L, writer, data)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn lua_resume(
|
||||
L: *mut lua_State,
|
||||
from: *mut lua_State,
|
||||
narg: c_int,
|
||||
nres: *mut c_int,
|
||||
) -> c_int {
|
||||
pub unsafe fn lua_resume(L: *mut lua_State, from: *mut lua_State, narg: c_int, nres: *mut c_int) -> c_int {
|
||||
let ret = lua_resume_(L, from, narg);
|
||||
if (ret == LUA_OK || ret == LUA_YIELD) && !(nres.is_null()) {
|
||||
*nres = lua_gettop(L);
|
||||
@@ -209,16 +200,16 @@ pub unsafe fn luaL_tolstring(L: *mut lua_State, mut idx: c_int, len: *mut usize)
|
||||
if luaL_callmeta(L, idx, cstr!("__tostring")) == 0 {
|
||||
match lua_type(L, idx) {
|
||||
LUA_TNIL => {
|
||||
lua_pushliteral(L, "nil");
|
||||
lua_pushliteral(L, c"nil");
|
||||
}
|
||||
LUA_TSTRING | LUA_TNUMBER => {
|
||||
lua_pushvalue(L, idx);
|
||||
}
|
||||
LUA_TBOOLEAN => {
|
||||
if lua_toboolean(L, idx) == 0 {
|
||||
lua_pushliteral(L, "false");
|
||||
lua_pushliteral(L, c"false");
|
||||
} else {
|
||||
lua_pushliteral(L, "true");
|
||||
lua_pushliteral(L, c"true");
|
||||
}
|
||||
}
|
||||
t => {
|
||||
@@ -240,14 +231,9 @@ pub unsafe fn luaL_tolstring(L: *mut lua_State, mut idx: c_int, len: *mut usize)
|
||||
lua_tolstring(L, -1, len)
|
||||
}
|
||||
|
||||
pub unsafe fn luaL_requiref(
|
||||
L: *mut lua_State,
|
||||
modname: *const c_char,
|
||||
openf: lua_CFunction,
|
||||
glb: c_int,
|
||||
) {
|
||||
pub unsafe fn luaL_requiref(L: *mut lua_State, modname: *const c_char, openf: lua_CFunction, glb: c_int) {
|
||||
luaL_checkstack(L, 3, cstr!("not enough stack slots available"));
|
||||
luaL_getsubtable(L, LUA_REGISTRYINDEX, cstr!("_LOADED"));
|
||||
luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE);
|
||||
if lua_getfield(L, -1, modname) == LUA_TNIL {
|
||||
lua_pop(L, 1);
|
||||
lua_pushcfunction(L, openf);
|
||||
@@ -262,3 +248,22 @@ pub unsafe fn luaL_requiref(
|
||||
}
|
||||
lua_replace(L, -2);
|
||||
}
|
||||
|
||||
pub unsafe fn luaL_loadbufferenv(
|
||||
L: *mut lua_State,
|
||||
data: *const c_char,
|
||||
size: usize,
|
||||
name: *const c_char,
|
||||
mode: *const c_char,
|
||||
mut env: c_int,
|
||||
) -> c_int {
|
||||
if env != 0 {
|
||||
env = lua_absindex(L, env);
|
||||
}
|
||||
let status = luaL_loadbufferx(L, data, size, name, mode);
|
||||
if status == LUA_OK && env != 0 {
|
||||
lua_pushvalue(L, env);
|
||||
lua_setupvalue(L, -2, 1);
|
||||
}
|
||||
status
|
||||
}
|
||||
|
||||
@@ -8,6 +8,12 @@ use super::lua::{self, lua_CFunction, lua_Integer, lua_Number, lua_State, lua_Un
|
||||
// Extra error code for 'luaL_load'
|
||||
pub const LUA_ERRFILE: c_int = lua::LUA_ERRERR + 1;
|
||||
|
||||
// Key, in the registry, for table of loaded modules
|
||||
pub const LUA_LOADED_TABLE: *const c_char = cstr!("_LOADED");
|
||||
|
||||
// Key, in the registry, for table of preloaded loaders
|
||||
pub const LUA_PRELOAD_TABLE: *const c_char = cstr!("_PRELOAD");
|
||||
|
||||
#[repr(C)]
|
||||
pub struct luaL_Reg {
|
||||
pub name: *const c_char,
|
||||
@@ -15,7 +21,7 @@ pub struct luaL_Reg {
|
||||
}
|
||||
|
||||
#[cfg_attr(all(windows, raw_dylib), link(name = "lua52", kind = "raw-dylib"))]
|
||||
extern "C-unwind" {
|
||||
unsafe extern "C-unwind" {
|
||||
pub fn luaL_checkversion_(L: *mut lua_State, ver: lua_Number);
|
||||
|
||||
#[link_name = "luaL_getmetafield"]
|
||||
@@ -25,12 +31,8 @@ extern "C-unwind" {
|
||||
pub fn luaL_tolstring_(L: *mut lua_State, idx: c_int, len: *mut usize) -> *const c_char;
|
||||
pub fn luaL_argerror(L: *mut lua_State, arg: c_int, extramsg: *const c_char) -> c_int;
|
||||
pub fn luaL_checklstring(L: *mut lua_State, arg: c_int, l: *mut usize) -> *const c_char;
|
||||
pub fn luaL_optlstring(
|
||||
L: *mut lua_State,
|
||||
arg: c_int,
|
||||
def: *const c_char,
|
||||
l: *mut usize,
|
||||
) -> *const c_char;
|
||||
pub fn luaL_optlstring(L: *mut lua_State, arg: c_int, def: *const c_char, l: *mut usize)
|
||||
-> *const c_char;
|
||||
pub fn luaL_checknumber(L: *mut lua_State, arg: c_int) -> lua_Number;
|
||||
pub fn luaL_optnumber(L: *mut lua_State, arg: c_int, def: lua_Number) -> lua_Number;
|
||||
pub fn luaL_checkinteger(L: *mut lua_State, arg: c_int) -> lua_Integer;
|
||||
@@ -67,12 +69,11 @@ pub const LUA_NOREF: c_int = -2;
|
||||
pub const LUA_REFNIL: c_int = -1;
|
||||
|
||||
#[cfg_attr(all(windows, raw_dylib), link(name = "lua52", kind = "raw-dylib"))]
|
||||
extern "C-unwind" {
|
||||
unsafe extern "C-unwind" {
|
||||
pub fn luaL_ref(L: *mut lua_State, t: c_int) -> c_int;
|
||||
pub fn luaL_unref(L: *mut lua_State, t: c_int, r#ref: c_int);
|
||||
|
||||
pub fn luaL_loadfilex(L: *mut lua_State, filename: *const c_char, mode: *const c_char)
|
||||
-> c_int;
|
||||
pub fn luaL_loadfilex(L: *mut lua_State, filename: *const c_char, mode: *const c_char) -> c_int;
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
@@ -81,7 +82,7 @@ pub unsafe fn luaL_loadfile(L: *mut lua_State, f: *const c_char) -> c_int {
|
||||
}
|
||||
|
||||
#[cfg_attr(all(windows, raw_dylib), link(name = "lua52", kind = "raw-dylib"))]
|
||||
extern "C-unwind" {
|
||||
unsafe extern "C-unwind" {
|
||||
pub fn luaL_loadbufferx(
|
||||
L: *mut lua_State,
|
||||
buff: *const c_char,
|
||||
@@ -109,12 +110,7 @@ extern "C-unwind" {
|
||||
pub fn luaL_traceback(L: *mut lua_State, L1: *mut lua_State, msg: *const c_char, level: c_int);
|
||||
|
||||
#[link_name = "luaL_requiref"]
|
||||
pub fn luaL_requiref_(
|
||||
L: *mut lua_State,
|
||||
modname: *const c_char,
|
||||
openf: lua_CFunction,
|
||||
glb: c_int,
|
||||
);
|
||||
pub fn luaL_requiref_(L: *mut lua_State, modname: *const c_char, openf: lua_CFunction, glb: c_int);
|
||||
}
|
||||
|
||||
//
|
||||
@@ -170,18 +166,76 @@ pub unsafe fn luaL_getmetatable(L: *mut lua_State, n: *const c_char) {
|
||||
lua::lua_getfield_(L, lua::LUA_REGISTRYINDEX, n);
|
||||
}
|
||||
|
||||
// luaL_opt would be implemented here but it is undocumented, so it's omitted
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn luaL_loadbuffer(
|
||||
L: *mut lua_State,
|
||||
s: *const c_char,
|
||||
sz: usize,
|
||||
n: *const c_char,
|
||||
) -> c_int {
|
||||
pub unsafe fn luaL_loadbuffer(L: *mut lua_State, s: *const c_char, sz: usize, n: *const c_char) -> c_int {
|
||||
luaL_loadbufferx(L, s, sz, n, ptr::null())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn luaL_opt<T>(
|
||||
L: *mut lua_State,
|
||||
f: unsafe extern "C-unwind" fn(*mut lua_State, c_int) -> T,
|
||||
n: c_int,
|
||||
d: T,
|
||||
) -> T {
|
||||
if lua::lua_isnoneornil(L, n) != 0 {
|
||||
d
|
||||
} else {
|
||||
f(L, n)
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// TODO: Generic Buffer Manipulation
|
||||
// Generic Buffer Manipulation
|
||||
//
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
const BUFSIZ: usize = 1024; // WASI libc's BUFSIZ is 1024
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const BUFSIZ: usize = libc::BUFSIZ as usize;
|
||||
|
||||
// The buffer size used by the lauxlib buffer system.
|
||||
// The "16384" workaround is taken from the LuaJIT source code.
|
||||
pub const LUAL_BUFFERSIZE: usize = if BUFSIZ > 16384 { 8192 } else { BUFSIZ };
|
||||
|
||||
#[repr(C)]
|
||||
pub struct luaL_Buffer {
|
||||
pub b: *mut c_char, // buffer address
|
||||
pub size: usize, // buffer size
|
||||
pub n: usize, // number of characters in buffer
|
||||
pub L: *mut lua_State,
|
||||
pub initb: [c_char; LUAL_BUFFERSIZE], // initial buffer space
|
||||
}
|
||||
|
||||
#[cfg_attr(all(windows, raw_dylib), link(name = "lua52", kind = "raw-dylib"))]
|
||||
unsafe extern "C-unwind" {
|
||||
pub fn luaL_buffinit(L: *mut lua_State, B: *mut luaL_Buffer);
|
||||
pub fn luaL_prepbuffsize(B: *mut luaL_Buffer, sz: usize) -> *mut c_char;
|
||||
pub fn luaL_addlstring(B: *mut luaL_Buffer, s: *const c_char, l: usize);
|
||||
pub fn luaL_addstring(B: *mut luaL_Buffer, s: *const c_char);
|
||||
pub fn luaL_addvalue(B: *mut luaL_Buffer);
|
||||
pub fn luaL_pushresult(B: *mut luaL_Buffer);
|
||||
pub fn luaL_pushresultsize(B: *mut luaL_Buffer, sz: usize);
|
||||
pub fn luaL_buffinitsize(L: *mut lua_State, B: *mut luaL_Buffer, sz: usize) -> *mut c_char;
|
||||
}
|
||||
|
||||
// Macro implementations as inline functions
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn luaL_prepbuffer(B: *mut luaL_Buffer) -> *mut c_char {
|
||||
luaL_prepbuffsize(B, LUAL_BUFFERSIZE)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn luaL_addchar(B: *mut luaL_Buffer, c: c_char) {
|
||||
if (*B).n >= (*B).size {
|
||||
luaL_prepbuffsize(B, 1);
|
||||
}
|
||||
*(*B).b.add((*B).n) = c;
|
||||
(*B).n += 1;
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn luaL_addsize(B: *mut luaL_Buffer, n: usize) {
|
||||
(*B).n += n;
|
||||
}
|
||||
|
||||
+15
-32
@@ -1,5 +1,6 @@
|
||||
//! Contains definitions from `lua.h`.
|
||||
|
||||
use std::ffi::CStr;
|
||||
use std::marker::{PhantomData, PhantomPinned};
|
||||
use std::os::raw::{c_char, c_double, c_int, c_uchar, c_uint, c_void};
|
||||
use std::ptr;
|
||||
@@ -88,13 +89,13 @@ pub type lua_Reader =
|
||||
pub type lua_Writer =
|
||||
unsafe extern "C-unwind" fn(L: *mut lua_State, p: *const c_void, sz: usize, ud: *mut c_void) -> c_int;
|
||||
|
||||
/// Type for memory-allocation functions
|
||||
/// Type for memory-allocation functions (no unwinding)
|
||||
#[rustfmt::skip]
|
||||
pub type lua_Alloc =
|
||||
unsafe extern "C-unwind" fn(ud: *mut c_void, ptr: *mut c_void, osize: usize, nsize: usize) -> *mut c_void;
|
||||
unsafe extern "C" fn(ud: *mut c_void, ptr: *mut c_void, osize: usize, nsize: usize) -> *mut c_void;
|
||||
|
||||
#[cfg_attr(all(windows, raw_dylib), link(name = "lua52", kind = "raw-dylib"))]
|
||||
extern "C-unwind" {
|
||||
unsafe extern "C-unwind" {
|
||||
//
|
||||
// State manipulation
|
||||
//
|
||||
@@ -160,14 +161,14 @@ pub const LUA_OPLT: c_int = 1;
|
||||
pub const LUA_OPLE: c_int = 2;
|
||||
|
||||
#[cfg_attr(all(windows, raw_dylib), link(name = "lua52", kind = "raw-dylib"))]
|
||||
extern "C-unwind" {
|
||||
unsafe extern "C-unwind" {
|
||||
pub fn lua_arith(L: *mut lua_State, op: c_int);
|
||||
pub fn lua_rawequal(L: *mut lua_State, idx1: c_int, idx2: c_int) -> c_int;
|
||||
pub fn lua_compare(L: *mut lua_State, idx1: c_int, idx2: c_int, op: c_int) -> c_int;
|
||||
}
|
||||
|
||||
#[cfg_attr(all(windows, raw_dylib), link(name = "lua52", kind = "raw-dylib"))]
|
||||
extern "C-unwind" {
|
||||
unsafe extern "C-unwind" {
|
||||
//
|
||||
// Push functions (C -> stack)
|
||||
//
|
||||
@@ -222,13 +223,7 @@ extern "C-unwind" {
|
||||
//
|
||||
// 'load' and 'call' functions (load and run Lua code)
|
||||
//
|
||||
pub fn lua_callk(
|
||||
L: *mut lua_State,
|
||||
nargs: c_int,
|
||||
nresults: c_int,
|
||||
ctx: c_int,
|
||||
k: Option<lua_CFunction>,
|
||||
);
|
||||
pub fn lua_callk(L: *mut lua_State, nargs: c_int, nresults: c_int, ctx: c_int, k: Option<lua_CFunction>);
|
||||
pub fn lua_pcallk(
|
||||
L: *mut lua_State,
|
||||
nargs: c_int,
|
||||
@@ -262,16 +257,11 @@ pub unsafe fn lua_pcall(L: *mut lua_State, n: c_int, r: c_int, f: c_int) -> c_in
|
||||
}
|
||||
|
||||
#[cfg_attr(all(windows, raw_dylib), link(name = "lua52", kind = "raw-dylib"))]
|
||||
extern "C-unwind" {
|
||||
unsafe extern "C-unwind" {
|
||||
//
|
||||
// Coroutine functions
|
||||
//
|
||||
pub fn lua_yieldk(
|
||||
L: *mut lua_State,
|
||||
nresults: c_int,
|
||||
ctx: c_int,
|
||||
k: Option<lua_CFunction>,
|
||||
) -> c_int;
|
||||
pub fn lua_yieldk(L: *mut lua_State, nresults: c_int, ctx: c_int, k: Option<lua_CFunction>) -> c_int;
|
||||
#[link_name = "lua_resume"]
|
||||
pub fn lua_resume_(L: *mut lua_State, from: *mut lua_State, narg: c_int) -> c_int;
|
||||
pub fn lua_status(L: *mut lua_State) -> c_int;
|
||||
@@ -299,12 +289,12 @@ pub const LUA_GCGEN: c_int = 10;
|
||||
pub const LUA_GCINC: c_int = 11;
|
||||
|
||||
#[cfg_attr(all(windows, raw_dylib), link(name = "lua52", kind = "raw-dylib"))]
|
||||
extern "C-unwind" {
|
||||
unsafe extern "C-unwind" {
|
||||
pub fn lua_gc(L: *mut lua_State, what: c_int, data: c_int) -> c_int;
|
||||
}
|
||||
|
||||
#[cfg_attr(all(windows, raw_dylib), link(name = "lua52", kind = "raw-dylib"))]
|
||||
extern "C-unwind" {
|
||||
unsafe extern "C-unwind" {
|
||||
//
|
||||
// Miscellaneous functions
|
||||
//
|
||||
@@ -406,10 +396,8 @@ pub unsafe fn lua_isnoneornil(L: *mut lua_State, n: c_int) -> c_int {
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn lua_pushliteral(L: *mut lua_State, s: &'static str) -> *const c_char {
|
||||
use std::ffi::CString;
|
||||
let c_str = CString::new(s).unwrap();
|
||||
lua_pushlstring_(L, c_str.as_ptr(), c_str.as_bytes().len())
|
||||
pub unsafe fn lua_pushliteral(L: *mut lua_State, s: &'static CStr) {
|
||||
lua_pushstring(L, s.as_ptr());
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
@@ -460,7 +448,7 @@ pub const LUA_MASKCOUNT: c_int = 1 << (LUA_HOOKCOUNT as usize);
|
||||
pub type lua_Hook = unsafe extern "C-unwind" fn(L: *mut lua_State, ar: *mut lua_Debug);
|
||||
|
||||
#[cfg_attr(all(windows, raw_dylib), link(name = "lua52", kind = "raw-dylib"))]
|
||||
extern "C-unwind" {
|
||||
unsafe extern "C-unwind" {
|
||||
pub fn lua_getstack(L: *mut lua_State, level: c_int, ar: *mut lua_Debug) -> c_int;
|
||||
pub fn lua_getinfo(L: *mut lua_State, what: *const c_char, ar: *mut lua_Debug) -> c_int;
|
||||
pub fn lua_getlocal(L: *mut lua_State, ar: *const lua_Debug, n: c_int) -> *const c_char;
|
||||
@@ -471,12 +459,7 @@ extern "C-unwind" {
|
||||
pub fn lua_upvalueid(L: *mut lua_State, fidx: c_int, n: c_int) -> *mut c_void;
|
||||
pub fn lua_upvaluejoin(L: *mut lua_State, fidx1: c_int, n1: c_int, fidx2: c_int, n2: c_int);
|
||||
|
||||
pub fn lua_sethook(
|
||||
L: *mut lua_State,
|
||||
func: Option<lua_Hook>,
|
||||
mask: c_int,
|
||||
count: c_int,
|
||||
) -> c_int;
|
||||
pub fn lua_sethook(L: *mut lua_State, func: Option<lua_Hook>, mask: c_int, count: c_int) -> c_int;
|
||||
pub fn lua_gethook(L: *mut lua_State) -> Option<lua_Hook>;
|
||||
pub fn lua_gethookmask(L: *mut lua_State) -> c_int;
|
||||
pub fn lua_gethookcount(L: *mut lua_State) -> c_int;
|
||||
|
||||
@@ -1,21 +1,21 @@
|
||||
//! Contains definitions from `lualib.h`.
|
||||
|
||||
use std::os::raw::c_int;
|
||||
use std::os::raw::{c_char, c_int};
|
||||
|
||||
use super::lua::lua_State;
|
||||
|
||||
pub const LUA_COLIBNAME: &str = "coroutine";
|
||||
pub const LUA_TABLIBNAME: &str = "table";
|
||||
pub const LUA_IOLIBNAME: &str = "io";
|
||||
pub const LUA_OSLIBNAME: &str = "os";
|
||||
pub const LUA_STRLIBNAME: &str = "string";
|
||||
pub const LUA_BITLIBNAME: &str = "bit32";
|
||||
pub const LUA_MATHLIBNAME: &str = "math";
|
||||
pub const LUA_DBLIBNAME: &str = "debug";
|
||||
pub const LUA_LOADLIBNAME: &str = "package";
|
||||
pub const LUA_COLIBNAME: *const c_char = cstr!("coroutine");
|
||||
pub const LUA_TABLIBNAME: *const c_char = cstr!("table");
|
||||
pub const LUA_IOLIBNAME: *const c_char = cstr!("io");
|
||||
pub const LUA_OSLIBNAME: *const c_char = cstr!("os");
|
||||
pub const LUA_STRLIBNAME: *const c_char = cstr!("string");
|
||||
pub const LUA_BITLIBNAME: *const c_char = cstr!("bit32");
|
||||
pub const LUA_MATHLIBNAME: *const c_char = cstr!("math");
|
||||
pub const LUA_DBLIBNAME: *const c_char = cstr!("debug");
|
||||
pub const LUA_LOADLIBNAME: *const c_char = cstr!("package");
|
||||
|
||||
#[cfg_attr(all(windows, raw_dylib), link(name = "lua52", kind = "raw-dylib"))]
|
||||
extern "C-unwind" {
|
||||
unsafe extern "C-unwind" {
|
||||
pub fn luaopen_base(L: *mut lua_State) -> c_int;
|
||||
pub fn luaopen_coroutine(L: *mut lua_State) -> c_int;
|
||||
pub fn luaopen_table(L: *mut lua_State) -> c_int;
|
||||
|
||||
@@ -1,19 +1,34 @@
|
||||
//! MLua compatibility layer for Lua 5.3
|
||||
|
||||
use std::os::raw::c_int;
|
||||
use std::os::raw::{c_char, c_int};
|
||||
|
||||
use super::lauxlib::*;
|
||||
use super::lua::*;
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn lua_resume(
|
||||
L: *mut lua_State,
|
||||
from: *mut lua_State,
|
||||
narg: c_int,
|
||||
nres: *mut c_int,
|
||||
) -> c_int {
|
||||
pub unsafe fn lua_resume(L: *mut lua_State, from: *mut lua_State, narg: c_int, nres: *mut c_int) -> c_int {
|
||||
let ret = lua_resume_(L, from, narg);
|
||||
if (ret == LUA_OK || ret == LUA_YIELD) && !(nres.is_null()) {
|
||||
*nres = lua_gettop(L);
|
||||
}
|
||||
ret
|
||||
}
|
||||
|
||||
pub unsafe fn luaL_loadbufferenv(
|
||||
L: *mut lua_State,
|
||||
data: *const c_char,
|
||||
size: usize,
|
||||
name: *const c_char,
|
||||
mode: *const c_char,
|
||||
mut env: c_int,
|
||||
) -> c_int {
|
||||
if env != 0 {
|
||||
env = lua_absindex(L, env);
|
||||
}
|
||||
let status = luaL_loadbufferx(L, data, size, name, mode);
|
||||
if status == LUA_OK && env != 0 {
|
||||
lua_pushvalue(L, env);
|
||||
lua_setupvalue(L, -2, 1);
|
||||
}
|
||||
status
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Contains definitions from `lauxlib.h`.
|
||||
|
||||
use std::os::raw::{c_char, c_int, c_void};
|
||||
use std::ptr;
|
||||
use std::{mem, ptr};
|
||||
|
||||
use super::lua::{self, lua_CFunction, lua_Integer, lua_Number, lua_State};
|
||||
|
||||
@@ -9,10 +9,10 @@ use super::lua::{self, lua_CFunction, lua_Integer, lua_Number, lua_State};
|
||||
pub const LUA_ERRFILE: c_int = lua::LUA_ERRERR + 1;
|
||||
|
||||
// Key, in the registry, for table of loaded modules
|
||||
pub const LUA_LOADED_TABLE: &str = "_LOADED";
|
||||
pub const LUA_LOADED_TABLE: *const c_char = cstr!("_LOADED");
|
||||
|
||||
// Key, in the registry, for table of preloaded loaders
|
||||
pub const LUA_PRELOAD_TABLE: &str = "_PRELOAD";
|
||||
pub const LUA_PRELOAD_TABLE: *const c_char = cstr!("_PRELOAD");
|
||||
|
||||
#[repr(C)]
|
||||
pub struct luaL_Reg {
|
||||
@@ -21,7 +21,7 @@ pub struct luaL_Reg {
|
||||
}
|
||||
|
||||
#[cfg_attr(all(windows, raw_dylib), link(name = "lua53", kind = "raw-dylib"))]
|
||||
extern "C-unwind" {
|
||||
unsafe extern "C-unwind" {
|
||||
pub fn luaL_checkversion_(L: *mut lua_State, ver: lua_Number, sz: usize);
|
||||
|
||||
pub fn luaL_getmetafield(L: *mut lua_State, obj: c_int, e: *const c_char) -> c_int;
|
||||
@@ -30,12 +30,8 @@ extern "C-unwind" {
|
||||
pub fn luaL_tolstring_(L: *mut lua_State, idx: c_int, len: *mut usize) -> *const c_char;
|
||||
pub fn luaL_argerror(L: *mut lua_State, arg: c_int, extramsg: *const c_char) -> c_int;
|
||||
pub fn luaL_checklstring(L: *mut lua_State, arg: c_int, l: *mut usize) -> *const c_char;
|
||||
pub fn luaL_optlstring(
|
||||
L: *mut lua_State,
|
||||
arg: c_int,
|
||||
def: *const c_char,
|
||||
l: *mut usize,
|
||||
) -> *const c_char;
|
||||
pub fn luaL_optlstring(L: *mut lua_State, arg: c_int, def: *const c_char, l: *mut usize)
|
||||
-> *const c_char;
|
||||
pub fn luaL_checknumber(L: *mut lua_State, arg: c_int) -> lua_Number;
|
||||
pub fn luaL_optnumber(L: *mut lua_State, arg: c_int, def: lua_Number) -> lua_Number;
|
||||
pub fn luaL_checkinteger(L: *mut lua_State, arg: c_int) -> lua_Integer;
|
||||
@@ -69,12 +65,11 @@ pub const LUA_NOREF: c_int = -2;
|
||||
pub const LUA_REFNIL: c_int = -1;
|
||||
|
||||
#[cfg_attr(all(windows, raw_dylib), link(name = "lua53", kind = "raw-dylib"))]
|
||||
extern "C-unwind" {
|
||||
unsafe extern "C-unwind" {
|
||||
pub fn luaL_ref(L: *mut lua_State, t: c_int) -> c_int;
|
||||
pub fn luaL_unref(L: *mut lua_State, t: c_int, r#ref: c_int);
|
||||
|
||||
pub fn luaL_loadfilex(L: *mut lua_State, filename: *const c_char, mode: *const c_char)
|
||||
-> c_int;
|
||||
pub fn luaL_loadfilex(L: *mut lua_State, filename: *const c_char, mode: *const c_char) -> c_int;
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
@@ -83,7 +78,7 @@ pub unsafe fn luaL_loadfile(L: *mut lua_State, f: *const c_char) -> c_int {
|
||||
}
|
||||
|
||||
#[cfg_attr(all(windows, raw_dylib), link(name = "lua53", kind = "raw-dylib"))]
|
||||
extern "C-unwind" {
|
||||
unsafe extern "C-unwind" {
|
||||
pub fn luaL_loadbufferx(
|
||||
L: *mut lua_State,
|
||||
buff: *const c_char,
|
||||
@@ -110,12 +105,7 @@ extern "C-unwind" {
|
||||
|
||||
pub fn luaL_traceback(L: *mut lua_State, L1: *mut lua_State, msg: *const c_char, level: c_int);
|
||||
|
||||
pub fn luaL_requiref(
|
||||
L: *mut lua_State,
|
||||
modname: *const c_char,
|
||||
openf: lua_CFunction,
|
||||
glb: c_int,
|
||||
);
|
||||
pub fn luaL_requiref(L: *mut lua_State, modname: *const c_char, openf: lua_CFunction, glb: c_int);
|
||||
}
|
||||
|
||||
//
|
||||
@@ -176,18 +166,72 @@ pub unsafe fn luaL_tolstring(L: *mut lua_State, idx: c_int, len: *mut usize) ->
|
||||
luaL_tolstring_(L, lua::lua_absindex(L, idx), len)
|
||||
}
|
||||
|
||||
// luaL_opt would be implemented here but it is undocumented, so it's omitted
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn luaL_loadbuffer(
|
||||
L: *mut lua_State,
|
||||
s: *const c_char,
|
||||
sz: usize,
|
||||
n: *const c_char,
|
||||
) -> c_int {
|
||||
pub unsafe fn luaL_loadbuffer(L: *mut lua_State, s: *const c_char, sz: usize, n: *const c_char) -> c_int {
|
||||
luaL_loadbufferx(L, s, sz, n, ptr::null())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn luaL_opt<T>(
|
||||
L: *mut lua_State,
|
||||
f: unsafe extern "C-unwind" fn(*mut lua_State, c_int) -> T,
|
||||
n: c_int,
|
||||
d: T,
|
||||
) -> T {
|
||||
if lua::lua_isnoneornil(L, n) != 0 {
|
||||
d
|
||||
} else {
|
||||
f(L, n)
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// TODO: Generic Buffer Manipulation
|
||||
// Generic Buffer Manipulation
|
||||
//
|
||||
|
||||
// The buffer size used by the lauxlib buffer system.
|
||||
// In Lua 5.3: LUAL_BUFFERSIZE = (int)(0x80 * sizeof(void*) * sizeof(lua_Integer))
|
||||
#[rustfmt::skip]
|
||||
pub const LUAL_BUFFERSIZE: usize = 0x80 * mem::size_of::<*const ()>() * mem::size_of::<lua_Integer>();
|
||||
|
||||
#[repr(C)]
|
||||
pub struct luaL_Buffer {
|
||||
pub b: *mut c_char, // buffer address
|
||||
pub size: usize, // buffer size
|
||||
pub n: usize, // number of characters in buffer
|
||||
pub L: *mut lua_State,
|
||||
pub initb: [c_char; LUAL_BUFFERSIZE], // initial buffer space
|
||||
}
|
||||
|
||||
#[cfg_attr(all(windows, raw_dylib), link(name = "lua53", kind = "raw-dylib"))]
|
||||
unsafe extern "C-unwind" {
|
||||
pub fn luaL_buffinit(L: *mut lua_State, B: *mut luaL_Buffer);
|
||||
pub fn luaL_prepbuffsize(B: *mut luaL_Buffer, sz: usize) -> *mut c_char;
|
||||
pub fn luaL_addlstring(B: *mut luaL_Buffer, s: *const c_char, l: usize);
|
||||
pub fn luaL_addstring(B: *mut luaL_Buffer, s: *const c_char);
|
||||
pub fn luaL_addvalue(B: *mut luaL_Buffer);
|
||||
pub fn luaL_pushresult(B: *mut luaL_Buffer);
|
||||
pub fn luaL_pushresultsize(B: *mut luaL_Buffer, sz: usize);
|
||||
pub fn luaL_buffinitsize(L: *mut lua_State, B: *mut luaL_Buffer, sz: usize) -> *mut c_char;
|
||||
}
|
||||
|
||||
// Macro implementations as inline functions
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn luaL_prepbuffer(B: *mut luaL_Buffer) -> *mut c_char {
|
||||
luaL_prepbuffsize(B, LUAL_BUFFERSIZE)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn luaL_addchar(B: *mut luaL_Buffer, c: c_char) {
|
||||
if (*B).n >= (*B).size {
|
||||
luaL_prepbuffsize(B, 1);
|
||||
}
|
||||
*(*B).b.add((*B).n) = c;
|
||||
(*B).n += 1;
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn luaL_addsize(B: *mut luaL_Buffer, n: usize) {
|
||||
(*B).n += n;
|
||||
}
|
||||
|
||||
+14
-21
@@ -1,9 +1,9 @@
|
||||
//! Contains definitions from `lua.h`.
|
||||
|
||||
use std::ffi::CStr;
|
||||
use std::marker::{PhantomData, PhantomPinned};
|
||||
use std::mem;
|
||||
use std::os::raw::{c_char, c_double, c_int, c_uchar, c_void};
|
||||
use std::ptr;
|
||||
use std::{mem, ptr};
|
||||
|
||||
// Mark for precompiled code (`<esc>Lua`)
|
||||
pub const LUA_SIGNATURE: &[u8] = b"\x1bLua";
|
||||
@@ -96,13 +96,13 @@ pub type lua_Reader =
|
||||
pub type lua_Writer =
|
||||
unsafe extern "C-unwind" fn(L: *mut lua_State, p: *const c_void, sz: usize, ud: *mut c_void) -> c_int;
|
||||
|
||||
/// Type for memory-allocation functions
|
||||
/// Type for memory-allocation functions (no unwinding)
|
||||
#[rustfmt::skip]
|
||||
pub type lua_Alloc =
|
||||
unsafe extern "C-unwind" fn(ud: *mut c_void, ptr: *mut c_void, osize: usize, nsize: usize) -> *mut c_void;
|
||||
unsafe extern "C" fn(ud: *mut c_void, ptr: *mut c_void, osize: usize, nsize: usize) -> *mut c_void;
|
||||
|
||||
#[cfg_attr(all(windows, raw_dylib), link(name = "lua53", kind = "raw-dylib"))]
|
||||
extern "C-unwind" {
|
||||
unsafe extern "C-unwind" {
|
||||
//
|
||||
// State manipulation
|
||||
//
|
||||
@@ -172,14 +172,14 @@ pub const LUA_OPLT: c_int = 1;
|
||||
pub const LUA_OPLE: c_int = 2;
|
||||
|
||||
#[cfg_attr(all(windows, raw_dylib), link(name = "lua53", kind = "raw-dylib"))]
|
||||
extern "C-unwind" {
|
||||
unsafe extern "C-unwind" {
|
||||
pub fn lua_arith(L: *mut lua_State, op: c_int);
|
||||
pub fn lua_rawequal(L: *mut lua_State, idx1: c_int, idx2: c_int) -> c_int;
|
||||
pub fn lua_compare(L: *mut lua_State, idx1: c_int, idx2: c_int, op: c_int) -> c_int;
|
||||
}
|
||||
|
||||
#[cfg_attr(all(windows, raw_dylib), link(name = "lua53", kind = "raw-dylib"))]
|
||||
extern "C-unwind" {
|
||||
unsafe extern "C-unwind" {
|
||||
//
|
||||
// Push functions (C -> stack)
|
||||
//
|
||||
@@ -251,12 +251,7 @@ extern "C-unwind" {
|
||||
mode: *const c_char,
|
||||
) -> c_int;
|
||||
|
||||
pub fn lua_dump(
|
||||
L: *mut lua_State,
|
||||
writer: lua_Writer,
|
||||
data: *mut c_void,
|
||||
strip: c_int,
|
||||
) -> c_int;
|
||||
pub fn lua_dump(L: *mut lua_State, writer: lua_Writer, data: *mut c_void, strip: c_int) -> c_int;
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
@@ -270,7 +265,7 @@ pub unsafe fn lua_pcall(L: *mut lua_State, n: c_int, r: c_int, f: c_int) -> c_in
|
||||
}
|
||||
|
||||
#[cfg_attr(all(windows, raw_dylib), link(name = "lua53", kind = "raw-dylib"))]
|
||||
extern "C-unwind" {
|
||||
unsafe extern "C-unwind" {
|
||||
//
|
||||
// Coroutine functions
|
||||
//
|
||||
@@ -305,12 +300,12 @@ pub const LUA_GCSETSTEPMUL: c_int = 7;
|
||||
pub const LUA_GCISRUNNING: c_int = 9;
|
||||
|
||||
#[cfg_attr(all(windows, raw_dylib), link(name = "lua53", kind = "raw-dylib"))]
|
||||
extern "C-unwind" {
|
||||
unsafe extern "C-unwind" {
|
||||
pub fn lua_gc(L: *mut lua_State, what: c_int, data: c_int) -> c_int;
|
||||
}
|
||||
|
||||
#[cfg_attr(all(windows, raw_dylib), link(name = "lua53", kind = "raw-dylib"))]
|
||||
extern "C-unwind" {
|
||||
unsafe extern "C-unwind" {
|
||||
//
|
||||
// Miscellaneous functions
|
||||
//
|
||||
@@ -413,10 +408,8 @@ pub unsafe fn lua_isnoneornil(L: *mut lua_State, n: c_int) -> c_int {
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn lua_pushliteral(L: *mut lua_State, s: &'static str) -> *const c_char {
|
||||
use std::ffi::CString;
|
||||
let c_str = CString::new(s).unwrap();
|
||||
lua_pushlstring(L, c_str.as_ptr(), c_str.as_bytes().len())
|
||||
pub unsafe fn lua_pushliteral(L: *mut lua_State, s: &'static CStr) {
|
||||
lua_pushstring(L, s.as_ptr());
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
@@ -484,7 +477,7 @@ pub const LUA_MASKCOUNT: c_int = 1 << (LUA_HOOKCOUNT as usize);
|
||||
pub type lua_Hook = unsafe extern "C-unwind" fn(L: *mut lua_State, ar: *mut lua_Debug);
|
||||
|
||||
#[cfg_attr(all(windows, raw_dylib), link(name = "lua53", kind = "raw-dylib"))]
|
||||
extern "C-unwind" {
|
||||
unsafe extern "C-unwind" {
|
||||
pub fn lua_getstack(L: *mut lua_State, level: c_int, ar: *mut lua_Debug) -> c_int;
|
||||
pub fn lua_getinfo(L: *mut lua_State, what: *const c_char, ar: *mut lua_Debug) -> c_int;
|
||||
pub fn lua_getlocal(L: *mut lua_State, ar: *const lua_Debug, n: c_int) -> *const c_char;
|
||||
|
||||
@@ -1,22 +1,22 @@
|
||||
//! Contains definitions from `lualib.h`.
|
||||
|
||||
use std::os::raw::c_int;
|
||||
use std::os::raw::{c_char, c_int};
|
||||
|
||||
use super::lua::lua_State;
|
||||
|
||||
pub const LUA_COLIBNAME: &str = "coroutine";
|
||||
pub const LUA_TABLIBNAME: &str = "table";
|
||||
pub const LUA_IOLIBNAME: &str = "io";
|
||||
pub const LUA_OSLIBNAME: &str = "os";
|
||||
pub const LUA_STRLIBNAME: &str = "string";
|
||||
pub const LUA_UTF8LIBNAME: &str = "utf8";
|
||||
pub const LUA_BITLIBNAME: &str = "bit32";
|
||||
pub const LUA_MATHLIBNAME: &str = "math";
|
||||
pub const LUA_DBLIBNAME: &str = "debug";
|
||||
pub const LUA_LOADLIBNAME: &str = "package";
|
||||
pub const LUA_COLIBNAME: *const c_char = cstr!("coroutine");
|
||||
pub const LUA_TABLIBNAME: *const c_char = cstr!("table");
|
||||
pub const LUA_IOLIBNAME: *const c_char = cstr!("io");
|
||||
pub const LUA_OSLIBNAME: *const c_char = cstr!("os");
|
||||
pub const LUA_STRLIBNAME: *const c_char = cstr!("string");
|
||||
pub const LUA_UTF8LIBNAME: *const c_char = cstr!("utf8");
|
||||
pub const LUA_BITLIBNAME: *const c_char = cstr!("bit32");
|
||||
pub const LUA_MATHLIBNAME: *const c_char = cstr!("math");
|
||||
pub const LUA_DBLIBNAME: *const c_char = cstr!("debug");
|
||||
pub const LUA_LOADLIBNAME: *const c_char = cstr!("package");
|
||||
|
||||
#[cfg_attr(all(windows, raw_dylib), link(name = "lua53", kind = "raw-dylib"))]
|
||||
extern "C-unwind" {
|
||||
unsafe extern "C-unwind" {
|
||||
pub fn luaopen_base(L: *mut lua_State) -> c_int;
|
||||
pub fn luaopen_coroutine(L: *mut lua_State) -> c_int;
|
||||
pub fn luaopen_table(L: *mut lua_State) -> c_int;
|
||||
|
||||
+123
-31
@@ -1,7 +1,7 @@
|
||||
//! Contains definitions from `lauxlib.h`.
|
||||
|
||||
use std::os::raw::{c_char, c_int, c_void};
|
||||
use std::ptr;
|
||||
use std::os::raw::{c_char, c_double, c_int, c_long, c_void};
|
||||
use std::{mem, ptr};
|
||||
|
||||
use super::lua::{self, lua_CFunction, lua_Integer, lua_Number, lua_State};
|
||||
|
||||
@@ -9,10 +9,10 @@ use super::lua::{self, lua_CFunction, lua_Integer, lua_Number, lua_State};
|
||||
pub const LUA_ERRFILE: c_int = lua::LUA_ERRERR + 1;
|
||||
|
||||
// Key, in the registry, for table of loaded modules
|
||||
pub const LUA_LOADED_TABLE: &str = "_LOADED";
|
||||
pub const LUA_LOADED_TABLE: *const c_char = cstr!("_LOADED");
|
||||
|
||||
// Key, in the registry, for table of preloaded loaders
|
||||
pub const LUA_PRELOAD_TABLE: &str = "_PRELOAD";
|
||||
pub const LUA_PRELOAD_TABLE: *const c_char = cstr!("_PRELOAD");
|
||||
|
||||
#[repr(C)]
|
||||
pub struct luaL_Reg {
|
||||
@@ -21,7 +21,7 @@ pub struct luaL_Reg {
|
||||
}
|
||||
|
||||
#[cfg_attr(all(windows, raw_dylib), link(name = "lua54", kind = "raw-dylib"))]
|
||||
extern "C-unwind" {
|
||||
unsafe extern "C-unwind" {
|
||||
pub fn luaL_checkversion_(L: *mut lua_State, ver: lua_Number, sz: usize);
|
||||
|
||||
pub fn luaL_getmetafield(L: *mut lua_State, obj: c_int, e: *const c_char) -> c_int;
|
||||
@@ -29,12 +29,8 @@ extern "C-unwind" {
|
||||
pub fn luaL_tolstring(L: *mut lua_State, idx: c_int, len: *mut usize) -> *const c_char;
|
||||
pub fn luaL_argerror(L: *mut lua_State, arg: c_int, extramsg: *const c_char) -> c_int;
|
||||
pub fn luaL_checklstring(L: *mut lua_State, arg: c_int, l: *mut usize) -> *const c_char;
|
||||
pub fn luaL_optlstring(
|
||||
L: *mut lua_State,
|
||||
arg: c_int,
|
||||
def: *const c_char,
|
||||
l: *mut usize,
|
||||
) -> *const c_char;
|
||||
pub fn luaL_optlstring(L: *mut lua_State, arg: c_int, def: *const c_char, l: *mut usize)
|
||||
-> *const c_char;
|
||||
pub fn luaL_checknumber(L: *mut lua_State, arg: c_int) -> lua_Number;
|
||||
pub fn luaL_optnumber(L: *mut lua_State, arg: c_int, def: lua_Number) -> lua_Number;
|
||||
pub fn luaL_checkinteger(L: *mut lua_State, arg: c_int) -> lua_Integer;
|
||||
@@ -68,12 +64,11 @@ pub const LUA_NOREF: c_int = -2;
|
||||
pub const LUA_REFNIL: c_int = -1;
|
||||
|
||||
#[cfg_attr(all(windows, raw_dylib), link(name = "lua54", kind = "raw-dylib"))]
|
||||
extern "C-unwind" {
|
||||
unsafe extern "C-unwind" {
|
||||
pub fn luaL_ref(L: *mut lua_State, t: c_int) -> c_int;
|
||||
pub fn luaL_unref(L: *mut lua_State, t: c_int, r#ref: c_int);
|
||||
|
||||
pub fn luaL_loadfilex(L: *mut lua_State, filename: *const c_char, mode: *const c_char)
|
||||
-> c_int;
|
||||
pub fn luaL_loadfilex(L: *mut lua_State, filename: *const c_char, mode: *const c_char) -> c_int;
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
@@ -82,7 +77,7 @@ pub unsafe fn luaL_loadfile(L: *mut lua_State, f: *const c_char) -> c_int {
|
||||
}
|
||||
|
||||
#[cfg_attr(all(windows, raw_dylib), link(name = "lua54", kind = "raw-dylib"))]
|
||||
extern "C-unwind" {
|
||||
unsafe extern "C-unwind" {
|
||||
pub fn luaL_loadbufferx(
|
||||
L: *mut lua_State,
|
||||
buff: *const c_char,
|
||||
@@ -96,7 +91,7 @@ extern "C-unwind" {
|
||||
|
||||
pub fn luaL_len(L: *mut lua_State, idx: c_int) -> lua_Integer;
|
||||
|
||||
// TODO: luaL_addgsub
|
||||
pub fn luaL_addgsub(B: *mut luaL_Buffer, s: *const c_char, p: *const c_char, r: *const c_char);
|
||||
|
||||
pub fn luaL_gsub(
|
||||
L: *mut lua_State,
|
||||
@@ -111,12 +106,7 @@ extern "C-unwind" {
|
||||
|
||||
pub fn luaL_traceback(L: *mut lua_State, L1: *mut lua_State, msg: *const c_char, level: c_int);
|
||||
|
||||
pub fn luaL_requiref(
|
||||
L: *mut lua_State,
|
||||
modname: *const c_char,
|
||||
openf: lua_CFunction,
|
||||
glb: c_int,
|
||||
);
|
||||
pub fn luaL_requiref(L: *mut lua_State, modname: *const c_char, openf: lua_CFunction, glb: c_int);
|
||||
}
|
||||
|
||||
//
|
||||
@@ -172,18 +162,120 @@ pub unsafe fn luaL_getmetatable(L: *mut lua_State, n: *const c_char) {
|
||||
lua::lua_getfield(L, lua::LUA_REGISTRYINDEX, n);
|
||||
}
|
||||
|
||||
// luaL_opt would be implemented here but it is undocumented, so it's omitted
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn luaL_loadbuffer(
|
||||
L: *mut lua_State,
|
||||
s: *const c_char,
|
||||
sz: usize,
|
||||
n: *const c_char,
|
||||
) -> c_int {
|
||||
pub unsafe fn luaL_loadbuffer(L: *mut lua_State, s: *const c_char, sz: usize, n: *const c_char) -> c_int {
|
||||
luaL_loadbufferx(L, s, sz, n, ptr::null())
|
||||
}
|
||||
|
||||
pub unsafe fn luaL_loadbufferenv(
|
||||
L: *mut lua_State,
|
||||
data: *const c_char,
|
||||
size: usize,
|
||||
name: *const c_char,
|
||||
mode: *const c_char,
|
||||
mut env: c_int,
|
||||
) -> c_int {
|
||||
if env != 0 {
|
||||
env = lua::lua_absindex(L, env);
|
||||
}
|
||||
let status = luaL_loadbufferx(L, data, size, name, mode);
|
||||
if status == lua::LUA_OK && env != 0 {
|
||||
lua::lua_pushvalue(L, env);
|
||||
lua::lua_setupvalue(L, -2, 1);
|
||||
}
|
||||
status
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn luaL_opt<T>(
|
||||
L: *mut lua_State,
|
||||
f: unsafe extern "C-unwind" fn(*mut lua_State, c_int) -> T,
|
||||
n: c_int,
|
||||
d: T,
|
||||
) -> T {
|
||||
if lua::lua_isnoneornil(L, n) != 0 {
|
||||
d
|
||||
} else {
|
||||
f(L, n)
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// TODO: Generic Buffer Manipulation
|
||||
// Generic Buffer Manipulation
|
||||
//
|
||||
|
||||
// The buffer size used by the lauxlib buffer system.
|
||||
// LUAL_BUFFERSIZE = (int)(16 * sizeof(void*) * sizeof(lua_Number))
|
||||
#[rustfmt::skip]
|
||||
pub const LUAL_BUFFERSIZE: usize = 16 * mem::size_of::<*const ()>() * mem::size_of::<lua_Number>();
|
||||
|
||||
// Union used for the initial buffer with maximum alignment.
|
||||
// This ensures proper alignment for the buffer data.
|
||||
#[repr(C)]
|
||||
pub union luaL_BufferInit {
|
||||
// Alignment matches LUAI_MAXALIGN
|
||||
pub _align_n: lua_Number,
|
||||
pub _align_u: c_double,
|
||||
pub _align_s: *mut c_void,
|
||||
pub _align_i: lua_Integer,
|
||||
pub _align_l: c_long,
|
||||
// Initial buffer space
|
||||
pub b: [c_char; LUAL_BUFFERSIZE],
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
pub struct luaL_Buffer {
|
||||
pub b: *mut c_char, // buffer address
|
||||
pub size: usize, // buffer size
|
||||
pub n: usize, // number of characters in buffer
|
||||
pub L: *mut lua_State,
|
||||
pub init: luaL_BufferInit, // initial buffer (union with alignment)
|
||||
}
|
||||
|
||||
#[cfg_attr(all(windows, raw_dylib), link(name = "lua54", kind = "raw-dylib"))]
|
||||
unsafe extern "C-unwind" {
|
||||
pub fn luaL_buffinit(L: *mut lua_State, B: *mut luaL_Buffer);
|
||||
pub fn luaL_prepbuffsize(B: *mut luaL_Buffer, sz: usize) -> *mut c_char;
|
||||
pub fn luaL_addlstring(B: *mut luaL_Buffer, s: *const c_char, l: usize);
|
||||
pub fn luaL_addstring(B: *mut luaL_Buffer, s: *const c_char);
|
||||
pub fn luaL_addvalue(B: *mut luaL_Buffer);
|
||||
pub fn luaL_pushresult(B: *mut luaL_Buffer);
|
||||
pub fn luaL_pushresultsize(B: *mut luaL_Buffer, sz: usize);
|
||||
pub fn luaL_buffinitsize(L: *mut lua_State, B: *mut luaL_Buffer, sz: usize) -> *mut c_char;
|
||||
}
|
||||
|
||||
// Macro implementations as inline functions
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn luaL_prepbuffer(B: *mut luaL_Buffer) -> *mut c_char {
|
||||
luaL_prepbuffsize(B, LUAL_BUFFERSIZE)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn luaL_addchar(B: *mut luaL_Buffer, c: c_char) {
|
||||
if (*B).n >= (*B).size {
|
||||
luaL_prepbuffsize(B, 1);
|
||||
}
|
||||
*(*B).b.add((*B).n) = c;
|
||||
(*B).n += 1;
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn luaL_addsize(B: *mut luaL_Buffer, n: usize) {
|
||||
(*B).n += n;
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn luaL_buffsub(B: *mut luaL_Buffer, n: usize) {
|
||||
(*B).n -= n;
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn luaL_bufflen(B: *mut luaL_Buffer) -> usize {
|
||||
(*B).n
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn luaL_buffaddr(B: *mut luaL_Buffer) -> *mut c_char {
|
||||
(*B).b
|
||||
}
|
||||
|
||||
+17
-30
@@ -1,9 +1,9 @@
|
||||
//! Contains definitions from `lua.h`.
|
||||
|
||||
use std::ffi::CStr;
|
||||
use std::marker::{PhantomData, PhantomPinned};
|
||||
use std::mem;
|
||||
use std::os::raw::{c_char, c_double, c_int, c_uchar, c_ushort, c_void};
|
||||
use std::ptr;
|
||||
use std::{mem, ptr};
|
||||
|
||||
// Mark for precompiled code (`<esc>Lua`)
|
||||
pub const LUA_SIGNATURE: &[u8] = b"\x1bLua";
|
||||
@@ -95,17 +95,16 @@ pub type lua_Reader =
|
||||
pub type lua_Writer =
|
||||
unsafe extern "C-unwind" fn(L: *mut lua_State, p: *const c_void, sz: usize, ud: *mut c_void) -> c_int;
|
||||
|
||||
/// Type for memory-allocation functions
|
||||
/// Type for memory-allocation functions (no unwinding)
|
||||
#[rustfmt::skip]
|
||||
pub type lua_Alloc =
|
||||
unsafe extern "C-unwind" fn(ud: *mut c_void, ptr: *mut c_void, osize: usize, nsize: usize) -> *mut c_void;
|
||||
unsafe extern "C" fn(ud: *mut c_void, ptr: *mut c_void, osize: usize, nsize: usize) -> *mut c_void;
|
||||
|
||||
/// Type for warning functions
|
||||
pub type lua_WarnFunction =
|
||||
unsafe extern "C-unwind" fn(ud: *mut c_void, msg: *const c_char, tocont: c_int);
|
||||
pub type lua_WarnFunction = unsafe extern "C-unwind" fn(ud: *mut c_void, msg: *const c_char, tocont: c_int);
|
||||
|
||||
#[cfg_attr(all(windows, raw_dylib), link(name = "lua54", kind = "raw-dylib"))]
|
||||
extern "C-unwind" {
|
||||
unsafe extern "C-unwind" {
|
||||
//
|
||||
// State manipulation
|
||||
//
|
||||
@@ -187,14 +186,14 @@ pub const LUA_OPLT: c_int = 1;
|
||||
pub const LUA_OPLE: c_int = 2;
|
||||
|
||||
#[cfg_attr(all(windows, raw_dylib), link(name = "lua54", kind = "raw-dylib"))]
|
||||
extern "C-unwind" {
|
||||
unsafe extern "C-unwind" {
|
||||
pub fn lua_arith(L: *mut lua_State, op: c_int);
|
||||
pub fn lua_rawequal(L: *mut lua_State, idx1: c_int, idx2: c_int) -> c_int;
|
||||
pub fn lua_compare(L: *mut lua_State, idx1: c_int, idx2: c_int, op: c_int) -> c_int;
|
||||
}
|
||||
|
||||
#[cfg_attr(all(windows, raw_dylib), link(name = "lua54", kind = "raw-dylib"))]
|
||||
extern "C-unwind" {
|
||||
unsafe extern "C-unwind" {
|
||||
//
|
||||
// Push functions (C -> stack)
|
||||
//
|
||||
@@ -266,12 +265,7 @@ extern "C-unwind" {
|
||||
mode: *const c_char,
|
||||
) -> c_int;
|
||||
|
||||
pub fn lua_dump(
|
||||
L: *mut lua_State,
|
||||
writer: lua_Writer,
|
||||
data: *mut c_void,
|
||||
strip: c_int,
|
||||
) -> c_int;
|
||||
pub fn lua_dump(L: *mut lua_State, writer: lua_Writer, data: *mut c_void, strip: c_int) -> c_int;
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
@@ -285,7 +279,7 @@ pub unsafe fn lua_pcall(L: *mut lua_State, n: c_int, r: c_int, f: c_int) -> c_in
|
||||
}
|
||||
|
||||
#[cfg_attr(all(windows, raw_dylib), link(name = "lua54", kind = "raw-dylib"))]
|
||||
extern "C-unwind" {
|
||||
unsafe extern "C-unwind" {
|
||||
//
|
||||
// Coroutine functions
|
||||
//
|
||||
@@ -295,12 +289,7 @@ extern "C-unwind" {
|
||||
ctx: lua_KContext,
|
||||
k: Option<lua_KFunction>,
|
||||
) -> c_int;
|
||||
pub fn lua_resume(
|
||||
L: *mut lua_State,
|
||||
from: *mut lua_State,
|
||||
narg: c_int,
|
||||
nres: *mut c_int,
|
||||
) -> c_int;
|
||||
pub fn lua_resume(L: *mut lua_State, from: *mut lua_State, narg: c_int, nres: *mut c_int) -> c_int;
|
||||
pub fn lua_status(L: *mut lua_State) -> c_int;
|
||||
pub fn lua_isyieldable(L: *mut lua_State) -> c_int;
|
||||
}
|
||||
@@ -314,7 +303,7 @@ pub unsafe fn lua_yield(L: *mut lua_State, n: c_int) -> c_int {
|
||||
// Warning-related functions
|
||||
//
|
||||
#[cfg_attr(all(windows, raw_dylib), link(name = "lua54", kind = "raw-dylib"))]
|
||||
extern "C-unwind" {
|
||||
unsafe extern "C-unwind" {
|
||||
pub fn lua_setwarnf(L: *mut lua_State, f: Option<lua_WarnFunction>, ud: *mut c_void);
|
||||
pub fn lua_warning(L: *mut lua_State, msg: *const c_char, tocont: c_int);
|
||||
}
|
||||
@@ -335,12 +324,12 @@ pub const LUA_GCGEN: c_int = 10;
|
||||
pub const LUA_GCINC: c_int = 11;
|
||||
|
||||
#[cfg_attr(all(windows, raw_dylib), link(name = "lua54", kind = "raw-dylib"))]
|
||||
extern "C-unwind" {
|
||||
unsafe extern "C-unwind" {
|
||||
pub fn lua_gc(L: *mut lua_State, what: c_int, ...) -> c_int;
|
||||
}
|
||||
|
||||
#[cfg_attr(all(windows, raw_dylib), link(name = "lua54", kind = "raw-dylib"))]
|
||||
extern "C-unwind" {
|
||||
unsafe extern "C-unwind" {
|
||||
//
|
||||
// Miscellaneous functions
|
||||
//
|
||||
@@ -446,10 +435,8 @@ pub unsafe fn lua_isnoneornil(L: *mut lua_State, n: c_int) -> c_int {
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn lua_pushliteral(L: *mut lua_State, s: &'static str) -> *const c_char {
|
||||
use std::ffi::CString;
|
||||
let c_str = CString::new(s).unwrap();
|
||||
lua_pushlstring(L, c_str.as_ptr(), c_str.as_bytes().len())
|
||||
pub unsafe fn lua_pushliteral(L: *mut lua_State, s: &'static CStr) {
|
||||
lua_pushstring(L, s.as_ptr());
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
@@ -532,7 +519,7 @@ pub const LUA_MASKCOUNT: c_int = 1 << (LUA_HOOKCOUNT as usize);
|
||||
pub type lua_Hook = unsafe extern "C-unwind" fn(L: *mut lua_State, ar: *mut lua_Debug);
|
||||
|
||||
#[cfg_attr(all(windows, raw_dylib), link(name = "lua54", kind = "raw-dylib"))]
|
||||
extern "C-unwind" {
|
||||
unsafe extern "C-unwind" {
|
||||
pub fn lua_getstack(L: *mut lua_State, level: c_int, ar: *mut lua_Debug) -> c_int;
|
||||
pub fn lua_getinfo(L: *mut lua_State, what: *const c_char, ar: *mut lua_Debug) -> c_int;
|
||||
pub fn lua_getlocal(L: *mut lua_State, ar: *const lua_Debug, n: c_int) -> *const c_char;
|
||||
|
||||
@@ -1,21 +1,21 @@
|
||||
//! Contains definitions from `lualib.h`.
|
||||
|
||||
use std::os::raw::c_int;
|
||||
use std::os::raw::{c_char, c_int};
|
||||
|
||||
use super::lua::lua_State;
|
||||
|
||||
pub const LUA_COLIBNAME: &str = "coroutine";
|
||||
pub const LUA_TABLIBNAME: &str = "table";
|
||||
pub const LUA_IOLIBNAME: &str = "io";
|
||||
pub const LUA_OSLIBNAME: &str = "os";
|
||||
pub const LUA_STRLIBNAME: &str = "string";
|
||||
pub const LUA_UTF8LIBNAME: &str = "utf8";
|
||||
pub const LUA_MATHLIBNAME: &str = "math";
|
||||
pub const LUA_DBLIBNAME: &str = "debug";
|
||||
pub const LUA_LOADLIBNAME: &str = "package";
|
||||
pub const LUA_COLIBNAME: *const c_char = cstr!("coroutine");
|
||||
pub const LUA_TABLIBNAME: *const c_char = cstr!("table");
|
||||
pub const LUA_IOLIBNAME: *const c_char = cstr!("io");
|
||||
pub const LUA_OSLIBNAME: *const c_char = cstr!("os");
|
||||
pub const LUA_STRLIBNAME: *const c_char = cstr!("string");
|
||||
pub const LUA_UTF8LIBNAME: *const c_char = cstr!("utf8");
|
||||
pub const LUA_MATHLIBNAME: *const c_char = cstr!("math");
|
||||
pub const LUA_DBLIBNAME: *const c_char = cstr!("debug");
|
||||
pub const LUA_LOADLIBNAME: *const c_char = cstr!("package");
|
||||
|
||||
#[cfg_attr(all(windows, raw_dylib), link(name = "lua54", kind = "raw-dylib"))]
|
||||
extern "C-unwind" {
|
||||
unsafe extern "C-unwind" {
|
||||
pub fn luaopen_base(L: *mut lua_State) -> c_int;
|
||||
pub fn luaopen_coroutine(L: *mut lua_State) -> c_int;
|
||||
pub fn luaopen_table(L: *mut lua_State) -> c_int;
|
||||
|
||||
@@ -0,0 +1,299 @@
|
||||
//! Contains definitions from `lauxlib.h`.
|
||||
|
||||
use std::os::raw::{c_char, c_double, c_int, c_long, c_uint, c_void};
|
||||
use std::{mem, ptr};
|
||||
|
||||
use super::lua::{self, lua_CFunction, lua_Integer, lua_Number, lua_State};
|
||||
|
||||
// Extra error code for 'luaL_loadfilex'
|
||||
pub const LUA_ERRFILE: c_int = lua::LUA_ERRERR + 1;
|
||||
|
||||
// Key, in the registry, for table of loaded modules
|
||||
pub const LUA_LOADED_TABLE: *const c_char = cstr!("_LOADED");
|
||||
|
||||
// Key, in the registry, for table of preloaded loaders
|
||||
pub const LUA_PRELOAD_TABLE: *const c_char = cstr!("_PRELOAD");
|
||||
|
||||
#[repr(C)]
|
||||
pub struct luaL_Reg {
|
||||
pub name: *const c_char,
|
||||
pub func: lua_CFunction,
|
||||
}
|
||||
|
||||
#[cfg_attr(all(windows, raw_dylib), link(name = "lua55", kind = "raw-dylib"))]
|
||||
unsafe extern "C-unwind" {
|
||||
pub fn luaL_checkversion_(L: *mut lua_State, ver: lua_Number, sz: usize);
|
||||
|
||||
pub fn luaL_getmetafield(L: *mut lua_State, obj: c_int, e: *const c_char) -> c_int;
|
||||
pub fn luaL_callmeta(L: *mut lua_State, obj: c_int, e: *const c_char) -> c_int;
|
||||
pub fn luaL_tolstring(L: *mut lua_State, idx: c_int, len: *mut usize) -> *const c_char;
|
||||
pub fn luaL_argerror(L: *mut lua_State, arg: c_int, extramsg: *const c_char) -> c_int;
|
||||
pub fn luaL_checklstring(L: *mut lua_State, arg: c_int, l: *mut usize) -> *const c_char;
|
||||
pub fn luaL_optlstring(L: *mut lua_State, arg: c_int, def: *const c_char, l: *mut usize)
|
||||
-> *const c_char;
|
||||
pub fn luaL_checknumber(L: *mut lua_State, arg: c_int) -> lua_Number;
|
||||
pub fn luaL_optnumber(L: *mut lua_State, arg: c_int, def: lua_Number) -> lua_Number;
|
||||
pub fn luaL_checkinteger(L: *mut lua_State, arg: c_int) -> lua_Integer;
|
||||
pub fn luaL_optinteger(L: *mut lua_State, arg: c_int, def: lua_Integer) -> lua_Integer;
|
||||
|
||||
pub fn luaL_checkstack(L: *mut lua_State, sz: c_int, msg: *const c_char);
|
||||
pub fn luaL_checktype(L: *mut lua_State, arg: c_int, t: c_int);
|
||||
pub fn luaL_checkany(L: *mut lua_State, arg: c_int);
|
||||
|
||||
pub fn luaL_newmetatable(L: *mut lua_State, tname: *const c_char) -> c_int;
|
||||
pub fn luaL_setmetatable(L: *mut lua_State, tname: *const c_char);
|
||||
pub fn luaL_testudata(L: *mut lua_State, ud: c_int, tname: *const c_char) -> *mut c_void;
|
||||
pub fn luaL_checkudata(L: *mut lua_State, ud: c_int, tname: *const c_char) -> *mut c_void;
|
||||
|
||||
pub fn luaL_where(L: *mut lua_State, lvl: c_int);
|
||||
pub fn luaL_error(L: *mut lua_State, fmt: *const c_char, ...) -> c_int;
|
||||
|
||||
pub fn luaL_checkoption(
|
||||
L: *mut lua_State,
|
||||
arg: c_int,
|
||||
def: *const c_char,
|
||||
lst: *const *const c_char,
|
||||
) -> c_int;
|
||||
|
||||
pub fn luaL_fileresult(L: *mut lua_State, stat: c_int, fname: *const c_char) -> c_int;
|
||||
pub fn luaL_execresult(L: *mut lua_State, stat: c_int) -> c_int;
|
||||
pub fn luaL_alloc(L: *mut lua_State, ptr: *mut c_void, osize: usize, nsize: usize) -> *mut c_void;
|
||||
}
|
||||
|
||||
// Pre-defined references
|
||||
pub const LUA_NOREF: c_int = -2;
|
||||
pub const LUA_REFNIL: c_int = -1;
|
||||
|
||||
#[cfg_attr(all(windows, raw_dylib), link(name = "lua55", kind = "raw-dylib"))]
|
||||
unsafe extern "C-unwind" {
|
||||
pub fn luaL_ref(L: *mut lua_State, t: c_int) -> c_int;
|
||||
pub fn luaL_unref(L: *mut lua_State, t: c_int, r#ref: c_int);
|
||||
|
||||
pub fn luaL_loadfilex(L: *mut lua_State, filename: *const c_char, mode: *const c_char) -> c_int;
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn luaL_loadfile(L: *mut lua_State, f: *const c_char) -> c_int {
|
||||
luaL_loadfilex(L, f, ptr::null())
|
||||
}
|
||||
|
||||
#[cfg_attr(all(windows, raw_dylib), link(name = "lua55", kind = "raw-dylib"))]
|
||||
unsafe extern "C-unwind" {
|
||||
pub fn luaL_loadbufferx(
|
||||
L: *mut lua_State,
|
||||
buff: *const c_char,
|
||||
sz: usize,
|
||||
name: *const c_char,
|
||||
mode: *const c_char,
|
||||
) -> c_int;
|
||||
pub fn luaL_loadstring(L: *mut lua_State, s: *const c_char) -> c_int;
|
||||
|
||||
pub fn luaL_newstate() -> *mut lua_State;
|
||||
|
||||
#[link_name = "luaL_makeseed"]
|
||||
pub fn luaL_makeseed_(L: *mut lua_State) -> c_uint;
|
||||
|
||||
pub fn luaL_len(L: *mut lua_State, idx: c_int) -> lua_Integer;
|
||||
|
||||
pub fn luaL_addgsub(B: *mut luaL_Buffer, s: *const c_char, p: *const c_char, r: *const c_char);
|
||||
|
||||
pub fn luaL_gsub(
|
||||
L: *mut lua_State,
|
||||
s: *const c_char,
|
||||
p: *const c_char,
|
||||
r: *const c_char,
|
||||
) -> *const c_char;
|
||||
|
||||
pub fn luaL_setfuncs(L: *mut lua_State, l: *const luaL_Reg, nup: c_int);
|
||||
|
||||
pub fn luaL_getsubtable(L: *mut lua_State, idx: c_int, fname: *const c_char) -> c_int;
|
||||
|
||||
pub fn luaL_traceback(L: *mut lua_State, L1: *mut lua_State, msg: *const c_char, level: c_int);
|
||||
|
||||
pub fn luaL_requiref(L: *mut lua_State, modname: *const c_char, openf: lua_CFunction, glb: c_int);
|
||||
}
|
||||
|
||||
//
|
||||
// Some useful macros (implemented as Rust functions)
|
||||
//
|
||||
|
||||
// TODO: luaL_newlibtable, luaL_newlib
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn luaL_argcheck(L: *mut lua_State, cond: c_int, arg: c_int, extramsg: *const c_char) {
|
||||
if cond == 0 {
|
||||
luaL_argerror(L, arg, extramsg);
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn luaL_checkstring(L: *mut lua_State, n: c_int) -> *const c_char {
|
||||
luaL_checklstring(L, n, ptr::null_mut())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn luaL_optstring(L: *mut lua_State, n: c_int, d: *const c_char) -> *const c_char {
|
||||
luaL_optlstring(L, n, d, ptr::null_mut())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn luaL_typename(L: *mut lua_State, i: c_int) -> *const c_char {
|
||||
lua::lua_typename(L, lua::lua_type(L, i))
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn luaL_dofile(L: *mut lua_State, filename: *const c_char) -> c_int {
|
||||
let status = luaL_loadfile(L, filename);
|
||||
if status == 0 {
|
||||
lua::lua_pcall(L, 0, lua::LUA_MULTRET, 0)
|
||||
} else {
|
||||
status
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn luaL_dostring(L: *mut lua_State, s: *const c_char) -> c_int {
|
||||
let status = luaL_loadstring(L, s);
|
||||
if status == 0 {
|
||||
lua::lua_pcall(L, 0, lua::LUA_MULTRET, 0)
|
||||
} else {
|
||||
status
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn luaL_getmetatable(L: *mut lua_State, n: *const c_char) {
|
||||
lua::lua_getfield(L, lua::LUA_REGISTRYINDEX, n);
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn luaL_loadbuffer(L: *mut lua_State, s: *const c_char, sz: usize, n: *const c_char) -> c_int {
|
||||
luaL_loadbufferx(L, s, sz, n, ptr::null())
|
||||
}
|
||||
|
||||
pub unsafe fn luaL_loadbufferenv(
|
||||
L: *mut lua_State,
|
||||
data: *const c_char,
|
||||
size: usize,
|
||||
name: *const c_char,
|
||||
mode: *const c_char,
|
||||
mut env: c_int,
|
||||
) -> c_int {
|
||||
if env != 0 {
|
||||
env = lua::lua_absindex(L, env);
|
||||
}
|
||||
let status = luaL_loadbufferx(L, data, size, name, mode);
|
||||
if status == lua::LUA_OK && env != 0 {
|
||||
lua::lua_pushvalue(L, env);
|
||||
lua::lua_setupvalue(L, -2, 1);
|
||||
}
|
||||
status
|
||||
}
|
||||
|
||||
pub unsafe fn luaL_makeseed(L: *mut lua_State) -> c_uint {
|
||||
#[cfg(macos)]
|
||||
return libc::arc4random();
|
||||
#[cfg(linux)]
|
||||
{
|
||||
let mut seed = 0u32;
|
||||
let buf = &mut seed as *mut _ as *mut c_void;
|
||||
if libc::getrandom(buf, 4, libc::GRND_NONBLOCK) == 4 {
|
||||
return seed;
|
||||
}
|
||||
}
|
||||
luaL_makeseed_(L)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn luaL_opt<T>(
|
||||
L: *mut lua_State,
|
||||
f: unsafe extern "C-unwind" fn(*mut lua_State, c_int) -> T,
|
||||
n: c_int,
|
||||
d: T,
|
||||
) -> T {
|
||||
if lua::lua_isnoneornil(L, n) != 0 {
|
||||
d
|
||||
} else {
|
||||
f(L, n)
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// Generic Buffer Manipulation
|
||||
//
|
||||
|
||||
// The buffer size used by the lauxlib buffer system.
|
||||
// LUAL_BUFFERSIZE = (int)(16 * sizeof(void*) * sizeof(lua_Number))
|
||||
#[rustfmt::skip]
|
||||
pub const LUAL_BUFFERSIZE: usize = 16 * mem::size_of::<*const ()>() * mem::size_of::<lua_Number>();
|
||||
|
||||
// Union used for the initial buffer with maximum alignment.
|
||||
// This ensures proper alignment for the buffer data.
|
||||
#[repr(C)]
|
||||
pub union luaL_BufferInit {
|
||||
// Alignment matches LUAI_MAXALIGN
|
||||
pub _align_n: lua_Number,
|
||||
pub _align_u: c_double,
|
||||
pub _align_s: *mut c_void,
|
||||
pub _align_i: lua_Integer,
|
||||
pub _align_l: c_long,
|
||||
// Initial buffer space
|
||||
pub b: [c_char; LUAL_BUFFERSIZE],
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
pub struct luaL_Buffer {
|
||||
pub b: *mut c_char, // buffer address
|
||||
pub size: usize, // buffer size
|
||||
pub n: usize, // number of characters in buffer
|
||||
pub L: *mut lua_State,
|
||||
pub init: luaL_BufferInit, // initial buffer (union with alignment)
|
||||
}
|
||||
|
||||
#[cfg_attr(all(windows, raw_dylib), link(name = "lua55", kind = "raw-dylib"))]
|
||||
unsafe extern "C-unwind" {
|
||||
pub fn luaL_buffinit(L: *mut lua_State, B: *mut luaL_Buffer);
|
||||
pub fn luaL_prepbuffsize(B: *mut luaL_Buffer, sz: usize) -> *mut c_char;
|
||||
pub fn luaL_addlstring(B: *mut luaL_Buffer, s: *const c_char, l: usize);
|
||||
pub fn luaL_addstring(B: *mut luaL_Buffer, s: *const c_char);
|
||||
pub fn luaL_addvalue(B: *mut luaL_Buffer);
|
||||
pub fn luaL_pushresult(B: *mut luaL_Buffer);
|
||||
pub fn luaL_pushresultsize(B: *mut luaL_Buffer, sz: usize);
|
||||
pub fn luaL_buffinitsize(L: *mut lua_State, B: *mut luaL_Buffer, sz: usize) -> *mut c_char;
|
||||
}
|
||||
|
||||
// Macro implementations as inline functions
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn luaL_prepbuffer(B: *mut luaL_Buffer) -> *mut c_char {
|
||||
luaL_prepbuffsize(B, LUAL_BUFFERSIZE)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn luaL_addchar(B: *mut luaL_Buffer, c: c_char) {
|
||||
if (*B).n >= (*B).size {
|
||||
luaL_prepbuffsize(B, 1);
|
||||
}
|
||||
*(*B).b.add((*B).n) = c;
|
||||
(*B).n += 1;
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn luaL_addsize(B: *mut luaL_Buffer, n: usize) {
|
||||
(*B).n += n;
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn luaL_buffsub(B: *mut luaL_Buffer, n: usize) {
|
||||
(*B).n -= n;
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn luaL_bufflen(B: *mut luaL_Buffer) -> usize {
|
||||
(*B).n
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn luaL_buffaddr(B: *mut luaL_Buffer) -> *mut c_char {
|
||||
(*B).b
|
||||
}
|
||||
@@ -0,0 +1,578 @@
|
||||
//! Contains definitions from `lua.h`.
|
||||
|
||||
use std::ffi::CStr;
|
||||
use std::marker::{PhantomData, PhantomPinned};
|
||||
use std::os::raw::{c_char, c_double, c_int, c_uchar, c_uint, c_void};
|
||||
use std::{mem, ptr};
|
||||
|
||||
// Mark for precompiled code (`<esc>Lua`)
|
||||
pub const LUA_SIGNATURE: &[u8] = b"\x1bLua";
|
||||
|
||||
// Option for multiple returns in 'lua_pcall' and 'lua_call'
|
||||
pub const LUA_MULTRET: c_int = -1;
|
||||
|
||||
// Size of the Lua stack
|
||||
#[doc(hidden)]
|
||||
pub const LUAI_MAXSTACK: c_int = c_int::MAX;
|
||||
|
||||
// Size of a raw memory area associated with a Lua state with very fast access.
|
||||
pub const LUA_EXTRASPACE: usize = mem::size_of::<*const ()>();
|
||||
|
||||
//
|
||||
// Pseudo-indices
|
||||
//
|
||||
pub const LUA_REGISTRYINDEX: c_int = -(c_int::MAX / 2 + 1000);
|
||||
|
||||
pub const fn lua_upvalueindex(i: c_int) -> c_int {
|
||||
LUA_REGISTRYINDEX - i
|
||||
}
|
||||
|
||||
//
|
||||
// Thread status
|
||||
//
|
||||
pub const LUA_OK: c_int = 0;
|
||||
pub const LUA_YIELD: c_int = 1;
|
||||
pub const LUA_ERRRUN: c_int = 2;
|
||||
pub const LUA_ERRSYNTAX: c_int = 3;
|
||||
pub const LUA_ERRMEM: c_int = 4;
|
||||
pub const LUA_ERRERR: c_int = 5;
|
||||
|
||||
/// A raw Lua state associated with a thread.
|
||||
#[repr(C)]
|
||||
pub struct lua_State {
|
||||
_data: [u8; 0],
|
||||
_marker: PhantomData<(*mut u8, PhantomPinned)>,
|
||||
}
|
||||
|
||||
//
|
||||
// Basic types
|
||||
//
|
||||
pub const LUA_TNONE: c_int = -1;
|
||||
|
||||
pub const LUA_TNIL: c_int = 0;
|
||||
pub const LUA_TBOOLEAN: c_int = 1;
|
||||
pub const LUA_TLIGHTUSERDATA: c_int = 2;
|
||||
pub const LUA_TNUMBER: c_int = 3;
|
||||
pub const LUA_TSTRING: c_int = 4;
|
||||
pub const LUA_TTABLE: c_int = 5;
|
||||
pub const LUA_TFUNCTION: c_int = 6;
|
||||
pub const LUA_TUSERDATA: c_int = 7;
|
||||
pub const LUA_TTHREAD: c_int = 8;
|
||||
|
||||
pub const LUA_NUMTYPES: c_int = 9;
|
||||
|
||||
/// Minimum Lua stack available to a C function
|
||||
pub const LUA_MINSTACK: c_int = 20;
|
||||
|
||||
// Predefined values in the registry
|
||||
// index 1 is reserved for the reference mechanism
|
||||
pub const LUA_RIDX_GLOBALS: lua_Integer = 2;
|
||||
pub const LUA_RIDX_MAINTHREAD: lua_Integer = 3;
|
||||
pub const LUA_RIDX_LAST: lua_Integer = 3;
|
||||
|
||||
/// A Lua number, usually equivalent to `f64`
|
||||
pub type lua_Number = c_double;
|
||||
|
||||
/// A Lua integer, usually equivalent to `i64`
|
||||
pub type lua_Integer = i64;
|
||||
|
||||
/// A Lua unsigned integer, usually equivalent to `u64`
|
||||
pub type lua_Unsigned = u64;
|
||||
|
||||
/// Type for continuation-function contexts
|
||||
pub type lua_KContext = isize;
|
||||
|
||||
/// Type for native C functions that can be passed to Lua
|
||||
pub type lua_CFunction = unsafe extern "C-unwind" fn(L: *mut lua_State) -> c_int;
|
||||
|
||||
/// Type for continuation functions
|
||||
pub type lua_KFunction =
|
||||
unsafe extern "C-unwind" fn(L: *mut lua_State, status: c_int, ctx: lua_KContext) -> c_int;
|
||||
|
||||
// Type for functions that read/write blocks when loading/dumping Lua chunks
|
||||
#[rustfmt::skip]
|
||||
pub type lua_Reader =
|
||||
unsafe extern "C-unwind" fn(L: *mut lua_State, ud: *mut c_void, sz: *mut usize) -> *const c_char;
|
||||
#[rustfmt::skip]
|
||||
pub type lua_Writer =
|
||||
unsafe extern "C-unwind" fn(L: *mut lua_State, p: *const c_void, sz: usize, ud: *mut c_void) -> c_int;
|
||||
|
||||
/// Type for memory-allocation functions (no unwinding)
|
||||
#[rustfmt::skip]
|
||||
pub type lua_Alloc =
|
||||
unsafe extern "C" fn(ud: *mut c_void, ptr: *mut c_void, osize: usize, nsize: usize) -> *mut c_void;
|
||||
|
||||
/// Type for warning functions
|
||||
pub type lua_WarnFunction = unsafe extern "C-unwind" fn(ud: *mut c_void, msg: *const c_char, tocont: c_int);
|
||||
|
||||
#[cfg_attr(all(windows, raw_dylib), link(name = "lua55", kind = "raw-dylib"))]
|
||||
unsafe extern "C-unwind" {
|
||||
//
|
||||
// State manipulation
|
||||
//
|
||||
pub fn lua_newstate(f: lua_Alloc, ud: *mut c_void, seed: c_uint) -> *mut lua_State;
|
||||
pub fn lua_close(L: *mut lua_State);
|
||||
pub fn lua_newthread(L: *mut lua_State) -> *mut lua_State;
|
||||
pub fn lua_closethread(L: *mut lua_State, from: *mut lua_State) -> c_int;
|
||||
|
||||
pub fn lua_atpanic(L: *mut lua_State, panicf: lua_CFunction) -> lua_CFunction;
|
||||
|
||||
pub fn lua_version(L: *mut lua_State) -> lua_Number;
|
||||
|
||||
//
|
||||
// Basic stack manipulation
|
||||
//
|
||||
pub fn lua_absindex(L: *mut lua_State, idx: c_int) -> c_int;
|
||||
pub fn lua_gettop(L: *mut lua_State) -> c_int;
|
||||
pub fn lua_settop(L: *mut lua_State, idx: c_int);
|
||||
pub fn lua_pushvalue(L: *mut lua_State, idx: c_int);
|
||||
pub fn lua_rotate(L: *mut lua_State, idx: c_int, n: c_int);
|
||||
pub fn lua_copy(L: *mut lua_State, fromidx: c_int, toidx: c_int);
|
||||
pub fn lua_checkstack(L: *mut lua_State, sz: c_int) -> c_int;
|
||||
|
||||
pub fn lua_xmove(from: *mut lua_State, to: *mut lua_State, n: c_int);
|
||||
|
||||
//
|
||||
// Access functions (stack -> C)
|
||||
//
|
||||
pub fn lua_isnumber(L: *mut lua_State, idx: c_int) -> c_int;
|
||||
pub fn lua_isstring(L: *mut lua_State, idx: c_int) -> c_int;
|
||||
pub fn lua_iscfunction(L: *mut lua_State, idx: c_int) -> c_int;
|
||||
pub fn lua_isinteger(L: *mut lua_State, idx: c_int) -> c_int;
|
||||
pub fn lua_isuserdata(L: *mut lua_State, idx: c_int) -> c_int;
|
||||
pub fn lua_type(L: *mut lua_State, idx: c_int) -> c_int;
|
||||
pub fn lua_typename(L: *mut lua_State, tp: c_int) -> *const c_char;
|
||||
|
||||
pub fn lua_tonumberx(L: *mut lua_State, idx: c_int, isnum: *mut c_int) -> lua_Number;
|
||||
pub fn lua_tointegerx(L: *mut lua_State, idx: c_int, isnum: *mut c_int) -> lua_Integer;
|
||||
pub fn lua_toboolean(L: *mut lua_State, idx: c_int) -> c_int;
|
||||
pub fn lua_tolstring(L: *mut lua_State, idx: c_int, len: *mut usize) -> *const c_char;
|
||||
#[link_name = "lua_rawlen"]
|
||||
fn lua_rawlen_(L: *mut lua_State, idx: c_int) -> lua_Unsigned;
|
||||
pub fn lua_tocfunction(L: *mut lua_State, idx: c_int) -> Option<lua_CFunction>;
|
||||
pub fn lua_touserdata(L: *mut lua_State, idx: c_int) -> *mut c_void;
|
||||
pub fn lua_tothread(L: *mut lua_State, idx: c_int) -> *mut lua_State;
|
||||
pub fn lua_topointer(L: *mut lua_State, idx: c_int) -> *const c_void;
|
||||
}
|
||||
|
||||
// lua_rawlen's return type changed from size_t to lua_Unsigned int in Lua 5.4.
|
||||
// This adapts the crate API to the new Lua ABI.
|
||||
#[inline(always)]
|
||||
pub unsafe fn lua_rawlen(L: *mut lua_State, idx: c_int) -> usize {
|
||||
lua_rawlen_(L, idx) as usize
|
||||
}
|
||||
|
||||
//
|
||||
// Comparison and arithmetic functions
|
||||
//
|
||||
pub const LUA_OPADD: c_int = 0;
|
||||
pub const LUA_OPSUB: c_int = 1;
|
||||
pub const LUA_OPMUL: c_int = 2;
|
||||
pub const LUA_OPMOD: c_int = 3;
|
||||
pub const LUA_OPPOW: c_int = 4;
|
||||
pub const LUA_OPDIV: c_int = 5;
|
||||
pub const LUA_OPIDIV: c_int = 6;
|
||||
pub const LUA_OPBAND: c_int = 7;
|
||||
pub const LUA_OPBOR: c_int = 8;
|
||||
pub const LUA_OPBXOR: c_int = 9;
|
||||
pub const LUA_OPSHL: c_int = 10;
|
||||
pub const LUA_OPSHR: c_int = 11;
|
||||
pub const LUA_OPUNM: c_int = 12;
|
||||
pub const LUA_OPBNOT: c_int = 13;
|
||||
|
||||
pub const LUA_OPEQ: c_int = 0;
|
||||
pub const LUA_OPLT: c_int = 1;
|
||||
pub const LUA_OPLE: c_int = 2;
|
||||
|
||||
#[cfg_attr(all(windows, raw_dylib), link(name = "lua55", kind = "raw-dylib"))]
|
||||
unsafe extern "C-unwind" {
|
||||
pub fn lua_arith(L: *mut lua_State, op: c_int);
|
||||
pub fn lua_rawequal(L: *mut lua_State, idx1: c_int, idx2: c_int) -> c_int;
|
||||
pub fn lua_compare(L: *mut lua_State, idx1: c_int, idx2: c_int, op: c_int) -> c_int;
|
||||
}
|
||||
|
||||
#[cfg_attr(all(windows, raw_dylib), link(name = "lua55", kind = "raw-dylib"))]
|
||||
unsafe extern "C-unwind" {
|
||||
//
|
||||
// Push functions (C -> stack)
|
||||
//
|
||||
pub fn lua_pushnil(L: *mut lua_State);
|
||||
pub fn lua_pushnumber(L: *mut lua_State, n: lua_Number);
|
||||
pub fn lua_pushinteger(L: *mut lua_State, n: lua_Integer);
|
||||
pub fn lua_pushlstring(L: *mut lua_State, s: *const c_char, len: usize) -> *const c_char;
|
||||
pub fn lua_pushexternalstring(
|
||||
L: *mut lua_State,
|
||||
s: *const c_char,
|
||||
len: usize,
|
||||
falloc: Option<lua_Alloc>,
|
||||
ud: *mut c_void,
|
||||
) -> *const c_char;
|
||||
pub fn lua_pushstring(L: *mut lua_State, s: *const c_char) -> *const c_char;
|
||||
// lua_pushvfstring
|
||||
pub fn lua_pushfstring(L: *mut lua_State, fmt: *const c_char, ...) -> *const c_char;
|
||||
pub fn lua_pushcclosure(L: *mut lua_State, f: lua_CFunction, n: c_int);
|
||||
pub fn lua_pushboolean(L: *mut lua_State, b: c_int);
|
||||
pub fn lua_pushlightuserdata(L: *mut lua_State, p: *mut c_void);
|
||||
pub fn lua_pushthread(L: *mut lua_State) -> c_int;
|
||||
|
||||
//
|
||||
// Get functions (Lua -> stack)
|
||||
//
|
||||
pub fn lua_getglobal(L: *mut lua_State, name: *const c_char) -> c_int;
|
||||
pub fn lua_gettable(L: *mut lua_State, idx: c_int) -> c_int;
|
||||
pub fn lua_getfield(L: *mut lua_State, idx: c_int, k: *const c_char) -> c_int;
|
||||
pub fn lua_geti(L: *mut lua_State, idx: c_int, n: lua_Integer) -> c_int;
|
||||
pub fn lua_rawget(L: *mut lua_State, idx: c_int) -> c_int;
|
||||
pub fn lua_rawgeti(L: *mut lua_State, idx: c_int, n: lua_Integer) -> c_int;
|
||||
pub fn lua_rawgetp(L: *mut lua_State, idx: c_int, p: *const c_void) -> c_int;
|
||||
|
||||
pub fn lua_createtable(L: *mut lua_State, narr: c_int, nrec: c_int);
|
||||
pub fn lua_newuserdatauv(L: *mut lua_State, sz: usize, nuvalue: c_int) -> *mut c_void;
|
||||
pub fn lua_getmetatable(L: *mut lua_State, objindex: c_int) -> c_int;
|
||||
pub fn lua_getiuservalue(L: *mut lua_State, idx: c_int, n: c_int) -> c_int;
|
||||
|
||||
//
|
||||
// Set functions (stack -> Lua)
|
||||
//
|
||||
pub fn lua_setglobal(L: *mut lua_State, name: *const c_char);
|
||||
pub fn lua_settable(L: *mut lua_State, idx: c_int);
|
||||
pub fn lua_setfield(L: *mut lua_State, idx: c_int, k: *const c_char);
|
||||
pub fn lua_seti(L: *mut lua_State, idx: c_int, n: lua_Integer);
|
||||
pub fn lua_rawset(L: *mut lua_State, idx: c_int);
|
||||
pub fn lua_rawseti(L: *mut lua_State, idx: c_int, n: lua_Integer);
|
||||
pub fn lua_rawsetp(L: *mut lua_State, idx: c_int, p: *const c_void);
|
||||
pub fn lua_setmetatable(L: *mut lua_State, objindex: c_int) -> c_int;
|
||||
pub fn lua_setiuservalue(L: *mut lua_State, idx: c_int, n: c_int) -> c_int;
|
||||
|
||||
//
|
||||
// 'load' and 'call' functions (load and run Lua code)
|
||||
//
|
||||
pub fn lua_callk(
|
||||
L: *mut lua_State,
|
||||
nargs: c_int,
|
||||
nresults: c_int,
|
||||
ctx: lua_KContext,
|
||||
k: Option<lua_KFunction>,
|
||||
);
|
||||
pub fn lua_pcallk(
|
||||
L: *mut lua_State,
|
||||
nargs: c_int,
|
||||
nresults: c_int,
|
||||
errfunc: c_int,
|
||||
ctx: lua_KContext,
|
||||
k: Option<lua_KFunction>,
|
||||
) -> c_int;
|
||||
|
||||
pub fn lua_load(
|
||||
L: *mut lua_State,
|
||||
reader: lua_Reader,
|
||||
data: *mut c_void,
|
||||
chunkname: *const c_char,
|
||||
mode: *const c_char,
|
||||
) -> c_int;
|
||||
|
||||
pub fn lua_dump(L: *mut lua_State, writer: lua_Writer, data: *mut c_void, strip: c_int) -> c_int;
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn lua_call(L: *mut lua_State, n: c_int, r: c_int) {
|
||||
lua_callk(L, n, r, 0, None)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn lua_pcall(L: *mut lua_State, n: c_int, r: c_int, f: c_int) -> c_int {
|
||||
lua_pcallk(L, n, r, f, 0, None)
|
||||
}
|
||||
|
||||
#[cfg_attr(all(windows, raw_dylib), link(name = "lua55", kind = "raw-dylib"))]
|
||||
unsafe extern "C-unwind" {
|
||||
//
|
||||
// Coroutine functions
|
||||
//
|
||||
pub fn lua_yieldk(
|
||||
L: *mut lua_State,
|
||||
nresults: c_int,
|
||||
ctx: lua_KContext,
|
||||
k: Option<lua_KFunction>,
|
||||
) -> c_int;
|
||||
pub fn lua_resume(L: *mut lua_State, from: *mut lua_State, narg: c_int, nres: *mut c_int) -> c_int;
|
||||
pub fn lua_status(L: *mut lua_State) -> c_int;
|
||||
pub fn lua_isyieldable(L: *mut lua_State) -> c_int;
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn lua_yield(L: *mut lua_State, n: c_int) -> c_int {
|
||||
lua_yieldk(L, n, 0, None)
|
||||
}
|
||||
|
||||
//
|
||||
// Warning-related functions
|
||||
//
|
||||
#[cfg_attr(all(windows, raw_dylib), link(name = "lua55", kind = "raw-dylib"))]
|
||||
unsafe extern "C-unwind" {
|
||||
pub fn lua_setwarnf(L: *mut lua_State, f: Option<lua_WarnFunction>, ud: *mut c_void);
|
||||
pub fn lua_warning(L: *mut lua_State, msg: *const c_char, tocont: c_int);
|
||||
}
|
||||
|
||||
//
|
||||
// Garbage-collection options
|
||||
//
|
||||
pub const LUA_GCSTOP: c_int = 0;
|
||||
pub const LUA_GCRESTART: c_int = 1;
|
||||
pub const LUA_GCCOLLECT: c_int = 2;
|
||||
pub const LUA_GCCOUNT: c_int = 3;
|
||||
pub const LUA_GCCOUNTB: c_int = 4;
|
||||
pub const LUA_GCSTEP: c_int = 5;
|
||||
pub const LUA_GCISRUNNING: c_int = 6;
|
||||
pub const LUA_GCGEN: c_int = 7;
|
||||
pub const LUA_GCINC: c_int = 8;
|
||||
pub const LUA_GCPARAM: c_int = 9;
|
||||
|
||||
// Parameters for GC generational mode
|
||||
pub const LUA_GCPMINORMUL: c_int = 0; // control minor collections
|
||||
pub const LUA_GCPMAJORMINOR: c_int = 1; // control shift major->minor
|
||||
pub const LUA_GCPMINORMAJOR: c_int = 2; // control shift minor->major
|
||||
|
||||
// Parameters for GC incremental mode
|
||||
pub const LUA_GCPPAUSE: c_int = 3; // size of pause between successive GCs
|
||||
pub const LUA_GCPSTEPMUL: c_int = 4; // GC "speed"
|
||||
pub const LUA_GCPSTEPSIZE: c_int = 5; // GC granularity
|
||||
|
||||
pub const LUA_GCPNUM: c_int = 6; // number of parameters
|
||||
|
||||
#[cfg_attr(all(windows, raw_dylib), link(name = "lua55", kind = "raw-dylib"))]
|
||||
unsafe extern "C-unwind" {
|
||||
pub fn lua_gc(L: *mut lua_State, what: c_int, ...) -> c_int;
|
||||
}
|
||||
|
||||
#[cfg_attr(all(windows, raw_dylib), link(name = "lua55", kind = "raw-dylib"))]
|
||||
unsafe extern "C-unwind" {
|
||||
//
|
||||
// Miscellaneous functions
|
||||
//
|
||||
#[link_name = "lua_error"]
|
||||
fn lua_error_(L: *mut lua_State) -> c_int;
|
||||
pub fn lua_next(L: *mut lua_State, idx: c_int) -> c_int;
|
||||
pub fn lua_concat(L: *mut lua_State, n: c_int);
|
||||
pub fn lua_len(L: *mut lua_State, idx: c_int);
|
||||
pub fn lua_numbertocstring(L: *mut lua_State, idx: c_int, buff: *mut c_char) -> c_uint;
|
||||
pub fn lua_stringtonumber(L: *mut lua_State, s: *const c_char) -> usize;
|
||||
pub fn lua_getallocf(L: *mut lua_State, ud: *mut *mut c_void) -> lua_Alloc;
|
||||
pub fn lua_setallocf(L: *mut lua_State, f: lua_Alloc, ud: *mut c_void);
|
||||
|
||||
pub fn lua_toclose(L: *mut lua_State, idx: c_int);
|
||||
pub fn lua_closeslot(L: *mut lua_State, idx: c_int);
|
||||
}
|
||||
|
||||
// lua_error does not return but is declared to return int, and Rust translates
|
||||
// ! to void which can cause link-time errors if the platform linker is aware
|
||||
// of return types and requires they match (for example: wasm does this).
|
||||
#[inline(always)]
|
||||
pub unsafe fn lua_error(L: *mut lua_State) -> ! {
|
||||
lua_error_(L);
|
||||
unreachable!();
|
||||
}
|
||||
|
||||
//
|
||||
// Some useful macros (implemented as Rust functions)
|
||||
//
|
||||
#[inline(always)]
|
||||
pub unsafe fn lua_getextraspace(L: *mut lua_State) -> *mut c_void {
|
||||
(L as *mut c_char).sub(LUA_EXTRASPACE) as *mut c_void
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn lua_tonumber(L: *mut lua_State, i: c_int) -> lua_Number {
|
||||
lua_tonumberx(L, i, ptr::null_mut())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn lua_tointeger(L: *mut lua_State, i: c_int) -> lua_Integer {
|
||||
lua_tointegerx(L, i, ptr::null_mut())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn lua_pop(L: *mut lua_State, n: c_int) {
|
||||
lua_settop(L, -n - 1)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn lua_newtable(L: *mut lua_State) {
|
||||
lua_createtable(L, 0, 0)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn lua_register(L: *mut lua_State, n: *const c_char, f: lua_CFunction) {
|
||||
lua_pushcfunction(L, f);
|
||||
lua_setglobal(L, n)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn lua_pushcfunction(L: *mut lua_State, f: lua_CFunction) {
|
||||
lua_pushcclosure(L, f, 0)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn lua_isfunction(L: *mut lua_State, n: c_int) -> c_int {
|
||||
(lua_type(L, n) == LUA_TFUNCTION) as c_int
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn lua_istable(L: *mut lua_State, n: c_int) -> c_int {
|
||||
(lua_type(L, n) == LUA_TTABLE) as c_int
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn lua_islightuserdata(L: *mut lua_State, n: c_int) -> c_int {
|
||||
(lua_type(L, n) == LUA_TLIGHTUSERDATA) as c_int
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn lua_isnil(L: *mut lua_State, n: c_int) -> c_int {
|
||||
(lua_type(L, n) == LUA_TNIL) as c_int
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn lua_isboolean(L: *mut lua_State, n: c_int) -> c_int {
|
||||
(lua_type(L, n) == LUA_TBOOLEAN) as c_int
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn lua_isthread(L: *mut lua_State, n: c_int) -> c_int {
|
||||
(lua_type(L, n) == LUA_TTHREAD) as c_int
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn lua_isnone(L: *mut lua_State, n: c_int) -> c_int {
|
||||
(lua_type(L, n) == LUA_TNONE) as c_int
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn lua_isnoneornil(L: *mut lua_State, n: c_int) -> c_int {
|
||||
(lua_type(L, n) <= 0) as c_int
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn lua_pushliteral(L: *mut lua_State, s: &'static CStr) {
|
||||
lua_pushstring(L, s.as_ptr());
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn lua_pushglobaltable(L: *mut lua_State) -> c_int {
|
||||
lua_rawgeti(L, LUA_REGISTRYINDEX, LUA_RIDX_GLOBALS)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn lua_tolightuserdata(L: *mut lua_State, idx: c_int) -> *mut c_void {
|
||||
if lua_islightuserdata(L, idx) != 0 {
|
||||
return lua_touserdata(L, idx);
|
||||
}
|
||||
ptr::null_mut()
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn lua_tostring(L: *mut lua_State, i: c_int) -> *const c_char {
|
||||
lua_tolstring(L, i, ptr::null_mut())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn lua_insert(L: *mut lua_State, idx: c_int) {
|
||||
lua_rotate(L, idx, 1)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn lua_remove(L: *mut lua_State, idx: c_int) {
|
||||
lua_rotate(L, idx, -1);
|
||||
lua_pop(L, 1)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn lua_replace(L: *mut lua_State, idx: c_int) {
|
||||
lua_copy(L, -1, idx);
|
||||
lua_pop(L, 1)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn lua_xpush(from: *mut lua_State, to: *mut lua_State, idx: c_int) {
|
||||
lua_pushvalue(from, idx);
|
||||
lua_xmove(from, to, 1);
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn lua_newuserdata(L: *mut lua_State, sz: usize) -> *mut c_void {
|
||||
lua_newuserdatauv(L, sz, 1)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn lua_getuservalue(L: *mut lua_State, idx: c_int) -> c_int {
|
||||
lua_getiuservalue(L, idx, 1)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn lua_setuservalue(L: *mut lua_State, idx: c_int) -> c_int {
|
||||
lua_setiuservalue(L, idx, 1)
|
||||
}
|
||||
|
||||
//
|
||||
// Debug API
|
||||
//
|
||||
|
||||
// Maximum size for the description of the source of a function in debug information.
|
||||
const LUA_IDSIZE: usize = 60;
|
||||
|
||||
// Event codes
|
||||
pub const LUA_HOOKCALL: c_int = 0;
|
||||
pub const LUA_HOOKRET: c_int = 1;
|
||||
pub const LUA_HOOKLINE: c_int = 2;
|
||||
pub const LUA_HOOKCOUNT: c_int = 3;
|
||||
pub const LUA_HOOKTAILCALL: c_int = 4;
|
||||
|
||||
// Event masks
|
||||
pub const LUA_MASKCALL: c_int = 1 << (LUA_HOOKCALL as usize);
|
||||
pub const LUA_MASKRET: c_int = 1 << (LUA_HOOKRET as usize);
|
||||
pub const LUA_MASKLINE: c_int = 1 << (LUA_HOOKLINE as usize);
|
||||
pub const LUA_MASKCOUNT: c_int = 1 << (LUA_HOOKCOUNT as usize);
|
||||
|
||||
/// Type for functions to be called on debug events.
|
||||
pub type lua_Hook = unsafe extern "C-unwind" fn(L: *mut lua_State, ar: *mut lua_Debug);
|
||||
|
||||
#[cfg_attr(all(windows, raw_dylib), link(name = "lua55", kind = "raw-dylib"))]
|
||||
unsafe extern "C-unwind" {
|
||||
pub fn lua_getstack(L: *mut lua_State, level: c_int, ar: *mut lua_Debug) -> c_int;
|
||||
pub fn lua_getinfo(L: *mut lua_State, what: *const c_char, ar: *mut lua_Debug) -> c_int;
|
||||
pub fn lua_getlocal(L: *mut lua_State, ar: *const lua_Debug, n: c_int) -> *const c_char;
|
||||
pub fn lua_setlocal(L: *mut lua_State, ar: *const lua_Debug, n: c_int) -> *const c_char;
|
||||
pub fn lua_getupvalue(L: *mut lua_State, funcindex: c_int, n: c_int) -> *const c_char;
|
||||
pub fn lua_setupvalue(L: *mut lua_State, funcindex: c_int, n: c_int) -> *const c_char;
|
||||
|
||||
pub fn lua_upvalueid(L: *mut lua_State, fidx: c_int, n: c_int) -> *mut c_void;
|
||||
pub fn lua_upvaluejoin(L: *mut lua_State, fidx1: c_int, n1: c_int, fidx2: c_int, n2: c_int);
|
||||
|
||||
pub fn lua_sethook(L: *mut lua_State, func: Option<lua_Hook>, mask: c_int, count: c_int);
|
||||
pub fn lua_gethook(L: *mut lua_State) -> Option<lua_Hook>;
|
||||
pub fn lua_gethookmask(L: *mut lua_State) -> c_int;
|
||||
pub fn lua_gethookcount(L: *mut lua_State) -> c_int;
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
pub struct lua_Debug {
|
||||
pub event: c_int,
|
||||
pub name: *const c_char, // (n)
|
||||
pub namewhat: *const c_char, // (n) 'global', 'local', 'field', 'method'
|
||||
pub what: *const c_char, // (S) 'Lua', 'C', 'main', 'tail'
|
||||
pub source: *const c_char, // (S)
|
||||
pub srclen: usize, // (S)
|
||||
pub currentline: c_int, // (l)
|
||||
pub linedefined: c_int, // (S)
|
||||
pub lastlinedefined: c_int, // (S)
|
||||
pub nups: c_uchar, // (u) number of upvalues
|
||||
pub nparams: c_uchar, // (u) number of parameters
|
||||
pub isvararg: c_char, // (u)
|
||||
pub extraargs: c_uchar, // (t) number of extra arguments
|
||||
pub istailcall: c_char, // (t)
|
||||
pub ftransfer: c_int, // (r) index of first value transferred
|
||||
pub ntransfer: c_int, // (r) number of transferred values
|
||||
pub short_src: [c_char; LUA_IDSIZE], // (S)
|
||||
// lua.h mentions this is for private use
|
||||
i_ci: *mut c_void,
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
//! Contains definitions from `lualib.h`.
|
||||
|
||||
use std::os::raw::{c_char, c_int};
|
||||
|
||||
use super::lua::lua_State;
|
||||
|
||||
pub const LUA_GLIBK: c_int = 1;
|
||||
|
||||
pub const LUA_LOADLIBNAME: *const c_char = cstr!("package");
|
||||
pub const LUA_LOADLIBK: c_int = LUA_GLIBK << 1;
|
||||
|
||||
pub const LUA_COLIBNAME: *const c_char = cstr!("coroutine");
|
||||
pub const LUA_COLIBK: c_int = LUA_GLIBK << 2;
|
||||
|
||||
pub const LUA_DBLIBNAME: *const c_char = cstr!("debug");
|
||||
pub const LUA_DBLIBK: c_int = LUA_GLIBK << 3;
|
||||
|
||||
pub const LUA_IOLIBNAME: *const c_char = cstr!("io");
|
||||
pub const LUA_IOLIBK: c_int = LUA_GLIBK << 4;
|
||||
|
||||
pub const LUA_MATHLIBNAME: *const c_char = cstr!("math");
|
||||
pub const LUA_MATHLIBK: c_int = LUA_GLIBK << 5;
|
||||
|
||||
pub const LUA_OSLIBNAME: *const c_char = cstr!("os");
|
||||
pub const LUA_OSLIBK: c_int = LUA_GLIBK << 6;
|
||||
|
||||
pub const LUA_STRLIBNAME: *const c_char = cstr!("string");
|
||||
pub const LUA_STRLIBK: c_int = LUA_GLIBK << 7;
|
||||
|
||||
pub const LUA_TABLIBNAME: *const c_char = cstr!("table");
|
||||
pub const LUA_TABLIBK: c_int = LUA_GLIBK << 8;
|
||||
|
||||
pub const LUA_UTF8LIBNAME: *const c_char = cstr!("utf8");
|
||||
pub const LUA_UTF8LIBK: c_int = LUA_GLIBK << 9;
|
||||
|
||||
#[cfg_attr(all(windows, raw_dylib), link(name = "lua55", kind = "raw-dylib"))]
|
||||
unsafe extern "C-unwind" {
|
||||
pub fn luaopen_base(L: *mut lua_State) -> c_int;
|
||||
pub fn luaopen_package(L: *mut lua_State) -> c_int;
|
||||
pub fn luaopen_coroutine(L: *mut lua_State) -> c_int;
|
||||
pub fn luaopen_debug(L: *mut lua_State) -> c_int;
|
||||
pub fn luaopen_io(L: *mut lua_State) -> c_int;
|
||||
pub fn luaopen_math(L: *mut lua_State) -> c_int;
|
||||
pub fn luaopen_os(L: *mut lua_State) -> c_int;
|
||||
pub fn luaopen_string(L: *mut lua_State) -> c_int;
|
||||
pub fn luaopen_table(L: *mut lua_State) -> c_int;
|
||||
pub fn luaopen_utf8(L: *mut lua_State) -> c_int;
|
||||
|
||||
// open all builtin libraries
|
||||
pub fn luaL_openselectedlibs(L: *mut lua_State, load: c_int, preload: c_int);
|
||||
}
|
||||
|
||||
pub unsafe fn luaL_openlibs(L: *mut lua_State) {
|
||||
luaL_openselectedlibs(L, !0, 0);
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
//! Low level bindings to Lua 5.5.
|
||||
|
||||
pub use lauxlib::*;
|
||||
pub use lua::*;
|
||||
pub use lualib::*;
|
||||
|
||||
pub mod lauxlib;
|
||||
pub mod lua;
|
||||
pub mod lualib;
|
||||
+150
-94
@@ -1,16 +1,17 @@
|
||||
//! MLua compatibility layer for Roblox Luau.
|
||||
//! MLua compatibility layer for Luau.
|
||||
//!
|
||||
//! Based on github.com/keplerproject/lua-compat-5.3
|
||||
|
||||
use std::ffi::CStr;
|
||||
use std::mem;
|
||||
use std::os::raw::{c_char, c_int, c_void};
|
||||
use std::ptr;
|
||||
use std::{mem, ptr};
|
||||
|
||||
use super::lauxlib::*;
|
||||
use super::lua::*;
|
||||
use super::luacode::*;
|
||||
|
||||
pub const LUA_RESUMEERROR: c_int = -1;
|
||||
|
||||
unsafe fn compat53_reverse(L: *mut lua_State, mut a: c_int, mut b: c_int) {
|
||||
while a < b {
|
||||
lua_pushvalue(L, a);
|
||||
@@ -22,8 +23,8 @@ unsafe fn compat53_reverse(L: *mut lua_State, mut a: c_int, mut b: c_int) {
|
||||
}
|
||||
}
|
||||
|
||||
const COMPAT53_LEVELS1: c_int = 12; // size of the first part of the stack
|
||||
const COMPAT53_LEVELS2: c_int = 10; // size of the second part of the stack
|
||||
const COMPAT53_LEVELS1: c_int = 10; // size of the first part of the stack
|
||||
const COMPAT53_LEVELS2: c_int = 11; // size of the second part of the stack
|
||||
|
||||
unsafe fn compat53_findfield(L: *mut lua_State, objidx: c_int, level: c_int) -> c_int {
|
||||
if level == 0 || lua_istable(L, -1) == 0 {
|
||||
@@ -40,11 +41,10 @@ unsafe fn compat53_findfield(L: *mut lua_State, objidx: c_int, level: c_int) ->
|
||||
lua_pop(L, 1); // remove value (but keep name)
|
||||
return 1;
|
||||
} else if compat53_findfield(L, objidx, level - 1) != 0 {
|
||||
// try recursively
|
||||
lua_remove(L, -2); // remove table (but keep name)
|
||||
lua_pushliteral(L, ".");
|
||||
lua_insert(L, -2); // place '.' between the two names
|
||||
lua_concat(L, 3);
|
||||
// stack: lib_name, lib_table, field_name (top)
|
||||
lua_pushliteral(L, c"."); // place '.' between the two names
|
||||
lua_replace(L, -3); // (in the slot occupied by table)
|
||||
lua_concat(L, 3); // lib_name.field_name
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
@@ -55,16 +55,23 @@ unsafe fn compat53_findfield(L: *mut lua_State, objidx: c_int, level: c_int) ->
|
||||
|
||||
unsafe fn compat53_pushglobalfuncname(
|
||||
L: *mut lua_State,
|
||||
L1: *mut lua_State,
|
||||
level: c_int,
|
||||
ar: *mut lua_Debug,
|
||||
) -> c_int {
|
||||
let top = lua_gettop(L);
|
||||
// push function
|
||||
lua_getinfo(L, level, cstr!("f"), ar);
|
||||
lua_getinfo(L1, level, cstr!("f"), ar); // push function
|
||||
lua_xmove(L1, L, 1); // and move onto L
|
||||
lua_pushvalue(L, LUA_GLOBALSINDEX);
|
||||
luaL_checkstack(L, 6, cstr!("not enough stack")); // slots for 'findfield'
|
||||
if compat53_findfield(L, top + 1, 2) != 0 {
|
||||
let name = lua_tostring(L, -1);
|
||||
if CStr::from_ptr(name).to_bytes().starts_with(b"_G.") {
|
||||
lua_pushstring(L, name.add(3)); // push name without prefix
|
||||
lua_remove(L, -2); // remove original name
|
||||
}
|
||||
lua_copy(L, -1, top + 1); // move name to proper place
|
||||
lua_pop(L, 2); // remove pushed values
|
||||
lua_settop(L, top + 1); // remove pushed values
|
||||
1
|
||||
} else {
|
||||
lua_settop(L, top); // remove function and global table
|
||||
@@ -72,15 +79,18 @@ unsafe fn compat53_pushglobalfuncname(
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn compat53_pushfuncname(L: *mut lua_State, level: c_int, ar: *mut lua_Debug) {
|
||||
unsafe fn compat53_pushfuncname(L: *mut lua_State, L1: *mut lua_State, level: c_int, ar: *mut lua_Debug) {
|
||||
if !(*ar).name.is_null() {
|
||||
// is there a name?
|
||||
lua_pushfstring(L, cstr!("function '%s'"), (*ar).name);
|
||||
} else if compat53_pushglobalfuncname(L, level, ar) != 0 {
|
||||
} else if compat53_pushglobalfuncname(L, L1, level, ar) != 0 {
|
||||
lua_pushfstring(L, cstr!("function '%s'"), lua_tostring(L, -1));
|
||||
lua_remove(L, -2); // remove name
|
||||
} else if *(*ar).what != b'C' as c_char {
|
||||
// for Lua functions, use <file:line>
|
||||
lua_pushfstring(L, cstr!("function <%s:%d>"), (*ar).short_src, (*ar).linedefined);
|
||||
} else {
|
||||
lua_pushliteral(L, "?");
|
||||
lua_pushliteral(L, c"?");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -113,7 +123,7 @@ pub unsafe fn lua_rotate(L: *mut lua_State, mut idx: c_int, mut n: c_int) {
|
||||
#[inline(always)]
|
||||
pub unsafe fn lua_copy(L: *mut lua_State, fromidx: c_int, toidx: c_int) {
|
||||
let abs_to = lua_absindex(L, toidx);
|
||||
luaL_checkstack(L, 1, cstr!("not enough stack slots"));
|
||||
luaL_checkstack(L, 1, cstr!("not enough stack slots available"));
|
||||
lua_pushvalue(L, fromidx);
|
||||
lua_replace(L, abs_to);
|
||||
}
|
||||
@@ -123,13 +133,19 @@ pub unsafe fn lua_isinteger(L: *mut lua_State, idx: c_int) -> c_int {
|
||||
if lua_type(L, idx) == LUA_TNUMBER {
|
||||
let n = lua_tonumber(L, idx);
|
||||
let i = lua_tointeger(L, idx);
|
||||
if (n - i as lua_Number).abs() < lua_Number::EPSILON {
|
||||
// Lua 5.3+ returns "false" for `-0.0`
|
||||
if n.to_bits() == (i as lua_Number).to_bits() {
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
0
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn lua_pushinteger(L: *mut lua_State, i: lua_Integer) {
|
||||
lua_pushnumber(L, i as lua_Number);
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn lua_tointeger(L: *mut lua_State, i: c_int) -> lua_Integer {
|
||||
lua_tointegerx(L, i, ptr::null_mut())
|
||||
@@ -181,21 +197,20 @@ pub unsafe fn lua_geti(L: *mut lua_State, mut idx: c_int, n: lua_Integer) -> c_i
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn lua_rawgeti(L: *mut lua_State, idx: c_int, n: lua_Integer) -> c_int {
|
||||
let n = n.try_into().expect("cannot convert index from lua_Integer");
|
||||
lua_rawgeti_(L, idx, n)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn lua_rawgetp(L: *mut lua_State, idx: c_int, p: *const c_void) -> c_int {
|
||||
let abs_i = lua_absindex(L, idx);
|
||||
lua_pushlightuserdata(L, p as *mut c_void);
|
||||
lua_rawget(L, abs_i)
|
||||
lua_rawgetptagged(L, idx, p, 0)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn lua_getuservalue(L: *mut lua_State, mut idx: c_int) -> c_int {
|
||||
luaL_checkstack(L, 2, cstr!("not enough stack slots available"));
|
||||
idx = lua_absindex(L, idx);
|
||||
lua_pushliteral(L, "__mlua_uservalues");
|
||||
lua_pushliteral(L, c"__mlua_uservalues");
|
||||
if lua_rawget(L, LUA_REGISTRYINDEX) != LUA_TTABLE {
|
||||
return LUA_TNIL;
|
||||
}
|
||||
@@ -216,29 +231,26 @@ pub unsafe fn lua_seti(L: *mut lua_State, mut idx: c_int, n: lua_Integer) {
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn lua_rawseti(L: *mut lua_State, idx: c_int, n: lua_Integer) {
|
||||
let n = n.try_into().expect("cannot convert index from lua_Integer");
|
||||
lua_rawseti_(L, idx, n)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn lua_rawsetp(L: *mut lua_State, idx: c_int, p: *const c_void) {
|
||||
let abs_i = lua_absindex(L, idx);
|
||||
luaL_checkstack(L, 1, cstr!("not enough stack slots"));
|
||||
lua_pushlightuserdata(L, p as *mut c_void);
|
||||
lua_insert(L, -2);
|
||||
lua_rawset(L, abs_i);
|
||||
lua_rawsetptagged(L, idx, p, 0)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn lua_setuservalue(L: *mut lua_State, mut idx: c_int) {
|
||||
luaL_checkstack(L, 4, cstr!("not enough stack slots available"));
|
||||
idx = lua_absindex(L, idx);
|
||||
lua_pushliteral(L, "__mlua_uservalues");
|
||||
lua_pushliteral(L, c"__mlua_uservalues");
|
||||
lua_pushvalue(L, -1);
|
||||
if lua_rawget(L, LUA_REGISTRYINDEX) != LUA_TTABLE {
|
||||
lua_pop(L, 1);
|
||||
lua_createtable(L, 0, 2); // main table
|
||||
lua_createtable(L, 0, 1); // metatable
|
||||
lua_pushliteral(L, "k");
|
||||
lua_pushliteral(L, c"k");
|
||||
lua_setfield(L, -2, cstr!("__mode"));
|
||||
lua_setmetatable(L, -2);
|
||||
lua_pushvalue(L, -2);
|
||||
@@ -281,12 +293,7 @@ pub unsafe fn lua_pushglobaltable(L: *mut lua_State) {
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn lua_resume(
|
||||
L: *mut lua_State,
|
||||
from: *mut lua_State,
|
||||
narg: c_int,
|
||||
nres: *mut c_int,
|
||||
) -> c_int {
|
||||
pub unsafe fn lua_resume(L: *mut lua_State, from: *mut lua_State, narg: c_int, nres: *mut c_int) -> c_int {
|
||||
let ret = lua_resume_(L, from, narg);
|
||||
if (ret == LUA_OK || ret == LUA_YIELD) && !(nres.is_null()) {
|
||||
*nres = lua_gettop(L);
|
||||
@@ -294,6 +301,19 @@ pub unsafe fn lua_resume(
|
||||
ret
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn lua_resumex(L: *mut lua_State, from: *mut lua_State, narg: c_int, nres: *mut c_int) -> c_int {
|
||||
let ret = if narg == LUA_RESUMEERROR {
|
||||
lua_resumeerror(L, from)
|
||||
} else {
|
||||
lua_resume_(L, from, narg)
|
||||
};
|
||||
if (ret == LUA_OK || ret == LUA_YIELD) && !(nres.is_null()) {
|
||||
*nres = lua_gettop(L);
|
||||
}
|
||||
ret
|
||||
}
|
||||
|
||||
//
|
||||
// lauxlib ported functions
|
||||
//
|
||||
@@ -304,12 +324,30 @@ pub unsafe fn luaL_checkstack(L: *mut lua_State, sz: c_int, msg: *const c_char)
|
||||
if !msg.is_null() {
|
||||
luaL_error(L, cstr!("stack overflow (%s)"), msg);
|
||||
} else {
|
||||
lua_pushliteral(L, "stack overflow");
|
||||
lua_pushliteral(L, c"stack overflow");
|
||||
lua_error(L);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn luaL_checkinteger(L: *mut lua_State, narg: c_int) -> lua_Integer {
|
||||
let mut isnum = 0;
|
||||
let int = lua_tointegerx(L, narg, &mut isnum);
|
||||
if isnum == 0 {
|
||||
luaL_typeerror(L, narg, lua_typename(L, LUA_TNUMBER));
|
||||
}
|
||||
int
|
||||
}
|
||||
|
||||
pub unsafe fn luaL_optinteger(L: *mut lua_State, narg: c_int, def: lua_Integer) -> lua_Integer {
|
||||
if lua_isnoneornil(L, narg) != 0 {
|
||||
def
|
||||
} else {
|
||||
luaL_checkinteger(L, narg)
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn luaL_getmetafield(L: *mut lua_State, obj: c_int, e: *const c_char) -> c_int {
|
||||
if luaL_getmetafield_(L, obj, e) != 0 {
|
||||
@@ -330,50 +368,72 @@ pub unsafe fn luaL_newmetatable(L: *mut lua_State, tname: *const c_char) -> c_in
|
||||
}
|
||||
}
|
||||
|
||||
pub unsafe fn luaL_loadbufferx(
|
||||
pub unsafe fn luaL_loadbufferenv(
|
||||
L: *mut lua_State,
|
||||
data: *const c_char,
|
||||
mut size: usize,
|
||||
name: *const c_char,
|
||||
mode: *const c_char,
|
||||
mut env: c_int,
|
||||
) -> c_int {
|
||||
extern "C" {
|
||||
unsafe extern "C" {
|
||||
fn free(p: *mut c_void);
|
||||
}
|
||||
|
||||
unsafe extern "C" fn data_dtor(_: *mut lua_State, data: *mut c_void) {
|
||||
free(*(data as *mut *mut c_char) as *mut c_void);
|
||||
}
|
||||
|
||||
let chunk_is_text = size == 0 || (*data as u8) >= b'\t';
|
||||
if !mode.is_null() {
|
||||
let modeb = CStr::from_ptr(mode).to_bytes();
|
||||
if !chunk_is_text && !modeb.contains(&b'b') {
|
||||
lua_pushfstring(
|
||||
L,
|
||||
cstr!("attempt to load a binary chunk (mode is '%s')"),
|
||||
mode,
|
||||
);
|
||||
lua_pushfstring(L, cstr!("attempt to load a binary chunk (mode is '%s')"), mode);
|
||||
return LUA_ERRSYNTAX;
|
||||
} else if chunk_is_text && !modeb.contains(&b't') {
|
||||
lua_pushfstring(
|
||||
L,
|
||||
cstr!("attempt to load a text chunk (mode is '%s')"),
|
||||
mode,
|
||||
);
|
||||
lua_pushfstring(L, cstr!("attempt to load a text chunk (mode is '%s')"), mode);
|
||||
return LUA_ERRSYNTAX;
|
||||
}
|
||||
}
|
||||
|
||||
if chunk_is_text {
|
||||
let data = luau_compile_(data, size, ptr::null_mut(), &mut size);
|
||||
let ok = luau_load(L, name, data, size, 0) == 0;
|
||||
free(data as *mut c_void);
|
||||
if !ok {
|
||||
return LUA_ERRSYNTAX;
|
||||
let status = if chunk_is_text {
|
||||
if env < 0 {
|
||||
env -= 1;
|
||||
}
|
||||
let data_ud = lua_newuserdatadtor(L, mem::size_of::<*mut c_char>(), data_dtor) as *mut *mut c_char;
|
||||
let data = luau_compile_(data, size, ptr::null_mut(), &mut size);
|
||||
ptr::write(data_ud, data);
|
||||
// By deferring the `free(data)` to the userdata destructor, we ensure that
|
||||
// even if `luau_load` throws an error, the `data` is still released.
|
||||
let status = luau_load(L, name, data, size, env);
|
||||
lua_replace(L, -2); // replace data with the result
|
||||
status
|
||||
} else {
|
||||
luau_load(L, name, data, size, env)
|
||||
};
|
||||
|
||||
if status != 0 {
|
||||
if lua_isstring(L, -1) != 0 && CStr::from_ptr(lua_tostring(L, -1)) == c"not enough memory" {
|
||||
// A case for Luau >= 0.679
|
||||
return LUA_ERRMEM;
|
||||
}
|
||||
} else if luau_load(L, name, data, size, 0) != 0 {
|
||||
return LUA_ERRSYNTAX;
|
||||
}
|
||||
|
||||
LUA_OK
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn luaL_loadbufferx(
|
||||
L: *mut lua_State,
|
||||
data: *const c_char,
|
||||
size: usize,
|
||||
name: *const c_char,
|
||||
mode: *const c_char,
|
||||
) -> c_int {
|
||||
luaL_loadbufferenv(L, data, size, name, mode, 0)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn luaL_loadbuffer(
|
||||
L: *mut lua_State,
|
||||
@@ -381,13 +441,13 @@ pub unsafe fn luaL_loadbuffer(
|
||||
size: usize,
|
||||
name: *const c_char,
|
||||
) -> c_int {
|
||||
luaL_loadbufferx(L, data, size, name, ptr::null())
|
||||
luaL_loadbufferenv(L, data, size, name, ptr::null(), 0)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn luaL_len(L: *mut lua_State, idx: c_int) -> lua_Integer {
|
||||
let mut isnum = 0;
|
||||
luaL_checkstack(L, 1, cstr!("not enough stack slots"));
|
||||
luaL_checkstack(L, 1, cstr!("not enough stack slots available"));
|
||||
lua_len(L, idx);
|
||||
let res = lua_tointegerx(L, -1, &mut isnum);
|
||||
lua_pop(L, 1);
|
||||
@@ -397,43 +457,44 @@ pub unsafe fn luaL_len(L: *mut lua_State, idx: c_int) -> lua_Integer {
|
||||
res
|
||||
}
|
||||
|
||||
pub unsafe fn luaL_traceback(
|
||||
L: *mut lua_State,
|
||||
L1: *mut lua_State,
|
||||
msg: *const c_char,
|
||||
mut level: c_int,
|
||||
) {
|
||||
pub unsafe fn luaL_traceback(L: *mut lua_State, L1: *mut lua_State, msg: *const c_char, mut level: c_int) {
|
||||
let mut ar: lua_Debug = mem::zeroed();
|
||||
let top = lua_gettop(L);
|
||||
let numlevels = lua_stackdepth(L);
|
||||
let mark = if numlevels > COMPAT53_LEVELS1 + COMPAT53_LEVELS2 {
|
||||
COMPAT53_LEVELS1
|
||||
} else {
|
||||
0
|
||||
};
|
||||
#[rustfmt::skip]
|
||||
let mut limit = if numlevels - level > COMPAT53_LEVELS1 + COMPAT53_LEVELS2 { COMPAT53_LEVELS1 } else { -1 };
|
||||
|
||||
let mut buf: luaL_Strbuf = mem::zeroed();
|
||||
luaL_buffinit(L, &mut buf);
|
||||
|
||||
if !msg.is_null() {
|
||||
lua_pushfstring(L, cstr!("%s\n"), msg);
|
||||
luaL_addstring(&mut buf, msg);
|
||||
luaL_addstring(&mut buf, cstr!("\n"));
|
||||
}
|
||||
lua_pushliteral(L, "stack traceback:");
|
||||
while lua_getinfo(L1, level, cstr!(""), &mut ar) != 0 {
|
||||
if level + 1 == mark {
|
||||
luaL_addstring(&mut buf, cstr!("stack traceback:"));
|
||||
while lua_getinfo(L1, level, cstr!("sln"), &mut ar) != 0 {
|
||||
if limit == 0 {
|
||||
// too many levels?
|
||||
lua_pushliteral(L, "\n\t..."); // add a '...'
|
||||
level = numlevels - COMPAT53_LEVELS2; // and skip to last ones
|
||||
let n = numlevels - level - COMPAT53_LEVELS2;
|
||||
// add warning about skip ("n + 1" because we skip current level too)
|
||||
lua_pushfstring(L, cstr!("\n\t...\t(skipping %d levels)"), n + 1);
|
||||
luaL_addvalue(&mut buf);
|
||||
level += n; // and skip to last levels
|
||||
} else {
|
||||
lua_getinfo(L1, level, cstr!("sln"), &mut ar);
|
||||
lua_pushfstring(L, cstr!("\n\t%s:"), ar.short_src);
|
||||
luaL_addstring(&mut buf, cstr!("\n\t"));
|
||||
luaL_addstring(&mut buf, ar.short_src);
|
||||
luaL_addstring(&mut buf, cstr!(":"));
|
||||
if ar.currentline > 0 {
|
||||
lua_pushfstring(L, cstr!("%d:"), ar.currentline);
|
||||
luaL_addunsigned(&mut buf, ar.currentline as _);
|
||||
luaL_addstring(&mut buf, cstr!(":"));
|
||||
}
|
||||
lua_pushliteral(L, " in ");
|
||||
compat53_pushfuncname(L, level, &mut ar);
|
||||
lua_concat(L, lua_gettop(L) - top);
|
||||
luaL_addstring(&mut buf, cstr!(" in "));
|
||||
compat53_pushfuncname(L, L1, level, &mut ar);
|
||||
luaL_addvalue(&mut buf);
|
||||
}
|
||||
level += 1;
|
||||
limit -= 1;
|
||||
}
|
||||
lua_concat(L, lua_gettop(L) - top);
|
||||
luaL_pushresult(&mut buf);
|
||||
}
|
||||
|
||||
pub unsafe fn luaL_tolstring(L: *mut lua_State, mut idx: c_int, len: *mut usize) -> *const c_char {
|
||||
@@ -441,16 +502,16 @@ pub unsafe fn luaL_tolstring(L: *mut lua_State, mut idx: c_int, len: *mut usize)
|
||||
if luaL_callmeta(L, idx, cstr!("__tostring")) == 0 {
|
||||
match lua_type(L, idx) {
|
||||
LUA_TNIL => {
|
||||
lua_pushliteral(L, "nil");
|
||||
lua_pushliteral(L, c"nil");
|
||||
}
|
||||
LUA_TSTRING | LUA_TNUMBER => {
|
||||
lua_pushvalue(L, idx);
|
||||
}
|
||||
LUA_TBOOLEAN => {
|
||||
if lua_toboolean(L, idx) == 0 {
|
||||
lua_pushliteral(L, "false");
|
||||
lua_pushliteral(L, c"false");
|
||||
} else {
|
||||
lua_pushliteral(L, "true");
|
||||
lua_pushliteral(L, c"true");
|
||||
}
|
||||
}
|
||||
t => {
|
||||
@@ -474,14 +535,14 @@ pub unsafe fn luaL_tolstring(L: *mut lua_State, mut idx: c_int, len: *mut usize)
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn luaL_setmetatable(L: *mut lua_State, tname: *const c_char) {
|
||||
luaL_checkstack(L, 1, cstr!("not enough stack slots"));
|
||||
luaL_checkstack(L, 1, cstr!("not enough stack slots available"));
|
||||
luaL_getmetatable(L, tname);
|
||||
lua_setmetatable(L, -2);
|
||||
}
|
||||
|
||||
pub unsafe fn luaL_getsubtable(L: *mut lua_State, idx: c_int, fname: *const c_char) -> c_int {
|
||||
let abs_i = lua_absindex(L, idx);
|
||||
luaL_checkstack(L, 3, cstr!("not enough stack slots"));
|
||||
luaL_checkstack(L, 3, cstr!("not enough stack slots available"));
|
||||
lua_pushstring_(L, fname);
|
||||
if lua_gettable(L, abs_i) == LUA_TTABLE {
|
||||
return 1;
|
||||
@@ -494,14 +555,9 @@ pub unsafe fn luaL_getsubtable(L: *mut lua_State, idx: c_int, fname: *const c_ch
|
||||
0
|
||||
}
|
||||
|
||||
pub unsafe fn luaL_requiref(
|
||||
L: *mut lua_State,
|
||||
modname: *const c_char,
|
||||
openf: lua_CFunction,
|
||||
glb: c_int,
|
||||
) {
|
||||
pub unsafe fn luaL_requiref(L: *mut lua_State, modname: *const c_char, openf: lua_CFunction, glb: c_int) {
|
||||
luaL_checkstack(L, 3, cstr!("not enough stack slots available"));
|
||||
luaL_getsubtable(L, LUA_REGISTRYINDEX, cstr!("_LOADED"));
|
||||
luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE);
|
||||
if lua_getfield(L, -1, modname) == LUA_TNIL {
|
||||
lua_pop(L, 1);
|
||||
lua_pushcfunction(L, openf);
|
||||
|
||||
@@ -3,9 +3,10 @@
|
||||
use std::os::raw::{c_char, c_float, c_int, c_void};
|
||||
use std::ptr;
|
||||
|
||||
use super::lua::{
|
||||
self, lua_CFunction, lua_Integer, lua_Number, lua_State, lua_Unsigned, LUA_REGISTRYINDEX,
|
||||
};
|
||||
use super::lua::{self, LUA_REGISTRYINDEX, lua_CFunction, lua_Number, lua_State, lua_Unsigned};
|
||||
|
||||
// Key, in the registry, for table of loaded modules
|
||||
pub const LUA_LOADED_TABLE: *const c_char = cstr!("_LOADED");
|
||||
|
||||
#[repr(C)]
|
||||
pub struct luaL_Reg {
|
||||
@@ -13,7 +14,7 @@ pub struct luaL_Reg {
|
||||
pub func: lua_CFunction,
|
||||
}
|
||||
|
||||
extern "C-unwind" {
|
||||
unsafe extern "C-unwind" {
|
||||
pub fn luaL_register(L: *mut lua_State, libname: *const c_char, l: *const luaL_Reg);
|
||||
#[link_name = "luaL_getmetafield"]
|
||||
pub fn luaL_getmetafield_(L: *mut lua_State, obj: c_int, e: *const c_char) -> c_int;
|
||||
@@ -35,8 +36,12 @@ extern "C-unwind" {
|
||||
pub fn luaL_checkboolean(L: *mut lua_State, narg: c_int) -> c_int;
|
||||
pub fn luaL_optboolean(L: *mut lua_State, narg: c_int, def: c_int) -> c_int;
|
||||
|
||||
pub fn luaL_checkinteger(L: *mut lua_State, narg: c_int) -> lua_Integer;
|
||||
pub fn luaL_optinteger(L: *mut lua_State, narg: c_int, def: lua_Integer) -> lua_Integer;
|
||||
#[link_name = "luaL_checkinteger"]
|
||||
pub fn luaL_checkinteger_(L: *mut lua_State, narg: c_int) -> c_int;
|
||||
pub fn luaL_checkinteger64(L: *mut lua_State, narg: c_int) -> i64;
|
||||
#[link_name = "luaL_optinteger"]
|
||||
pub fn luaL_optinteger_(L: *mut lua_State, narg: c_int, def: c_int) -> c_int;
|
||||
pub fn luaL_optinteger64(L: *mut lua_State, narg: c_int, def: i64) -> i64;
|
||||
pub fn luaL_checkunsigned(L: *mut lua_State, narg: c_int) -> lua_Unsigned;
|
||||
pub fn luaL_optunsigned(L: *mut lua_State, narg: c_int, def: lua_Unsigned) -> lua_Unsigned;
|
||||
|
||||
@@ -71,10 +76,20 @@ extern "C-unwind" {
|
||||
|
||||
pub fn luaL_newstate() -> *mut lua_State;
|
||||
|
||||
// TODO: luaL_findtable
|
||||
pub fn luaL_findtable(
|
||||
L: *mut lua_State,
|
||||
idx: c_int,
|
||||
fname: *const c_char,
|
||||
szhint: c_int,
|
||||
) -> *const c_char;
|
||||
|
||||
pub fn luaL_typename(L: *mut lua_State, idx: c_int) -> *const c_char;
|
||||
|
||||
pub fn luaL_callyieldable(L: *mut lua_State, nargs: c_int, nresults: c_int) -> c_int;
|
||||
|
||||
#[link_name = "luaL_traceback"]
|
||||
pub fn luaL_traceback_(L: *mut lua_State, L1: *mut lua_State, msg: *const c_char, level: c_int);
|
||||
|
||||
// sandbox libraries and globals
|
||||
#[link_name = "luaL_sandbox"]
|
||||
pub fn luaL_sandbox_(L: *mut lua_State);
|
||||
@@ -109,7 +124,19 @@ pub unsafe fn luaL_optstring(L: *mut lua_State, n: c_int, d: *const c_char) -> *
|
||||
luaL_optlstring(L, n, d, ptr::null_mut())
|
||||
}
|
||||
|
||||
// TODO: luaL_opt
|
||||
#[inline(always)]
|
||||
pub unsafe fn luaL_opt<T>(
|
||||
L: *mut lua_State,
|
||||
f: unsafe extern "C-unwind" fn(*mut lua_State, c_int) -> T,
|
||||
n: c_int,
|
||||
d: T,
|
||||
) -> T {
|
||||
if lua::lua_isnoneornil(L, n) != 0 {
|
||||
d
|
||||
} else {
|
||||
f(L, n)
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn luaL_getmetatable(L: *mut lua_State, n: *const c_char) -> c_int {
|
||||
@@ -143,7 +170,7 @@ pub unsafe fn luaL_sandbox(L: *mut lua_State, enabled: c_int) {
|
||||
}
|
||||
|
||||
// set all builtin metatables to read-only
|
||||
lua_pushliteral(L, "");
|
||||
lua_pushliteral(L, c"");
|
||||
if lua_getmetatable(L, -1) != 0 {
|
||||
lua_setreadonly(L, -1, enabled);
|
||||
lua_pop(L, 2);
|
||||
@@ -175,7 +202,7 @@ pub struct luaL_Strbuf {
|
||||
// For compatibility
|
||||
pub type luaL_Buffer = luaL_Strbuf;
|
||||
|
||||
extern "C-unwind" {
|
||||
unsafe extern "C-unwind" {
|
||||
pub fn luaL_buffinit(L: *mut lua_State, B: *mut luaL_Strbuf);
|
||||
pub fn luaL_buffinitsize(L: *mut lua_State, B: *mut luaL_Strbuf, size: usize) -> *mut c_char;
|
||||
pub fn luaL_prepbuffsize(B: *mut luaL_Strbuf, size: usize) -> *mut c_char;
|
||||
@@ -202,3 +229,18 @@ pub unsafe fn luaL_addstring(B: *mut luaL_Strbuf, s: *const c_char) {
|
||||
}
|
||||
luaL_addlstring(B, s, len);
|
||||
}
|
||||
|
||||
pub unsafe fn luaL_addunsigned(B: *mut luaL_Strbuf, mut n: lua_Unsigned) {
|
||||
let mut buf: [c_char; 32] = [0; 32];
|
||||
let mut i = 32;
|
||||
loop {
|
||||
i -= 1;
|
||||
let digit = (n % 10) as u8;
|
||||
buf[i] = (b'0' + digit) as c_char;
|
||||
n /= 10;
|
||||
if n == 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
luaL_addlstring(B, buf.as_ptr().add(i), 32 - i);
|
||||
}
|
||||
|
||||
+112
-69
@@ -1,5 +1,6 @@
|
||||
//! Contains definitions from `lua.h`.
|
||||
|
||||
use std::ffi::CStr;
|
||||
use std::marker::{PhantomData, PhantomPinned};
|
||||
use std::os::raw::{c_char, c_double, c_float, c_int, c_uint, c_void};
|
||||
use std::{mem, ptr};
|
||||
@@ -11,10 +12,10 @@ pub const LUA_MULTRET: c_int = -1;
|
||||
const LUAI_MAXCSTACK: c_int = 1000000;
|
||||
|
||||
// Number of valid Lua userdata tags
|
||||
const LUA_UTAG_LIMIT: c_int = 128;
|
||||
pub const LUA_UTAG_LIMIT: c_int = 128;
|
||||
|
||||
// Number of valid Lua lightuserdata tags
|
||||
const LUA_LUTAG_LIMIT: c_int = 128;
|
||||
pub const LUA_LUTAG_LIMIT: c_int = 128;
|
||||
|
||||
//
|
||||
// Pseudo-indices
|
||||
@@ -36,6 +37,16 @@ pub const LUA_ERRRUN: c_int = 2;
|
||||
pub const LUA_ERRSYNTAX: c_int = 3;
|
||||
pub const LUA_ERRMEM: c_int = 4;
|
||||
pub const LUA_ERRERR: c_int = 5;
|
||||
pub const LUA_BREAK: c_int = 6; // yielded for a debug breakpoint
|
||||
|
||||
//
|
||||
// Coroutine status
|
||||
//
|
||||
pub const LUA_CORUN: c_int = 0; // running
|
||||
pub const LUA_COSUS: c_int = 1; // suspended
|
||||
pub const LUA_CONOR: c_int = 2; // 'normal' (it resumed another coroutine)
|
||||
pub const LUA_COFIN: c_int = 3; // finished
|
||||
pub const LUA_COERR: c_int = 4; // finished with error
|
||||
|
||||
/// A raw Lua state associated with a thread.
|
||||
#[repr(C)]
|
||||
@@ -54,14 +65,15 @@ pub const LUA_TBOOLEAN: c_int = 1;
|
||||
|
||||
pub const LUA_TLIGHTUSERDATA: c_int = 2;
|
||||
pub const LUA_TNUMBER: c_int = 3;
|
||||
pub const LUA_TVECTOR: c_int = 4;
|
||||
pub const LUA_TINTEGER: c_int = 4;
|
||||
pub const LUA_TVECTOR: c_int = 5;
|
||||
|
||||
pub const LUA_TSTRING: c_int = 5;
|
||||
pub const LUA_TTABLE: c_int = 6;
|
||||
pub const LUA_TFUNCTION: c_int = 7;
|
||||
pub const LUA_TUSERDATA: c_int = 8;
|
||||
pub const LUA_TTHREAD: c_int = 9;
|
||||
pub const LUA_TBUFFER: c_int = 10;
|
||||
pub const LUA_TSTRING: c_int = 6;
|
||||
pub const LUA_TTABLE: c_int = 7;
|
||||
pub const LUA_TFUNCTION: c_int = 8;
|
||||
pub const LUA_TUSERDATA: c_int = 9;
|
||||
pub const LUA_TTHREAD: c_int = 10;
|
||||
pub const LUA_TBUFFER: c_int = 11;
|
||||
|
||||
/// Guaranteed number of Lua stack slots available to a C function.
|
||||
pub const LUA_MINSTACK: c_int = 20;
|
||||
@@ -69,8 +81,11 @@ pub const LUA_MINSTACK: c_int = 20;
|
||||
/// A Lua number, usually equivalent to `f64`.
|
||||
pub type lua_Number = c_double;
|
||||
|
||||
/// A Lua integer, equivalent to `i32`.
|
||||
pub type lua_Integer = c_int;
|
||||
/// A Lua integer, usually equivalent to `i64`
|
||||
#[cfg(target_pointer_width = "32")]
|
||||
pub type lua_Integer = i32;
|
||||
#[cfg(target_pointer_width = "64")]
|
||||
pub type lua_Integer = i64;
|
||||
|
||||
/// A Lua unsigned integer, equivalent to `u32`.
|
||||
pub type lua_Unsigned = c_uint;
|
||||
@@ -79,24 +94,19 @@ pub type lua_Unsigned = c_uint;
|
||||
pub type lua_CFunction = unsafe extern "C-unwind" fn(L: *mut lua_State) -> c_int;
|
||||
pub type lua_Continuation = unsafe extern "C-unwind" fn(L: *mut lua_State, status: c_int) -> c_int;
|
||||
|
||||
/// Type for userdata destructor functions.
|
||||
pub type lua_Udestructor = unsafe extern "C-unwind" fn(*mut c_void);
|
||||
pub type lua_Destructor = unsafe extern "C-unwind" fn(L: *mut lua_State, *mut c_void);
|
||||
/// Type for userdata destructor functions (no unwinding).
|
||||
pub type lua_Destructor = unsafe extern "C" fn(L: *mut lua_State, *mut c_void);
|
||||
|
||||
/// Type for memory-allocation functions.
|
||||
pub type lua_Alloc = unsafe extern "C-unwind" fn(
|
||||
ud: *mut c_void,
|
||||
ptr: *mut c_void,
|
||||
osize: usize,
|
||||
nsize: usize,
|
||||
) -> *mut c_void;
|
||||
/// Type for memory-allocation functions (no unwinding).
|
||||
pub type lua_Alloc =
|
||||
unsafe extern "C" fn(ud: *mut c_void, ptr: *mut c_void, osize: usize, nsize: usize) -> *mut c_void;
|
||||
|
||||
/// Returns Luau release version (eg. `0.xxx`).
|
||||
pub const fn luau_version() -> Option<&'static str> {
|
||||
option_env!("LUAU_VERSION")
|
||||
}
|
||||
|
||||
extern "C-unwind" {
|
||||
unsafe extern "C-unwind" {
|
||||
//
|
||||
// State manipulation
|
||||
//
|
||||
@@ -140,14 +150,22 @@ extern "C-unwind" {
|
||||
|
||||
pub fn lua_tonumberx(L: *mut lua_State, idx: c_int, isnum: *mut c_int) -> lua_Number;
|
||||
#[link_name = "lua_tointegerx"]
|
||||
pub fn lua_tointegerx_(L: *mut lua_State, idx: c_int, isnum: *mut c_int) -> lua_Integer;
|
||||
pub fn lua_tointegerx_(L: *mut lua_State, idx: c_int, isnum: *mut c_int) -> c_int;
|
||||
pub fn lua_tounsignedx(L: *mut lua_State, idx: c_int, isnum: *mut c_int) -> lua_Unsigned;
|
||||
pub fn lua_tovector(L: *mut lua_State, idx: c_int) -> *const c_float;
|
||||
pub fn lua_toboolean(L: *mut lua_State, idx: c_int) -> c_int;
|
||||
pub fn lua_tointeger64(L: *mut lua_State, idx: c_int, isinteger: *mut c_int) -> i64;
|
||||
pub fn lua_tolstring(L: *mut lua_State, idx: c_int, len: *mut usize) -> *const c_char;
|
||||
pub fn lua_tostringatom(L: *mut lua_State, idx: c_int, atom: *mut c_int) -> *const c_char;
|
||||
pub fn lua_tolstringatom(
|
||||
L: *mut lua_State,
|
||||
idx: c_int,
|
||||
len: *mut usize,
|
||||
atom: *mut c_int,
|
||||
) -> *const c_char;
|
||||
pub fn lua_namecallatom(L: *mut lua_State, atom: *mut c_int) -> *const c_char;
|
||||
pub fn lua_objlen(L: *mut lua_State, idx: c_int) -> usize;
|
||||
#[link_name = "lua_objlen"]
|
||||
pub fn lua_objlen_(L: *mut lua_State, idx: c_int) -> c_int;
|
||||
pub fn lua_tocfunction(L: *mut lua_State, idx: c_int) -> Option<lua_CFunction>;
|
||||
pub fn lua_tolightuserdata(L: *mut lua_State, idx: c_int) -> *mut c_void;
|
||||
pub fn lua_tolightuserdatatagged(L: *mut lua_State, idx: c_int, tag: c_int) -> *mut c_void;
|
||||
@@ -164,7 +182,9 @@ extern "C-unwind" {
|
||||
//
|
||||
pub fn lua_pushnil(L: *mut lua_State);
|
||||
pub fn lua_pushnumber(L: *mut lua_State, n: lua_Number);
|
||||
pub fn lua_pushinteger(L: *mut lua_State, n: lua_Integer);
|
||||
#[link_name = "lua_pushinteger"]
|
||||
pub fn lua_pushinteger_(L: *mut lua_State, n: c_int);
|
||||
pub fn lua_pushinteger64(L: *mut lua_State, n: i64);
|
||||
pub fn lua_pushunsigned(L: *mut lua_State, n: lua_Unsigned);
|
||||
#[cfg(not(feature = "luau-vector4"))]
|
||||
pub fn lua_pushvector(L: *mut lua_State, x: c_float, y: c_float, z: c_float);
|
||||
@@ -189,7 +209,8 @@ extern "C-unwind" {
|
||||
|
||||
pub fn lua_pushlightuserdatatagged(L: *mut lua_State, p: *mut c_void, tag: c_int);
|
||||
pub fn lua_newuserdatatagged(L: *mut lua_State, sz: usize, tag: c_int) -> *mut c_void;
|
||||
pub fn lua_newuserdatadtor(L: *mut lua_State, sz: usize, dtor: lua_Udestructor) -> *mut c_void;
|
||||
pub fn lua_newuserdatataggedwithmetatable(L: *mut lua_State, sz: usize, tag: c_int) -> *mut c_void;
|
||||
pub fn lua_newuserdatadtor(L: *mut lua_State, sz: usize, dtor: lua_Destructor) -> *mut c_void;
|
||||
|
||||
pub fn lua_newbuffer(L: *mut lua_State, sz: usize) -> *mut c_void;
|
||||
|
||||
@@ -202,6 +223,7 @@ extern "C-unwind" {
|
||||
pub fn lua_rawget(L: *mut lua_State, idx: c_int) -> c_int;
|
||||
#[link_name = "lua_rawgeti"]
|
||||
pub fn lua_rawgeti_(L: *mut lua_State, idx: c_int, n: c_int) -> c_int;
|
||||
pub fn lua_rawgetptagged(L: *mut lua_State, idx: c_int, p: *const c_void, tag: c_int) -> c_int;
|
||||
pub fn lua_createtable(L: *mut lua_State, narr: c_int, nrec: c_int);
|
||||
|
||||
pub fn lua_setreadonly(L: *mut lua_State, idx: c_int, enabled: c_int);
|
||||
@@ -216,9 +238,11 @@ extern "C-unwind" {
|
||||
//
|
||||
pub fn lua_settable(L: *mut lua_State, idx: c_int);
|
||||
pub fn lua_setfield(L: *mut lua_State, idx: c_int, k: *const c_char);
|
||||
pub fn lua_rawsetfield(L: *mut lua_State, idx: c_int, k: *const c_char);
|
||||
pub fn lua_rawset(L: *mut lua_State, idx: c_int);
|
||||
#[link_name = "lua_rawseti"]
|
||||
pub fn lua_rawseti_(L: *mut lua_State, idx: c_int, n: c_int);
|
||||
pub fn lua_rawsetptagged(L: *mut lua_State, idx: c_int, p: *const c_void, tag: c_int);
|
||||
pub fn lua_setmetatable(L: *mut lua_State, objindex: c_int) -> c_int;
|
||||
pub fn lua_setfenv(L: *mut lua_State, idx: c_int) -> c_int;
|
||||
|
||||
@@ -234,6 +258,7 @@ extern "C-unwind" {
|
||||
) -> c_int;
|
||||
pub fn lua_call(L: *mut lua_State, nargs: c_int, nresults: c_int);
|
||||
pub fn lua_pcall(L: *mut lua_State, nargs: c_int, nresults: c_int, errfunc: c_int) -> c_int;
|
||||
pub fn lua_cpcall(L: *mut lua_State, f: lua_CFunction, ud: *mut c_void) -> c_int;
|
||||
|
||||
//
|
||||
// Coroutine functions
|
||||
@@ -247,6 +272,12 @@ extern "C-unwind" {
|
||||
pub fn lua_isyieldable(L: *mut lua_State) -> c_int;
|
||||
pub fn lua_getthreaddata(L: *mut lua_State) -> *mut c_void;
|
||||
pub fn lua_setthreaddata(L: *mut lua_State, data: *mut c_void);
|
||||
pub fn lua_costatus(L: *mut lua_State, co: *mut lua_State) -> c_int;
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn lua_objlen(L: *mut lua_State, idx: c_int) -> usize {
|
||||
lua_objlen_(L, idx) as usize
|
||||
}
|
||||
|
||||
//
|
||||
@@ -263,14 +294,14 @@ pub const LUA_GCSETGOAL: c_int = 7;
|
||||
pub const LUA_GCSETSTEPMUL: c_int = 8;
|
||||
pub const LUA_GCSETSTEPSIZE: c_int = 9;
|
||||
|
||||
extern "C-unwind" {
|
||||
unsafe extern "C-unwind" {
|
||||
pub fn lua_gc(L: *mut lua_State, what: c_int, data: c_int) -> c_int;
|
||||
}
|
||||
|
||||
//
|
||||
// Memory statistics
|
||||
//
|
||||
extern "C-unwind" {
|
||||
unsafe extern "C-unwind" {
|
||||
pub fn lua_setmemcat(L: *mut lua_State, category: c_int);
|
||||
pub fn lua_totalbytes(L: *mut lua_State, category: c_int) -> usize;
|
||||
}
|
||||
@@ -278,22 +309,23 @@ extern "C-unwind" {
|
||||
//
|
||||
// Miscellaneous functions
|
||||
//
|
||||
extern "C-unwind" {
|
||||
unsafe extern "C-unwind" {
|
||||
pub fn lua_error(L: *mut lua_State) -> !;
|
||||
pub fn lua_next(L: *mut lua_State, idx: c_int) -> c_int;
|
||||
pub fn lua_rawiter(L: *mut lua_State, idx: c_int, iter: c_int) -> c_int;
|
||||
pub fn lua_concat(L: *mut lua_State, n: c_int);
|
||||
// TODO: lua_encodepointer
|
||||
pub fn lua_encodepointer(L: *mut lua_State, p: usize) -> usize;
|
||||
pub fn lua_clock() -> c_double;
|
||||
pub fn lua_setuserdatatag(L: *mut lua_State, idx: c_int, tag: c_int);
|
||||
pub fn lua_setuserdatadtor(L: *mut lua_State, tag: c_int, dtor: Option<lua_Destructor>);
|
||||
pub fn lua_getuserdatadtor(L: *mut lua_State, tag: c_int) -> Option<lua_Destructor>;
|
||||
pub fn lua_setuserdatametatable(L: *mut lua_State, tag: c_int, idx: c_int);
|
||||
pub fn lua_setuserdatametatable(L: *mut lua_State, tag: c_int);
|
||||
pub fn lua_getuserdatametatable(L: *mut lua_State, tag: c_int);
|
||||
pub fn lua_setlightuserdataname(L: *mut lua_State, tag: c_int, name: *const c_char);
|
||||
pub fn lua_getlightuserdataname(L: *mut lua_State, tag: c_int) -> *const c_char;
|
||||
pub fn lua_clonefunction(L: *mut lua_State, idx: c_int);
|
||||
pub fn lua_cleartable(L: *mut lua_State, idx: c_int);
|
||||
pub fn lua_clonetable(L: *mut lua_State, idx: c_int);
|
||||
pub fn lua_getallocf(L: *mut lua_State, ud: *mut *mut c_void) -> lua_Alloc;
|
||||
}
|
||||
|
||||
@@ -303,7 +335,7 @@ extern "C-unwind" {
|
||||
pub const LUA_NOREF: c_int = -1;
|
||||
pub const LUA_REFNIL: c_int = 0;
|
||||
|
||||
extern "C-unwind" {
|
||||
unsafe extern "C-unwind" {
|
||||
pub fn lua_ref(L: *mut lua_State, idx: c_int) -> c_int;
|
||||
pub fn lua_unref(L: *mut lua_State, r#ref: c_int);
|
||||
}
|
||||
@@ -313,13 +345,13 @@ extern "C-unwind" {
|
||||
//
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn lua_tonumber(L: *mut lua_State, i: c_int) -> lua_Number {
|
||||
lua_tonumberx(L, i, ptr::null_mut())
|
||||
pub unsafe fn lua_tonumber(L: *mut lua_State, idx: c_int) -> lua_Number {
|
||||
lua_tonumberx(L, idx, ptr::null_mut())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn lua_tointeger_(L: *mut lua_State, i: c_int) -> lua_Integer {
|
||||
lua_tointegerx_(L, i, ptr::null_mut())
|
||||
pub unsafe fn lua_tointeger_(L: *mut lua_State, idx: c_int) -> c_int {
|
||||
lua_tointegerx_(L, idx, ptr::null_mut())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
@@ -343,15 +375,20 @@ pub unsafe fn lua_newuserdata(L: *mut lua_State, sz: usize) -> *mut c_void {
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn lua_newuserdata_t<T>(L: *mut lua_State) -> *mut T {
|
||||
unsafe extern "C-unwind" fn destructor<T>(ud: *mut c_void) {
|
||||
pub unsafe fn lua_newuserdata_t<T>(L: *mut lua_State, data: T) -> *mut T {
|
||||
unsafe extern "C" fn destructor<T>(_: *mut lua_State, ud: *mut c_void) {
|
||||
ptr::drop_in_place(ud as *mut T);
|
||||
}
|
||||
|
||||
lua_newuserdatadtor(L, mem::size_of::<T>(), destructor::<T>) as *mut T
|
||||
let ud_ptr = lua_newuserdatadtor(L, const { mem::size_of::<T>() }, destructor::<T>) as *mut T;
|
||||
ptr::write(ud_ptr, data);
|
||||
ud_ptr
|
||||
}
|
||||
|
||||
// TODO: lua_strlen
|
||||
#[inline(always)]
|
||||
pub unsafe fn lua_strlen(L: *mut lua_State, i: c_int) -> usize {
|
||||
lua_objlen(L, i)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn lua_isfunction(L: *mut lua_State, n: c_int) -> c_int {
|
||||
@@ -378,6 +415,11 @@ pub unsafe fn lua_isboolean(L: *mut lua_State, n: c_int) -> c_int {
|
||||
(lua_type(L, n) == LUA_TBOOLEAN) as c_int
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn lua_isinteger64(L: *mut lua_State, n: c_int) -> c_int {
|
||||
(lua_type(L, n) == LUA_TINTEGER) as c_int
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn lua_isvector(L: *mut lua_State, n: c_int) -> c_int {
|
||||
(lua_type(L, n) == LUA_TVECTOR) as c_int
|
||||
@@ -404,10 +446,8 @@ pub unsafe fn lua_isnoneornil(L: *mut lua_State, n: c_int) -> c_int {
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn lua_pushliteral(L: *mut lua_State, s: &'static str) {
|
||||
use std::ffi::CString;
|
||||
let c_str = CString::new(s).unwrap();
|
||||
lua_pushlstring_(L, c_str.as_ptr(), c_str.as_bytes().len())
|
||||
pub unsafe fn lua_pushliteral(L: *mut lua_State, s: &'static CStr) {
|
||||
lua_pushstring_(L, s.as_ptr());
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
@@ -426,12 +466,7 @@ pub unsafe fn lua_pushcclosure(L: *mut lua_State, f: lua_CFunction, nup: c_int)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub unsafe fn lua_pushcclosured(
|
||||
L: *mut lua_State,
|
||||
f: lua_CFunction,
|
||||
debugname: *const c_char,
|
||||
nup: c_int,
|
||||
) {
|
||||
pub unsafe fn lua_pushcclosured(L: *mut lua_State, f: lua_CFunction, debugname: *const c_char, nup: c_int) {
|
||||
lua_pushcclosurek(L, f, debugname, nup, None)
|
||||
}
|
||||
|
||||
@@ -474,14 +509,15 @@ pub type lua_Coverage = unsafe extern "C-unwind" fn(
|
||||
size: usize,
|
||||
);
|
||||
|
||||
extern "C-unwind" {
|
||||
pub type lua_CounterFunction =
|
||||
unsafe extern "C-unwind" fn(context: *mut c_void, function: *const c_char, linedefined: c_int);
|
||||
|
||||
pub type lua_CounterValue =
|
||||
unsafe extern "C-unwind" fn(context: *mut c_void, kind: c_int, line: c_int, hits: u64);
|
||||
|
||||
unsafe extern "C-unwind" {
|
||||
pub fn lua_stackdepth(L: *mut lua_State) -> c_int;
|
||||
pub fn lua_getinfo(
|
||||
L: *mut lua_State,
|
||||
level: c_int,
|
||||
what: *const c_char,
|
||||
ar: *mut lua_Debug,
|
||||
) -> c_int;
|
||||
pub fn lua_getinfo(L: *mut lua_State, level: c_int, what: *const c_char, ar: *mut lua_Debug) -> c_int;
|
||||
pub fn lua_getargument(L: *mut lua_State, level: c_int, n: c_int) -> c_int;
|
||||
pub fn lua_getlocal(L: *mut lua_State, level: c_int, n: c_int) -> *const c_char;
|
||||
pub fn lua_setlocal(L: *mut lua_State, level: c_int, n: c_int) -> *const c_char;
|
||||
@@ -489,18 +525,16 @@ extern "C-unwind" {
|
||||
pub fn lua_setupvalue(L: *mut lua_State, funcindex: c_int, n: c_int) -> *const c_char;
|
||||
|
||||
pub fn lua_singlestep(L: *mut lua_State, enabled: c_int);
|
||||
pub fn lua_breakpoint(
|
||||
L: *mut lua_State,
|
||||
funcindex: c_int,
|
||||
line: c_int,
|
||||
enabled: c_int,
|
||||
) -> c_int;
|
||||
pub fn lua_breakpoint(L: *mut lua_State, funcindex: c_int, line: c_int, enabled: c_int) -> c_int;
|
||||
|
||||
pub fn lua_getcoverage(
|
||||
pub fn lua_getcoverage(L: *mut lua_State, funcindex: c_int, context: *mut c_void, callback: lua_Coverage);
|
||||
|
||||
pub fn lua_getcounters(
|
||||
L: *mut lua_State,
|
||||
funcindex: c_int,
|
||||
context: *mut c_void,
|
||||
callback: lua_Coverage,
|
||||
functionvisit: lua_CounterFunction,
|
||||
countervisit: lua_CounterValue,
|
||||
);
|
||||
|
||||
pub fn lua_debugtrace(L: *mut lua_State) -> *const c_char;
|
||||
@@ -539,8 +573,8 @@ pub struct lua_Callbacks {
|
||||
|
||||
/// gets called when L is created (LP == parent) or destroyed (LP == NULL)
|
||||
pub userthread: Option<unsafe extern "C-unwind" fn(LP: *mut lua_State, L: *mut lua_State)>,
|
||||
/// gets called when a string is created; returned atom can be retrieved via tostringatom
|
||||
pub useratom: Option<unsafe extern "C-unwind" fn(s: *const c_char, l: usize) -> i16>,
|
||||
/// gets called when a string is created to assign an atom id
|
||||
pub useratom: Option<unsafe extern "C-unwind" fn(L: *mut lua_State, s: *const c_char, l: usize) -> i16>,
|
||||
|
||||
/// gets called when BREAK instruction is encountered
|
||||
pub debugbreak: Option<unsafe extern "C-unwind" fn(L: *mut lua_State, ar: *mut lua_Debug)>,
|
||||
@@ -550,13 +584,22 @@ pub struct lua_Callbacks {
|
||||
pub debuginterrupt: Option<unsafe extern "C-unwind" fn(L: *mut lua_State, ar: *mut lua_Debug)>,
|
||||
/// gets called when protected call results in an error
|
||||
pub debugprotectederror: Option<unsafe extern "C-unwind" fn(L: *mut lua_State)>,
|
||||
|
||||
/// gets called when memory is allocated
|
||||
pub onallocate: Option<unsafe extern "C-unwind" fn(L: *mut lua_State, osize: usize, nsize: usize)>,
|
||||
}
|
||||
|
||||
extern "C" {
|
||||
unsafe extern "C" {
|
||||
pub fn lua_callbacks(L: *mut lua_State) -> *mut lua_Callbacks;
|
||||
}
|
||||
|
||||
// Functions from customization lib
|
||||
extern "C" {
|
||||
unsafe extern "C" {
|
||||
pub fn luau_setfflag(name: *const c_char, value: c_int) -> c_int;
|
||||
pub fn lua_getmetatablepointer(L: *mut lua_State, idx: c_int) -> *const c_void;
|
||||
pub fn lua_gcdump(
|
||||
L: *mut lua_State,
|
||||
file: *mut c_void,
|
||||
category_name: Option<unsafe extern "C" fn(L: *mut lua_State, memcat: u8) -> *const c_char>,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Contains definitions from `luacode.h`.
|
||||
|
||||
use std::marker::{PhantomData, PhantomPinned};
|
||||
use std::os::raw::{c_char, c_int, c_void};
|
||||
use std::{ptr, slice};
|
||||
|
||||
@@ -15,6 +16,10 @@ pub struct lua_CompileOptions {
|
||||
pub vectorType: *const c_char,
|
||||
pub mutableGlobals: *const *const c_char,
|
||||
pub userdataTypes: *const *const c_char,
|
||||
pub librariesWithKnownMembers: *const *const c_char,
|
||||
pub libraryMemberTypeCallback: Option<lua_LibraryMemberTypeCallback>,
|
||||
pub libraryMemberConstantCallback: Option<lua_LibraryMemberConstantCallback>,
|
||||
pub disabledBuiltins: *const *const c_char,
|
||||
}
|
||||
|
||||
impl Default for lua_CompileOptions {
|
||||
@@ -29,11 +34,58 @@ impl Default for lua_CompileOptions {
|
||||
vectorType: ptr::null(),
|
||||
mutableGlobals: ptr::null(),
|
||||
userdataTypes: ptr::null(),
|
||||
librariesWithKnownMembers: ptr::null(),
|
||||
libraryMemberTypeCallback: None,
|
||||
libraryMemberConstantCallback: None,
|
||||
disabledBuiltins: ptr::null(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extern "C-unwind" {
|
||||
#[repr(C)]
|
||||
pub struct lua_CompileConstant {
|
||||
_data: [u8; 0],
|
||||
_marker: PhantomData<(*mut u8, PhantomPinned)>,
|
||||
}
|
||||
|
||||
/// Type table tags
|
||||
#[doc(hidden)]
|
||||
#[repr(i32)]
|
||||
#[non_exhaustive]
|
||||
pub enum luau_BytecodeType {
|
||||
Nil = 0,
|
||||
Boolean,
|
||||
Number,
|
||||
String,
|
||||
Table,
|
||||
Function,
|
||||
Thread,
|
||||
UserData,
|
||||
Vector,
|
||||
Buffer,
|
||||
|
||||
Any = 15,
|
||||
}
|
||||
|
||||
pub type lua_LibraryMemberTypeCallback =
|
||||
unsafe extern "C-unwind" fn(library: *const c_char, member: *const c_char) -> c_int;
|
||||
|
||||
pub type lua_LibraryMemberConstantCallback = unsafe extern "C-unwind" fn(
|
||||
library: *const c_char,
|
||||
member: *const c_char,
|
||||
constant: *mut lua_CompileConstant,
|
||||
);
|
||||
|
||||
unsafe extern "C" {
|
||||
pub fn luau_set_compile_constant_nil(cons: *mut lua_CompileConstant);
|
||||
pub fn luau_set_compile_constant_boolean(cons: *mut lua_CompileConstant, b: c_int);
|
||||
pub fn luau_set_compile_constant_number(cons: *mut lua_CompileConstant, n: f64);
|
||||
pub fn luau_set_compile_constant_integer64(cons: *mut lua_CompileConstant, l: i64);
|
||||
pub fn luau_set_compile_constant_vector(cons: *mut lua_CompileConstant, x: f32, y: f32, z: f32, w: f32);
|
||||
pub fn luau_set_compile_constant_string(cons: *mut lua_CompileConstant, s: *const c_char, l: usize);
|
||||
}
|
||||
|
||||
unsafe extern "C-unwind" {
|
||||
#[link_name = "luau_compile"]
|
||||
pub fn luau_compile_(
|
||||
source: *const c_char,
|
||||
@@ -43,7 +95,7 @@ extern "C-unwind" {
|
||||
) -> *mut c_char;
|
||||
}
|
||||
|
||||
extern "C" {
|
||||
unsafe extern "C" {
|
||||
fn free(p: *mut c_void);
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ use std::os::raw::c_int;
|
||||
|
||||
use super::lua::lua_State;
|
||||
|
||||
extern "C-unwind" {
|
||||
unsafe extern "C-unwind" {
|
||||
pub fn luau_codegen_supported() -> c_int;
|
||||
pub fn luau_codegen_create(state: *mut lua_State);
|
||||
pub fn luau_codegen_compile(state: *mut lua_State, idx: c_int);
|
||||
|
||||
+15
-11
@@ -1,20 +1,22 @@
|
||||
//! Contains definitions from `lualib.h`.
|
||||
|
||||
use std::os::raw::c_int;
|
||||
use std::os::raw::{c_char, c_int};
|
||||
|
||||
use super::lua::lua_State;
|
||||
|
||||
pub const LUA_COLIBNAME: &str = "coroutine";
|
||||
pub const LUA_TABLIBNAME: &str = "table";
|
||||
pub const LUA_OSLIBNAME: &str = "os";
|
||||
pub const LUA_STRLIBNAME: &str = "string";
|
||||
pub const LUA_BITLIBNAME: &str = "bit32";
|
||||
pub const LUA_BUFFERLIBNAME: &str = "buffer";
|
||||
pub const LUA_UTF8LIBNAME: &str = "utf8";
|
||||
pub const LUA_MATHLIBNAME: &str = "math";
|
||||
pub const LUA_DBLIBNAME: &str = "debug";
|
||||
pub const LUA_COLIBNAME: *const c_char = cstr!("coroutine");
|
||||
pub const LUA_TABLIBNAME: *const c_char = cstr!("table");
|
||||
pub const LUA_OSLIBNAME: *const c_char = cstr!("os");
|
||||
pub const LUA_STRLIBNAME: *const c_char = cstr!("string");
|
||||
pub const LUA_BITLIBNAME: *const c_char = cstr!("bit32");
|
||||
pub const LUA_BUFFERLIBNAME: *const c_char = cstr!("buffer");
|
||||
pub const LUA_UTF8LIBNAME: *const c_char = cstr!("utf8");
|
||||
pub const LUA_MATHLIBNAME: *const c_char = cstr!("math");
|
||||
pub const LUA_DBLIBNAME: *const c_char = cstr!("debug");
|
||||
pub const LUA_VECLIBNAME: *const c_char = cstr!("vector");
|
||||
pub const LUA_INTLIBNAME: *const c_char = cstr!("integer");
|
||||
|
||||
extern "C-unwind" {
|
||||
unsafe extern "C-unwind" {
|
||||
pub fn luaopen_base(L: *mut lua_State) -> c_int;
|
||||
pub fn luaopen_coroutine(L: *mut lua_State) -> c_int;
|
||||
pub fn luaopen_table(L: *mut lua_State) -> c_int;
|
||||
@@ -25,6 +27,8 @@ extern "C-unwind" {
|
||||
pub fn luaopen_utf8(L: *mut lua_State) -> c_int;
|
||||
pub fn luaopen_math(L: *mut lua_State) -> c_int;
|
||||
pub fn luaopen_debug(L: *mut lua_State) -> c_int;
|
||||
pub fn luaopen_vector(L: *mut lua_State) -> c_int;
|
||||
pub fn luaopen_integer(L: *mut lua_State) -> c_int;
|
||||
|
||||
// open all builtin libraries
|
||||
pub fn luaL_openlibs(L: *mut lua_State);
|
||||
|
||||
@@ -0,0 +1,219 @@
|
||||
//! Contains definitions from `Require.h`.
|
||||
|
||||
use std::os::raw::{c_char, c_int, c_void};
|
||||
|
||||
use super::lua::lua_State;
|
||||
|
||||
pub const LUA_REGISTERED_MODULES_TABLE: *const c_char = cstr!("_REGISTEREDMODULES");
|
||||
|
||||
#[repr(C)]
|
||||
pub enum luarequire_NavigateResult {
|
||||
Success,
|
||||
Ambiguous,
|
||||
NotFound,
|
||||
}
|
||||
|
||||
// Functions returning WriteSuccess are expected to set their size_out argument
|
||||
// to the number of bytes written to the buffer. If WriteBufferTooSmall is
|
||||
// returned, size_out should be set to the required buffer size.
|
||||
#[repr(C)]
|
||||
pub enum luarequire_WriteResult {
|
||||
Success,
|
||||
BufferTooSmall,
|
||||
Failure,
|
||||
}
|
||||
|
||||
/// Represents whether a configuration file is present, and if so, its syntax.
|
||||
#[repr(C)]
|
||||
pub enum luarequire_ConfigStatus {
|
||||
Absent,
|
||||
// Signals the presence of multiple configuration files
|
||||
Ambiguous,
|
||||
PresentJson,
|
||||
PresentLuau,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
pub struct luarequire_Configuration {
|
||||
// Returns whether requires are permitted from the given chunkname.
|
||||
pub is_require_allowed: unsafe extern "C-unwind" fn(
|
||||
L: *mut lua_State,
|
||||
ctx: *mut c_void,
|
||||
requirer_chunkname: *const c_char,
|
||||
) -> bool,
|
||||
|
||||
// Resets the internal state to point at the requirer module.
|
||||
pub reset: unsafe extern "C-unwind" fn(
|
||||
L: *mut lua_State,
|
||||
ctx: *mut c_void,
|
||||
requirer_chunkname: *const c_char,
|
||||
) -> luarequire_NavigateResult,
|
||||
|
||||
// Resets the internal state to point at an aliased module, given its exact path from a configuration
|
||||
// file. This function is only called when an alias's path cannot be resolved relative to its
|
||||
// configuration file.
|
||||
pub jump_to_alias: unsafe extern "C-unwind" fn(
|
||||
L: *mut lua_State,
|
||||
ctx: *mut c_void,
|
||||
path: *const c_char,
|
||||
) -> luarequire_NavigateResult,
|
||||
|
||||
// Provides an initial alias override opportunity prior to searching for configuration files.
|
||||
// If NAVIGATE_SUCCESS is returned, the internal state must be updated to point at the
|
||||
// aliased location.
|
||||
// Can be left undefined.
|
||||
pub to_alias_override: Option<
|
||||
unsafe extern "C-unwind" fn(
|
||||
L: *mut lua_State,
|
||||
ctx: *mut c_void,
|
||||
alias_unprefixed: *const c_char,
|
||||
) -> luarequire_NavigateResult,
|
||||
>,
|
||||
|
||||
// Provides a final override opportunity if an alias cannot be found in configuration files. If
|
||||
// NAVIGATE_SUCCESS is returned, this must update the internal state to point at the aliased module.
|
||||
// Can be left undefined.
|
||||
pub to_alias_fallback: Option<
|
||||
unsafe extern "C-unwind" fn(
|
||||
L: *mut lua_State,
|
||||
ctx: *mut c_void,
|
||||
alias_unprefixed: *const c_char,
|
||||
) -> luarequire_NavigateResult,
|
||||
>,
|
||||
|
||||
// Navigates through the context by making mutations to the internal state.
|
||||
pub to_parent:
|
||||
unsafe extern "C-unwind" fn(L: *mut lua_State, ctx: *mut c_void) -> luarequire_NavigateResult,
|
||||
pub to_child: unsafe extern "C-unwind" fn(
|
||||
L: *mut lua_State,
|
||||
ctx: *mut c_void,
|
||||
name: *const c_char,
|
||||
) -> luarequire_NavigateResult,
|
||||
|
||||
// Returns whether the context is currently pointing at a module.
|
||||
pub is_module_present: unsafe extern "C-unwind" fn(L: *mut lua_State, ctx: *mut c_void) -> bool,
|
||||
|
||||
// Provides a chunkname for the current module. This will be accessible through the debug library. This
|
||||
// function is only called if is_module_present returns true.
|
||||
pub get_chunkname: unsafe extern "C-unwind" fn(
|
||||
L: *mut lua_State,
|
||||
ctx: *mut c_void,
|
||||
buffer: *mut c_char,
|
||||
buffer_size: usize,
|
||||
size_out: *mut usize,
|
||||
) -> luarequire_WriteResult,
|
||||
|
||||
// Provides a loadname that identifies the current module and is passed to load. This function
|
||||
// is only called if is_module_present returns true.
|
||||
pub get_loadname: unsafe extern "C-unwind" fn(
|
||||
L: *mut lua_State,
|
||||
ctx: *mut c_void,
|
||||
buffer: *mut c_char,
|
||||
buffer_size: usize,
|
||||
size_out: *mut usize,
|
||||
) -> luarequire_WriteResult,
|
||||
|
||||
// Provides a cache key representing the current module. This function is only called if
|
||||
// is_module_present returns true.
|
||||
pub get_cache_key: unsafe extern "C-unwind" fn(
|
||||
L: *mut lua_State,
|
||||
ctx: *mut c_void,
|
||||
buffer: *mut c_char,
|
||||
buffer_size: usize,
|
||||
size_out: *mut usize,
|
||||
) -> luarequire_WriteResult,
|
||||
|
||||
// Returns whether a configuration file is present in the current context, and if so, its syntax.
|
||||
// If not present, require-by-string will call to_parent until either a configuration file is present or
|
||||
// NAVIGATE_FAILURE is returned (at root).
|
||||
pub get_config_status:
|
||||
unsafe extern "C-unwind" fn(L: *mut lua_State, ctx: *mut c_void) -> luarequire_ConfigStatus,
|
||||
|
||||
// Parses the configuration file in the current context for the given alias and returns its
|
||||
// value or WRITE_FAILURE if not found. This function is only called if get_config_status
|
||||
// returns true. If this function pointer is set, get_config must not be set. Opting in to this
|
||||
// function pointer disables parsing configuration files internally and can be used for finer
|
||||
// control over the configuration file parsing process.
|
||||
pub get_alias: Option<
|
||||
unsafe extern "C-unwind" fn(
|
||||
L: *mut lua_State,
|
||||
ctx: *mut c_void,
|
||||
alias: *const c_char,
|
||||
buffer: *mut c_char,
|
||||
buffer_size: usize,
|
||||
size_out: *mut usize,
|
||||
) -> luarequire_WriteResult,
|
||||
>,
|
||||
|
||||
// Provides the contents of the configuration file in the current context.
|
||||
// This function is only called if get_config_status does not return CONFIG_ABSENT. If this function
|
||||
// pointer is set, get_alias must not be set. Opting in to this function pointer enables parsing
|
||||
// configuration files internally.
|
||||
pub get_config: Option<
|
||||
unsafe extern "C-unwind" fn(
|
||||
L: *mut lua_State,
|
||||
ctx: *mut c_void,
|
||||
buffer: *mut c_char,
|
||||
buffer_size: usize,
|
||||
size_out: *mut usize,
|
||||
) -> luarequire_WriteResult,
|
||||
>,
|
||||
|
||||
// Returns the maximum number of milliseconds to allow for executing a given Luau-syntax configuration
|
||||
// file. This function is only called if get_config_status returns CONFIG_PRESENT_LUAU and can be left
|
||||
// undefined if support for Luau-syntax configuration files is not needed. A default value of 2000ms is
|
||||
// used. Negative values are treated as infinite.
|
||||
pub get_luau_config_timeout:
|
||||
Option<unsafe extern "C-unwind" fn(L: *mut lua_State, ctx: *mut c_void) -> c_int>,
|
||||
|
||||
// Executes the module and places the result on the stack. Returns the number of results placed on the
|
||||
// stack.
|
||||
// Returning -1 directs the requiring thread to yield. In this case, this thread should be resumed with
|
||||
// the module result pushed onto its stack.
|
||||
pub load: unsafe extern "C-unwind" fn(
|
||||
L: *mut lua_State,
|
||||
ctx: *mut c_void,
|
||||
path: *const c_char,
|
||||
chunkname: *const c_char,
|
||||
loadname: *const c_char,
|
||||
) -> c_int,
|
||||
}
|
||||
|
||||
// Populates function pointers in the given luarequire_Configuration.
|
||||
pub type luarequire_Configuration_init = unsafe extern "C-unwind" fn(config: *mut luarequire_Configuration);
|
||||
|
||||
unsafe extern "C-unwind" {
|
||||
// Initializes and pushes the require closure onto the stack without registration.
|
||||
pub fn luarequire_pushrequire(
|
||||
L: *mut lua_State,
|
||||
config_init: luarequire_Configuration_init,
|
||||
ctx: *mut c_void,
|
||||
) -> c_int;
|
||||
|
||||
// Initializes the require library and registers it globally.
|
||||
pub fn luaopen_require(L: *mut lua_State, config_init: luarequire_Configuration_init, ctx: *mut c_void);
|
||||
|
||||
// Initializes and pushes a "proxyrequire" closure onto the stack.
|
||||
//
|
||||
// The closure takes two parameters: the string path to resolve and the chunkname of an existing
|
||||
// module.
|
||||
pub fn luarequire_pushproxyrequire(
|
||||
L: *mut lua_State,
|
||||
config_init: luarequire_Configuration_init,
|
||||
ctx: *mut c_void,
|
||||
) -> c_int;
|
||||
|
||||
// Registers an aliased require path to a result.
|
||||
//
|
||||
// After registration, the given result will always be immediately returned when the given path is
|
||||
// required.
|
||||
// Expects the path and table to be passed as arguments on the stack.
|
||||
pub fn luarequire_registermodule(L: *mut lua_State) -> c_int;
|
||||
|
||||
// Clears the entry associated with the given cache key from the require cache.
|
||||
// Expects the cache key to be passed as an argument on the stack.
|
||||
pub fn luarequire_clearcacheentry(L: *mut lua_State) -> c_int;
|
||||
|
||||
// Clears all entries from the require cache.
|
||||
pub fn luarequire_clearcache(L: *mut lua_State) -> c_int;
|
||||
}
|
||||
@@ -6,6 +6,7 @@ pub use lua::*;
|
||||
pub use luacode::*;
|
||||
pub use luacodegen::*;
|
||||
pub use lualib::*;
|
||||
pub use luarequire::*;
|
||||
|
||||
pub mod compat;
|
||||
pub mod lauxlib;
|
||||
@@ -13,3 +14,4 @@ pub mod lua;
|
||||
pub mod luacode;
|
||||
pub mod luacodegen;
|
||||
pub mod lualib;
|
||||
pub mod luarequire;
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
#[allow(unused_macros)]
|
||||
macro_rules! cstr {
|
||||
($s:expr) => {
|
||||
concat!($s, "\0") as *const str as *const [::std::os::raw::c_char]
|
||||
as *const ::std::os::raw::c_char
|
||||
concat!($s, "\0") as *const str as *const [::std::os::raw::c_char] as *const ::std::os::raw::c_char
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
[package]
|
||||
name = "mlua_derive"
|
||||
version = "0.9.3"
|
||||
version = "0.12.0-rc.1"
|
||||
authors = ["Aleksandr Orlenko <zxteam@pm.me>"]
|
||||
edition = "2021"
|
||||
rust-version = "1.88"
|
||||
edition = "2024"
|
||||
description = "Procedural macros for the mlua crate."
|
||||
repository = "https://github.com/khvzak/mlua"
|
||||
repository = "https://github.com/mlua-rs/mlua"
|
||||
keywords = ["lua", "mlua"]
|
||||
license = "MIT"
|
||||
|
||||
@@ -12,13 +13,11 @@ license = "MIT"
|
||||
proc-macro = true
|
||||
|
||||
[features]
|
||||
macros = ["proc-macro-error", "itertools", "regex", "once_cell"]
|
||||
macros = ["proc-macro-error2", "itertools"]
|
||||
|
||||
[dependencies]
|
||||
quote = "1.0"
|
||||
proc-macro2 = { version = "1.0", features = ["span-locations"] }
|
||||
proc-macro-error = { version = "1.0", optional = true }
|
||||
proc-macro-error2 = { version = "2.0.1", optional = true }
|
||||
syn = { version = "2.0", features = ["full"] }
|
||||
itertools = { version = "0.12", optional = true }
|
||||
regex = { version = "1.4", optional = true }
|
||||
once_cell = { version = "1.0", optional = true }
|
||||
itertools = { version = "0.14", optional = true }
|
||||
|
||||
@@ -1,105 +0,0 @@
|
||||
use proc_macro::{TokenStream, TokenTree};
|
||||
|
||||
use crate::token::{Pos, Token, Tokens};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct Capture {
|
||||
key: Token,
|
||||
rust: TokenTree,
|
||||
}
|
||||
|
||||
impl Capture {
|
||||
fn new(key: Token, rust: TokenTree) -> Self {
|
||||
Self { key, rust }
|
||||
}
|
||||
|
||||
/// Token string inside `chunk!`
|
||||
pub(crate) fn key(&self) -> &Token {
|
||||
&self.key
|
||||
}
|
||||
|
||||
/// As rust variable, e.g. `x`
|
||||
pub(crate) fn as_rust(&self) -> &TokenTree {
|
||||
&self.rust
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct Captures(Vec<Capture>);
|
||||
|
||||
impl Captures {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self(Vec::new())
|
||||
}
|
||||
|
||||
pub(crate) fn add(&mut self, token: &Token) -> Capture {
|
||||
let tt = token.tree();
|
||||
let key = token.clone();
|
||||
|
||||
match self.0.iter().find(|arg| arg.key() == &key) {
|
||||
Some(arg) => arg.clone(),
|
||||
None => {
|
||||
let arg = Capture::new(key, tt.clone());
|
||||
self.0.push(arg.clone());
|
||||
arg
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn captures(&self) -> &[Capture] {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct Chunk {
|
||||
source: String,
|
||||
caps: Captures,
|
||||
}
|
||||
|
||||
impl Chunk {
|
||||
pub(crate) fn new(tokens: TokenStream) -> Self {
|
||||
let tokens = Tokens::retokenize(tokens);
|
||||
|
||||
let mut source = String::new();
|
||||
let mut caps = Captures::new();
|
||||
|
||||
let mut pos: Option<Pos> = None;
|
||||
for t in tokens {
|
||||
if t.is_cap() {
|
||||
caps.add(&t);
|
||||
}
|
||||
|
||||
let (line, col) = (t.start().line, t.start().column);
|
||||
let (prev_line, prev_col) = pos
|
||||
.take()
|
||||
.map(|lc| (lc.line, lc.column))
|
||||
.unwrap_or_else(|| (line, col));
|
||||
|
||||
#[allow(clippy::comparison_chain)]
|
||||
if line > prev_line {
|
||||
source.push('\n');
|
||||
} else if line == prev_line {
|
||||
for _ in 0..col.saturating_sub(prev_col) {
|
||||
source.push(' ');
|
||||
}
|
||||
}
|
||||
source.push_str(&t.to_string());
|
||||
|
||||
pos = Some(t.end());
|
||||
}
|
||||
|
||||
Self {
|
||||
source: source.trim_end().to_string(),
|
||||
caps,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn source(&self) -> &str {
|
||||
&self.source
|
||||
}
|
||||
|
||||
pub(crate) fn captures(&self) -> &[Capture] {
|
||||
self.caps.captures()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
use std::ops::Deref;
|
||||
|
||||
use proc_macro::TokenStream;
|
||||
use proc_macro2::TokenStream as TokenStream2;
|
||||
use quote::{ToTokens, quote};
|
||||
|
||||
use self::token::{Pos, Token, Tokens};
|
||||
|
||||
mod token;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct Capture(Token);
|
||||
|
||||
impl Deref for Capture {
|
||||
type Target = Token;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Capture {
|
||||
fn new(token: &Token) -> Self {
|
||||
Self(token.clone())
|
||||
}
|
||||
|
||||
pub(crate) fn name(&self) -> String {
|
||||
self.0.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
impl ToTokens for Capture {
|
||||
fn to_tokens(&self, tokens: &mut TokenStream2) {
|
||||
let ts: TokenStream = self.0.tree().clone().into();
|
||||
tokens.extend(TokenStream2::from(ts));
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct Captures(Vec<Capture>);
|
||||
|
||||
impl Captures {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self(Vec::new())
|
||||
}
|
||||
|
||||
pub(crate) fn add(&mut self, token: &Token) {
|
||||
if self.0.iter().any(|arg| &**arg == token) {
|
||||
return;
|
||||
}
|
||||
self.0.push(Capture::new(token));
|
||||
}
|
||||
|
||||
pub(crate) fn captures(&self) -> &[Capture] {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct Chunk {
|
||||
source: String,
|
||||
caps: Captures,
|
||||
}
|
||||
|
||||
impl Chunk {
|
||||
pub(crate) fn new(tokens: TokenStream) -> Self {
|
||||
let tokens = Tokens::retokenize(tokens);
|
||||
|
||||
let mut source = String::new();
|
||||
let mut caps = Captures::new();
|
||||
|
||||
let mut prev_end: Option<Pos> = None;
|
||||
for t in tokens {
|
||||
if t.is_cap() {
|
||||
caps.add(&t);
|
||||
}
|
||||
|
||||
let (line, col) = (t.start().line, t.start().column);
|
||||
if let Some(prev) = prev_end {
|
||||
if line > prev.line {
|
||||
source.push('\n');
|
||||
source.push_str(&" ".repeat(col.saturating_sub(1)));
|
||||
} else if line == prev.line {
|
||||
source.push_str(&" ".repeat(col.saturating_sub(prev.column)));
|
||||
}
|
||||
} else {
|
||||
source.push_str(&" ".repeat(col.saturating_sub(1)));
|
||||
}
|
||||
source.push_str(&t.to_string());
|
||||
|
||||
prev_end = Some(t.end());
|
||||
}
|
||||
|
||||
Self {
|
||||
source: source.trim_end().to_string(),
|
||||
caps,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn captures(&self) -> &[Capture] {
|
||||
self.caps.captures()
|
||||
}
|
||||
|
||||
pub(crate) fn expand(&self) -> TokenStream2 {
|
||||
let source = &self.source;
|
||||
|
||||
let caps_len = self.captures().len();
|
||||
let caps = self.captures().iter().map(|cap| {
|
||||
let cap_name = cap.name();
|
||||
quote! { env.raw_set(#cap_name, #cap)?; }
|
||||
});
|
||||
|
||||
quote! {{
|
||||
use mlua::{AsChunk, ChunkMode, Lua, Result, Table};
|
||||
use ::std::borrow::Cow;
|
||||
use ::std::cell::Cell;
|
||||
use ::std::io::Result as IoResult;
|
||||
|
||||
struct InnerChunk<F: FnOnce(&Lua) -> Result<Table>>(Cell<Option<F>>);
|
||||
|
||||
impl<F> AsChunk for InnerChunk<F>
|
||||
where
|
||||
F: FnOnce(&Lua) -> Result<Table>,
|
||||
{
|
||||
fn environment(&self, lua: &Lua) -> Result<Option<Table>> {
|
||||
if #caps_len > 0 {
|
||||
if let Some(make_env) = self.0.take() {
|
||||
return make_env(lua).map(Some);
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn mode(&self) -> Option<ChunkMode> {
|
||||
Some(ChunkMode::Text)
|
||||
}
|
||||
|
||||
fn source<'a>(&self) -> IoResult<Cow<'a, [u8]>> {
|
||||
Ok(Cow::Borrowed((#source).as_bytes()))
|
||||
}
|
||||
}
|
||||
|
||||
let make_env = move |lua: &Lua| -> Result<Table> {
|
||||
let globals = lua.globals();
|
||||
let env = lua.create_table()?;
|
||||
let meta = lua.create_table()?;
|
||||
meta.raw_set("__index", &globals)?;
|
||||
meta.raw_set("__newindex", &globals)?;
|
||||
|
||||
// Add captured variables
|
||||
#(#caps)*
|
||||
|
||||
env.set_metatable(Some(meta))?;
|
||||
Ok(env)
|
||||
};
|
||||
|
||||
InnerChunk(Cell::new(Some(make_env)))
|
||||
}}
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,10 @@
|
||||
use std::{
|
||||
cmp::{Eq, PartialEq},
|
||||
fmt::{self, Display, Formatter},
|
||||
vec::IntoIter,
|
||||
};
|
||||
use std::cmp::{Eq, PartialEq};
|
||||
use std::fmt::{self, Display, Formatter};
|
||||
use std::vec::IntoIter;
|
||||
|
||||
use itertools::Itertools;
|
||||
use once_cell::sync::Lazy;
|
||||
use proc_macro::{Delimiter, Span, TokenStream, TokenTree};
|
||||
use proc_macro2::Span as Span2;
|
||||
use regex::Regex;
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(crate) struct Pos {
|
||||
@@ -41,49 +37,14 @@ fn span_pos(span: &Span) -> (Pos, Pos) {
|
||||
let start = span2.start();
|
||||
let end = span2.end();
|
||||
|
||||
// In stable, line/column information is not provided
|
||||
// and set to 0 (line is 1-indexed)
|
||||
// Rust 1.88 stabilized Span APIs, so this branch must be unreachable
|
||||
if start.line == 0 || end.line == 0 {
|
||||
return fallback_span_pos(span);
|
||||
proc_macro_error2::abort_call_site!(
|
||||
"cannot retrieve span location information; mlua requires nightly Rust or stable >= 1.88"
|
||||
);
|
||||
}
|
||||
|
||||
(
|
||||
Pos::new(start.line, start.column),
|
||||
Pos::new(end.line, end.column),
|
||||
)
|
||||
}
|
||||
|
||||
fn parse_pos(span: &Span) -> Option<(usize, usize)> {
|
||||
// Workaround to somehow retrieve location information in span in stable rust :(
|
||||
|
||||
static RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"bytes\(([0-9]+)\.\.([0-9]+)\)").unwrap());
|
||||
|
||||
match RE.captures(&format!("{span:?}")) {
|
||||
Some(caps) => match (caps.get(1), caps.get(2)) {
|
||||
(Some(start), Some(end)) => Some((
|
||||
match start.as_str().parse() {
|
||||
Ok(v) => v,
|
||||
_ => return None,
|
||||
},
|
||||
match end.as_str().parse() {
|
||||
Ok(v) => v,
|
||||
_ => return None,
|
||||
},
|
||||
)),
|
||||
_ => None,
|
||||
},
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn fallback_span_pos(span: &Span) -> (Pos, Pos) {
|
||||
let (start, end) = match parse_pos(span) {
|
||||
Some(v) => v,
|
||||
None => proc_macro_error::abort_call_site!(
|
||||
"Cannot retrieve span information; please use nightly"
|
||||
),
|
||||
};
|
||||
(Pos::new(1, start), Pos::new(1, end))
|
||||
(Pos::new(start.line, start.column), Pos::new(end.line, end.column))
|
||||
}
|
||||
|
||||
/// Attribute of token.
|
||||
@@ -115,8 +76,9 @@ impl Eq for Token {}
|
||||
impl Token {
|
||||
fn new(tree: TokenTree) -> Self {
|
||||
let (start, end) = span_pos(&tree.span());
|
||||
let source = tree.span().source_text().unwrap_or_else(|| tree.to_string());
|
||||
Self {
|
||||
source: tree.to_string(),
|
||||
source,
|
||||
start,
|
||||
end,
|
||||
tree,
|
||||
@@ -175,14 +137,17 @@ impl Tokens {
|
||||
Tokens(
|
||||
tt.into_iter()
|
||||
.flat_map(Tokens::from)
|
||||
.peekable()
|
||||
.batching(|iter| {
|
||||
// Find variable tokens
|
||||
// Find variable tokens: `$` + `ident` => `$ident`
|
||||
let t = iter.next()?;
|
||||
if t.is("$") {
|
||||
// `$` + `ident` => `$ident`
|
||||
let t = iter.next().expect("$ must trail an identifier");
|
||||
Some(t.attr(TokenAttr::Cap))
|
||||
if let Some(next) = iter.next()
|
||||
&& matches!(next.tree, TokenTree::Ident(_))
|
||||
{
|
||||
Some(next.attr(TokenAttr::Cap))
|
||||
} else {
|
||||
proc_macro_error2::abort!(t.tree.span(), "`$` must be followed by an identifier");
|
||||
}
|
||||
} else {
|
||||
Some(t)
|
||||
}
|
||||
+14
-16
@@ -1,11 +1,9 @@
|
||||
use proc_macro::TokenStream;
|
||||
use quote::quote;
|
||||
use syn::{parse_macro_input, DeriveInput};
|
||||
use syn::{DeriveInput, parse_macro_input};
|
||||
|
||||
pub fn from_lua(input: TokenStream) -> TokenStream {
|
||||
let DeriveInput {
|
||||
ident, generics, ..
|
||||
} = parse_macro_input!(input as DeriveInput);
|
||||
let DeriveInput { ident, generics, .. } = parse_macro_input!(input as DeriveInput);
|
||||
|
||||
let ident_str = ident.to_string();
|
||||
let (impl_generics, ty_generics, _) = generics.split_for_impl();
|
||||
@@ -15,19 +13,19 @@ pub fn from_lua(input: TokenStream) -> TokenStream {
|
||||
};
|
||||
|
||||
quote! {
|
||||
impl #impl_generics ::mlua::FromLua<'_> for #ident #ty_generics #where_clause {
|
||||
#[inline]
|
||||
fn from_lua(value: ::mlua::Value<'_>, _: &'_ ::mlua::Lua) -> ::mlua::Result<Self> {
|
||||
match value {
|
||||
::mlua::Value::UserData(ud) => Ok(ud.borrow::<Self>()?.clone()),
|
||||
_ => Err(::mlua::Error::FromLuaConversionError {
|
||||
from: value.type_name(),
|
||||
to: #ident_str,
|
||||
message: None,
|
||||
}),
|
||||
}
|
||||
impl #impl_generics ::mlua::FromLua for #ident #ty_generics #where_clause {
|
||||
#[inline]
|
||||
fn from_lua(value: ::mlua::Value, _: &::mlua::Lua) -> ::mlua::Result<Self> {
|
||||
match value {
|
||||
::mlua::Value::UserData(ud) => Ok(ud.borrow::<Self>()?.clone()),
|
||||
_ => Err(::mlua::Error::FromLuaConversionError {
|
||||
from: value.type_name(),
|
||||
to: #ident_str.to_string(),
|
||||
message: None,
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
.into()
|
||||
}
|
||||
|
||||
+27
-133
@@ -1,150 +1,30 @@
|
||||
use proc_macro::TokenStream;
|
||||
use proc_macro2::{Ident, Span};
|
||||
use quote::quote;
|
||||
use syn::meta::ParseNestedMeta;
|
||||
use syn::{parse_macro_input, ItemFn, LitStr, Result};
|
||||
|
||||
mod module;
|
||||
|
||||
#[cfg(feature = "macros")]
|
||||
use {
|
||||
crate::chunk::Chunk, proc_macro::TokenTree, proc_macro2::TokenStream as TokenStream2,
|
||||
proc_macro_error::proc_macro_error,
|
||||
};
|
||||
use {crate::chunk::Chunk, proc_macro_error2::proc_macro_error};
|
||||
|
||||
#[derive(Default)]
|
||||
struct ModuleAttributes {
|
||||
name: Option<Ident>,
|
||||
skip_memory_check: bool,
|
||||
}
|
||||
|
||||
impl ModuleAttributes {
|
||||
fn parse(&mut self, meta: ParseNestedMeta) -> Result<()> {
|
||||
if meta.path.is_ident("name") {
|
||||
match meta.value() {
|
||||
Ok(value) => {
|
||||
self.name = Some(value.parse::<LitStr>()?.parse()?);
|
||||
}
|
||||
Err(_) => {
|
||||
return Err(meta.error("`name` attribute must have a value"));
|
||||
}
|
||||
}
|
||||
} else if meta.path.is_ident("skip_memory_check") {
|
||||
if meta.value().is_ok() {
|
||||
return Err(meta.error("`skip_memory_check` attribute have no values"));
|
||||
}
|
||||
self.skip_memory_check = true;
|
||||
} else {
|
||||
return Err(meta.error("unsupported module attribute"));
|
||||
#[cfg(feature = "macros")]
|
||||
macro_rules! try_compile {
|
||||
($expr:expr) => {
|
||||
match $expr {
|
||||
Ok(val) => val,
|
||||
Err(err) => return err.to_compile_error().into(),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
#[proc_macro_attribute]
|
||||
pub fn lua_module(attr: TokenStream, item: TokenStream) -> TokenStream {
|
||||
let mut args = ModuleAttributes::default();
|
||||
if !attr.is_empty() {
|
||||
let args_parser = syn::meta::parser(|meta| args.parse(meta));
|
||||
parse_macro_input!(attr with args_parser);
|
||||
}
|
||||
|
||||
let func = parse_macro_input!(item as ItemFn);
|
||||
let func_name = &func.sig.ident;
|
||||
let module_name = args.name.unwrap_or_else(|| func_name.clone());
|
||||
let ext_entrypoint_name = Ident::new(&format!("luaopen_{module_name}"), Span::call_site());
|
||||
let skip_memory_check = if args.skip_memory_check {
|
||||
quote! { lua.skip_memory_check(true); }
|
||||
} else {
|
||||
quote! {}
|
||||
};
|
||||
|
||||
let wrapped = quote! {
|
||||
mlua::require_module_feature!();
|
||||
|
||||
#func
|
||||
|
||||
#[no_mangle]
|
||||
unsafe extern "C-unwind" fn #ext_entrypoint_name(state: *mut mlua::lua_State) -> ::std::os::raw::c_int {
|
||||
let lua = mlua::Lua::init_from_ptr(state);
|
||||
#skip_memory_check
|
||||
lua.entrypoint1(state, #func_name)
|
||||
}
|
||||
};
|
||||
|
||||
wrapped.into()
|
||||
}
|
||||
|
||||
#[cfg(feature = "macros")]
|
||||
fn to_ident(tt: &TokenTree) -> TokenStream2 {
|
||||
let s: TokenStream = tt.clone().into();
|
||||
s.into()
|
||||
module::lua_module(attr, item)
|
||||
}
|
||||
|
||||
#[cfg(feature = "macros")]
|
||||
#[proc_macro]
|
||||
#[proc_macro_error]
|
||||
pub fn chunk(input: TokenStream) -> TokenStream {
|
||||
let chunk = Chunk::new(input);
|
||||
|
||||
let source = chunk.source();
|
||||
|
||||
let caps_len = chunk.captures().len();
|
||||
let caps = chunk.captures().iter().map(|cap| {
|
||||
let cap_name = cap.as_rust().to_string();
|
||||
let cap = to_ident(cap.as_rust());
|
||||
quote! { env.raw_set(#cap_name, #cap)?; }
|
||||
});
|
||||
|
||||
let wrapped_code = quote! {{
|
||||
use mlua::{AsChunk, ChunkMode, Lua, Result, Table};
|
||||
use ::std::borrow::Cow;
|
||||
use ::std::cell::Cell;
|
||||
use ::std::io::Result as IoResult;
|
||||
use ::std::marker::PhantomData;
|
||||
|
||||
struct InnerChunk<'lua, F: FnOnce(&'lua Lua) -> Result<Table<'lua>>>(Cell<Option<F>>, PhantomData<&'lua ()>);
|
||||
|
||||
impl<'lua, F> AsChunk<'lua, 'static> for InnerChunk<'lua, F>
|
||||
where
|
||||
F: FnOnce(&'lua Lua) -> Result<Table<'lua>>,
|
||||
{
|
||||
fn environment(&self, lua: &'lua Lua) -> Result<Option<Table<'lua>>> {
|
||||
if #caps_len > 0 {
|
||||
if let Some(make_env) = self.0.take() {
|
||||
return make_env(lua).map(Some);
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn mode(&self) -> Option<ChunkMode> {
|
||||
Some(ChunkMode::Text)
|
||||
}
|
||||
|
||||
fn source(self) -> IoResult<Cow<'static, [u8]>> {
|
||||
Ok(Cow::Borrowed((#source).as_bytes()))
|
||||
}
|
||||
}
|
||||
|
||||
fn annotate<'a, F: FnOnce(&'a Lua) -> Result<Table<'a>>>(f: F) -> F { f }
|
||||
|
||||
let make_env = annotate(move |lua: &Lua| -> Result<Table> {
|
||||
let globals = lua.globals();
|
||||
let env = lua.create_table()?;
|
||||
let meta = lua.create_table()?;
|
||||
meta.raw_set("__index", globals.clone())?;
|
||||
meta.raw_set("__newindex", globals)?;
|
||||
|
||||
// Add captured variables
|
||||
#(#caps)*
|
||||
|
||||
env.set_metatable(Some(meta));
|
||||
Ok(env)
|
||||
});
|
||||
|
||||
InnerChunk(Cell::new(Some(make_env)), PhantomData)
|
||||
}};
|
||||
|
||||
wrapped_code.into()
|
||||
Chunk::new(input).expand().into()
|
||||
}
|
||||
|
||||
#[cfg(feature = "macros")]
|
||||
@@ -153,9 +33,23 @@ pub fn from_lua(input: TokenStream) -> TokenStream {
|
||||
from_lua::from_lua(input)
|
||||
}
|
||||
|
||||
/// Derive macro for implementing `UserData` for a Rust type.
|
||||
#[cfg(feature = "macros")]
|
||||
#[proc_macro_derive(UserData, attributes(lua))]
|
||||
pub fn userdata(item: TokenStream) -> TokenStream {
|
||||
userdata::userdata_type(item)
|
||||
}
|
||||
|
||||
/// Attribute macro for exposing impl block methods to Lua userdata.
|
||||
#[cfg(feature = "macros")]
|
||||
#[proc_macro_attribute]
|
||||
pub fn userdata_impl(attr: TokenStream, item: TokenStream) -> TokenStream {
|
||||
userdata::userdata_impl::userdata_impl(attr, item)
|
||||
}
|
||||
|
||||
#[cfg(feature = "macros")]
|
||||
mod chunk;
|
||||
#[cfg(feature = "macros")]
|
||||
mod from_lua;
|
||||
#[cfg(feature = "macros")]
|
||||
mod token;
|
||||
mod userdata;
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
use proc_macro::TokenStream;
|
||||
use proc_macro2::{Ident, Span};
|
||||
use quote::quote;
|
||||
use syn::meta::ParseNestedMeta;
|
||||
use syn::{ItemFn, LitStr, Result, parse_macro_input};
|
||||
|
||||
#[derive(Default)]
|
||||
struct ModuleAttributes {
|
||||
name: Option<Ident>,
|
||||
skip_memory_check: bool,
|
||||
}
|
||||
|
||||
impl ModuleAttributes {
|
||||
fn parse(&mut self, meta: ParseNestedMeta) -> Result<()> {
|
||||
if meta.path.is_ident("name") {
|
||||
match meta.value() {
|
||||
Ok(value) => {
|
||||
self.name = Some(value.parse::<LitStr>()?.parse()?);
|
||||
}
|
||||
Err(_) => {
|
||||
return Err(meta.error("`name` attribute must have a value"));
|
||||
}
|
||||
}
|
||||
} else if meta.path.is_ident("skip_memory_check") {
|
||||
if meta.value().is_ok() {
|
||||
return Err(meta.error("`skip_memory_check` attribute have no values"));
|
||||
}
|
||||
self.skip_memory_check = true;
|
||||
} else {
|
||||
return Err(meta.error("unsupported module attribute"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn lua_module(attr: TokenStream, item: TokenStream) -> TokenStream {
|
||||
let mut args = ModuleAttributes::default();
|
||||
if !attr.is_empty() {
|
||||
let args_parser = syn::meta::parser(|meta| args.parse(meta));
|
||||
parse_macro_input!(attr with args_parser);
|
||||
}
|
||||
|
||||
let func = parse_macro_input!(item as ItemFn);
|
||||
let func_name = &func.sig.ident;
|
||||
let module_name = args.name.unwrap_or_else(|| func_name.clone());
|
||||
let ext_entrypoint_name = Ident::new(&format!("luaopen_{module_name}"), Span::call_site());
|
||||
let skip_memory_check = if args.skip_memory_check {
|
||||
quote! { lua.skip_memory_check(true); }
|
||||
} else {
|
||||
quote! {}
|
||||
};
|
||||
|
||||
let wrapped = quote! {
|
||||
mlua::require_module_feature!();
|
||||
|
||||
#func
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
unsafe extern "C-unwind" fn #ext_entrypoint_name(state: *mut mlua::lua_State) -> ::std::os::raw::c_int {
|
||||
mlua::Lua::entrypoint1(state, move |lua| {
|
||||
#skip_memory_check
|
||||
#func_name(lua)
|
||||
})
|
||||
}
|
||||
};
|
||||
|
||||
wrapped.into()
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
use proc_macro2::Span;
|
||||
use syn::meta::ParseNestedMeta;
|
||||
use syn::{Ident, LitStr, Result};
|
||||
|
||||
/// Parsed `#[lua(...)]` attribute.
|
||||
///
|
||||
/// Some flags are context-dependent:
|
||||
/// - Struct fields: `get`, `set`, `name`, `skip`
|
||||
/// - Impl methods: `getter`, `setter`, `field`, `meta`, `infallible`, `name`, `skip`
|
||||
#[derive(Default)]
|
||||
pub(crate) struct LuaAttr {
|
||||
pub(crate) span: Option<Span>,
|
||||
pub(crate) name: Option<String>,
|
||||
pub(crate) infallible: bool,
|
||||
pub(crate) skip: bool,
|
||||
|
||||
// Struct field context flags
|
||||
pub(crate) get: bool,
|
||||
pub(crate) set: bool,
|
||||
|
||||
// Impl method context flags
|
||||
pub(crate) getter: bool,
|
||||
pub(crate) setter: bool,
|
||||
pub(crate) field: bool,
|
||||
pub(crate) meta: bool,
|
||||
}
|
||||
|
||||
impl LuaAttr {
|
||||
pub(crate) fn parse_inner(&mut self, meta: ParseNestedMeta) -> Result<()> {
|
||||
match &meta.path {
|
||||
path if path.is_ident("skip") => {
|
||||
if meta.value().is_ok() {
|
||||
return Err(meta.error("`skip` does not take a value"));
|
||||
}
|
||||
self.skip = true;
|
||||
}
|
||||
path if path.is_ident("infallible") => {
|
||||
if meta.value().is_ok() {
|
||||
return Err(meta.error("`infallible` does not take a value"));
|
||||
}
|
||||
self.infallible = true;
|
||||
}
|
||||
path if path.is_ident("get") => self.get = true,
|
||||
path if path.is_ident("set") => self.set = true,
|
||||
path if path.is_ident("getter") => self.getter = true,
|
||||
path if path.is_ident("setter") => self.setter = true,
|
||||
path if path.is_ident("field") => self.field = true,
|
||||
path if path.is_ident("meta") => self.meta = true,
|
||||
path if path.is_ident("name") => {
|
||||
let value = meta.value()?;
|
||||
let lit: LitStr = value.parse()?;
|
||||
self.name = Some(lit.value());
|
||||
}
|
||||
_ => {
|
||||
return Err(meta.error(
|
||||
"unsupported lua attribute, expected: ".to_string()
|
||||
+ "`skip`, `infallible`, `get`, `set`, `getter`, `setter`, `field`, `meta`, `name`",
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Returns the effective Lua name.
|
||||
pub(crate) fn name(&self, ident: &Ident) -> String {
|
||||
self.name.clone().unwrap_or_else(|| ident.to_string())
|
||||
}
|
||||
|
||||
/// Returns the span to use for error reporting.
|
||||
pub(crate) fn span(&self) -> Span {
|
||||
self.span.unwrap_or_else(Span::call_site)
|
||||
}
|
||||
|
||||
/// Returns the effective Lua metamethod name.
|
||||
///
|
||||
/// If `name` is set via attribute, use it. Otherwise, if the function name
|
||||
/// starts with `__`, use that. Returns an error if neither is available.
|
||||
pub(crate) fn effective_meta_name(&self, fn_ident: &Ident) -> Result<String> {
|
||||
if let Some(ref name) = self.name {
|
||||
return Ok(name.clone());
|
||||
}
|
||||
let fn_name = fn_ident.to_string();
|
||||
if fn_name.starts_with("__") {
|
||||
return Ok(fn_name);
|
||||
}
|
||||
Err(syn::Error::new(
|
||||
fn_ident.span(),
|
||||
format!(
|
||||
"could not infer metamethod name from `{fn_name}`, either add `name = \"...\"` to `#[lua(meta, ...)]` or prefix the function with `__`"
|
||||
),
|
||||
))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
mod attr;
|
||||
pub(crate) mod userdata_impl;
|
||||
|
||||
use proc_macro::TokenStream;
|
||||
use quote::{format_ident, quote};
|
||||
use syn::spanned::Spanned;
|
||||
use syn::{Attribute, Data, DeriveInput, Error, Fields, FieldsNamed, Meta, parse_macro_input};
|
||||
|
||||
use self::attr::LuaAttr;
|
||||
|
||||
/// Wrap registration tokens with any `#[cfg]`/`#[cfg_attr]` attributes from the original item.
|
||||
pub(crate) fn with_cfg(tokens: proc_macro2::TokenStream, attrs: &[Attribute]) -> proc_macro2::TokenStream {
|
||||
let cfgs: Vec<_> = (attrs.iter())
|
||||
.filter(|attr| attr.path().is_ident("cfg") || attr.path().is_ident("cfg_attr"))
|
||||
.collect();
|
||||
if cfgs.is_empty() {
|
||||
return tokens;
|
||||
}
|
||||
quote! {
|
||||
#(#cfgs)*
|
||||
#tokens
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse all `#[lua(...)]` attributes on a field, merging them into one `LuaAttr`.
|
||||
fn parse_field_lua_attr(attrs: &[Attribute]) -> syn::Result<LuaAttr> {
|
||||
let mut lua_attr = LuaAttr::default();
|
||||
for attr in attrs {
|
||||
if !attr.path().is_ident("lua") {
|
||||
continue;
|
||||
}
|
||||
match &attr.meta {
|
||||
Meta::List(_) => {
|
||||
lua_attr.span = Some(attr.span());
|
||||
attr.parse_nested_meta(|meta| lua_attr.parse_inner(meta))?;
|
||||
validate_field_lua_attr(&lua_attr)?;
|
||||
}
|
||||
Meta::Path(_) => {}
|
||||
Meta::NameValue(_) => {
|
||||
return Err(syn::Error::new_spanned(
|
||||
attr,
|
||||
"`#[lua = \"...\"]` is not supported: use `#[lua(attr = \"...\")]`",
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(lua_attr)
|
||||
}
|
||||
|
||||
fn validate_field_lua_attr(attr: &LuaAttr) -> syn::Result<()> {
|
||||
for (set, name) in [
|
||||
(attr.getter, "getter"),
|
||||
(attr.setter, "setter"),
|
||||
(attr.field, "field"),
|
||||
(attr.meta, "meta"),
|
||||
(attr.infallible, "infallible"),
|
||||
] {
|
||||
if set {
|
||||
return Err(syn::Error::new(
|
||||
attr.span(),
|
||||
format!("`{name}` is not valid for struct fields"),
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn userdata_type(item: TokenStream) -> TokenStream {
|
||||
let input = parse_macro_input!(item as DeriveInput);
|
||||
let type_name = &input.ident;
|
||||
|
||||
let named_fields: Option<&FieldsNamed> = match &input.data {
|
||||
Data::Struct(data) => match &data.fields {
|
||||
Fields::Named(fields) => Some(fields),
|
||||
Fields::Unnamed(_) | Fields::Unit => None,
|
||||
},
|
||||
Data::Enum(_) => None,
|
||||
Data::Union(_) => {
|
||||
return Error::new_spanned(&input, "`#[derive(UserData)]` cannot be applied to unions")
|
||||
.to_compile_error()
|
||||
.into();
|
||||
}
|
||||
};
|
||||
|
||||
// Check for generic parameters (not supported)
|
||||
let has_generics = !input.generics.params.is_empty();
|
||||
if has_generics {
|
||||
return Error::new_spanned(
|
||||
&input.generics,
|
||||
"`#[derive(UserData)]` does not support generic type parameters. Wrap the generic type in a concrete newtype instead."
|
||||
)
|
||||
.to_compile_error()
|
||||
.into();
|
||||
}
|
||||
|
||||
let mut field_registrations = Vec::new();
|
||||
if let Some(fields) = &named_fields {
|
||||
for field in &fields.named {
|
||||
let field_name = field.ident.as_ref().unwrap();
|
||||
|
||||
let lua_attr = try_compile!(parse_field_lua_attr(&field.attrs));
|
||||
if lua_attr.skip {
|
||||
continue;
|
||||
}
|
||||
|
||||
let lua_name = lua_attr.name.unwrap_or_else(|| field_name.to_string());
|
||||
|
||||
// Assume get/set by default (unless explicitly specified)
|
||||
let (has_get, has_set) = if lua_attr.get || lua_attr.set {
|
||||
(lua_attr.get, lua_attr.set)
|
||||
} else {
|
||||
(true, true)
|
||||
};
|
||||
|
||||
if has_get {
|
||||
let tokens = quote! {
|
||||
registry.add_field_method_get(#lua_name, |_lua, this| Ok(this.#field_name.clone()));
|
||||
};
|
||||
field_registrations.push(with_cfg(tokens, &field.attrs));
|
||||
}
|
||||
if has_set {
|
||||
let tokens = quote! {
|
||||
registry.add_field_method_set(#lua_name, |_lua, this, val| {
|
||||
this.#field_name = val;
|
||||
Ok(())
|
||||
});
|
||||
};
|
||||
field_registrations.push(with_cfg(tokens, &field.attrs));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let registration_type_name = format_ident!("__MluaUserDataRegistration_{type_name}");
|
||||
let register_fields_fn_name = format_ident!("__mlua_register_{type_name}_fields");
|
||||
|
||||
let output = quote! {
|
||||
#[doc(hidden)]
|
||||
#[allow(non_camel_case_types)]
|
||||
struct #registration_type_name {
|
||||
register: fn(&mut ::mlua::userdata::UserDataRegistry<#type_name>),
|
||||
}
|
||||
|
||||
::mlua::__inventory::collect!(#registration_type_name);
|
||||
|
||||
#[allow(non_snake_case)]
|
||||
fn #register_fields_fn_name(registry: &mut ::mlua::userdata::UserDataRegistry<#type_name>) {
|
||||
use ::mlua::userdata::UserDataFields as _;
|
||||
#(#field_registrations)*
|
||||
}
|
||||
|
||||
::mlua::__inventory::submit! {
|
||||
#registration_type_name { register: #register_fields_fn_name }
|
||||
}
|
||||
|
||||
impl ::mlua::userdata::UserData for #type_name {
|
||||
fn register(registry: &mut ::mlua::userdata::UserDataRegistry<Self>) {
|
||||
for item in ::mlua::__inventory::iter::<#registration_type_name> {
|
||||
(item.register)(registry);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
output.into()
|
||||
}
|
||||
@@ -0,0 +1,730 @@
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
use proc_macro::TokenStream;
|
||||
use proc_macro2::TokenStream as TokenStream2;
|
||||
use quote::{format_ident, quote};
|
||||
use syn::spanned::Spanned;
|
||||
use syn::{
|
||||
Attribute, FnArg, Ident, ImplItem, ItemImpl, Meta, Signature, Type, parse_macro_input, parse_quote,
|
||||
};
|
||||
|
||||
use super::attr::LuaAttr;
|
||||
use super::with_cfg;
|
||||
|
||||
/// `&T` reference types that mlua provides as wrapper types via `FromLua`.
|
||||
static BORROW_WRAPPERS: &[(&str, &str)] = &[
|
||||
("str", "::mlua::string::BorrowedStr"),
|
||||
("[u8]", "::mlua::string::BorrowedBytes"),
|
||||
];
|
||||
|
||||
enum SelfKind {
|
||||
Ref(RefKind),
|
||||
Owned,
|
||||
None,
|
||||
}
|
||||
|
||||
enum RefKind {
|
||||
Ref,
|
||||
Mut,
|
||||
}
|
||||
|
||||
struct ArgInfo {
|
||||
ident: Ident,
|
||||
userdata_ref: Option<RefKind>,
|
||||
callback_type: Type,
|
||||
}
|
||||
|
||||
struct MethodInfo {
|
||||
self_kind: SelfKind,
|
||||
has_lua: bool,
|
||||
args: Vec<ArgInfo>,
|
||||
}
|
||||
|
||||
/// Extract the inner type from a reference type.
|
||||
fn ref_inner_type(ty: &Type) -> Type {
|
||||
match ty {
|
||||
Type::Reference(ref_ty) => (*ref_ty.elem).clone(),
|
||||
_ => ty.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Check if the type is `&Lua` or `&mlua::Lua`.
|
||||
fn is_lua_ref(ty: &Type) -> bool {
|
||||
let Type::Reference(ref_ty) = ty else { return false };
|
||||
match &*ref_ty.elem {
|
||||
Type::Path(p) if p.path.segments.len() == 1 => p.path.segments[0].ident == "Lua",
|
||||
Type::Path(p) if p.path.segments.len() == 2 => {
|
||||
p.path.segments[0].ident == "mlua" && p.path.segments[1].ident == "Lua"
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Classify a `&[mut] T` parameter, returning the callback wrapper type.
|
||||
///
|
||||
/// Known borrow types come from the mapping table `BORROW_WRAPPERS`.
|
||||
/// Everything else gets `UserDataRef[Mut]<T>`.
|
||||
fn classify_ref_type(ty: &Type) -> Option<Type> {
|
||||
let Type::Reference(ref_ty) = ty else { return None };
|
||||
|
||||
// Check known borrow wrappers:
|
||||
// - For `&T` check the path name
|
||||
// - For `&[T]` unpack the slice and format the element as `[T]` for lookup
|
||||
if ref_ty.mutability.is_none() {
|
||||
let lookup_name: Option<String> = match &*ref_ty.elem {
|
||||
Type::Path(path) => path.path.segments.last().map(|seg| seg.ident.to_string()),
|
||||
Type::Slice(slice) => {
|
||||
if let Type::Path(path) = &*slice.elem {
|
||||
path.path.segments.last().map(|seg| format!("[{}]", seg.ident))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
if let Some(ref name) = lookup_name {
|
||||
for &(inner, wrapper) in BORROW_WRAPPERS {
|
||||
if name == inner {
|
||||
let wrapper = syn::parse_str(wrapper).expect("invalid wrapper type");
|
||||
return Some(wrapper);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Mutable references to slices are not supported.
|
||||
if matches!(&*ref_ty.elem, Type::Slice(_)) && ref_ty.mutability.is_some() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let inner = ref_inner_type(ty);
|
||||
if ref_ty.mutability.is_none() {
|
||||
Some(parse_quote! { ::mlua::userdata::UserDataRef<#inner> })
|
||||
} else {
|
||||
Some(parse_quote! { ::mlua::userdata::UserDataRefMut<#inner> })
|
||||
}
|
||||
}
|
||||
|
||||
/// Analyze method signature.
|
||||
///
|
||||
/// Determine `self` kind and collect the callback arguments.
|
||||
/// Auto-detects `&Lua` as the first non-self parameter.
|
||||
fn analyze_self_and_args(sig: &Signature) -> syn::Result<MethodInfo> {
|
||||
let mut self_kind = SelfKind::None;
|
||||
let mut has_lua = false;
|
||||
let mut args = Vec::new();
|
||||
let mut check_first_typed = true;
|
||||
|
||||
for param in &sig.inputs {
|
||||
match param {
|
||||
FnArg::Receiver(recv) if recv.reference.is_some() && recv.mutability.is_some() => {
|
||||
self_kind = SelfKind::Ref(RefKind::Mut);
|
||||
}
|
||||
FnArg::Receiver(recv) if recv.reference.is_some() => {
|
||||
self_kind = SelfKind::Ref(RefKind::Ref);
|
||||
}
|
||||
FnArg::Receiver(_) => {
|
||||
self_kind = SelfKind::Owned;
|
||||
}
|
||||
FnArg::Typed(typed) => {
|
||||
if check_first_typed && is_lua_ref(&typed.ty) {
|
||||
has_lua = true;
|
||||
check_first_typed = false;
|
||||
continue;
|
||||
}
|
||||
check_first_typed = false;
|
||||
if let syn::Pat::Ident(pat_ident) = &*typed.pat {
|
||||
let arg_type = &*typed.ty;
|
||||
let ref_kind = match arg_type {
|
||||
Type::Reference(r) if r.mutability.is_some() => Some(RefKind::Mut),
|
||||
Type::Reference(_) => Some(RefKind::Ref),
|
||||
_ => None,
|
||||
};
|
||||
let callback_type = match &ref_kind {
|
||||
Some(_) => match classify_ref_type(arg_type) {
|
||||
Some(ty) => ty,
|
||||
None => {
|
||||
return Err(syn::Error::new_spanned(
|
||||
arg_type,
|
||||
"this reference type is not supported as a callback parameter",
|
||||
));
|
||||
}
|
||||
},
|
||||
None => arg_type.clone(),
|
||||
};
|
||||
args.push(ArgInfo {
|
||||
ident: pat_ident.ident.clone(),
|
||||
userdata_ref: ref_kind,
|
||||
callback_type,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(MethodInfo {
|
||||
self_kind,
|
||||
has_lua,
|
||||
args,
|
||||
})
|
||||
}
|
||||
|
||||
fn strip_item_attrs(attrs: &[Attribute]) -> Vec<Attribute> {
|
||||
(attrs.iter())
|
||||
.filter(|attr| !attr.path().is_ident("lua"))
|
||||
.cloned()
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn parse_lua_attr(attrs: &[Attribute]) -> syn::Result<LuaAttr> {
|
||||
let mut lua_attr = LuaAttr::default();
|
||||
for attr in attrs {
|
||||
if !attr.path().is_ident("lua") {
|
||||
continue;
|
||||
}
|
||||
match &attr.meta {
|
||||
Meta::List(_) => {
|
||||
lua_attr.span = Some(attr.span());
|
||||
attr.parse_nested_meta(|meta| lua_attr.parse_inner(meta))?;
|
||||
validate_lua_attr(&lua_attr)?;
|
||||
}
|
||||
Meta::Path(_) => {}
|
||||
Meta::NameValue(_) => {
|
||||
return Err(syn::Error::new_spanned(
|
||||
attr,
|
||||
"`#[lua = \"...\"]` is not supported: use `#[lua(attr = \"...\")]`",
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(lua_attr)
|
||||
}
|
||||
|
||||
fn validate_lua_attr(attr: &LuaAttr) -> syn::Result<()> {
|
||||
for (set, name) in [(attr.get, "get"), (attr.set, "set")] {
|
||||
if set {
|
||||
return Err(syn::Error::new(
|
||||
attr.span(),
|
||||
format!("`{name}` is not valid for methods"),
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn userdata_impl(attr: TokenStream, item: TokenStream) -> TokenStream {
|
||||
if !attr.is_empty() {
|
||||
return syn::Error::new_spanned(
|
||||
proc_macro2::TokenStream::from(attr),
|
||||
"`#[userdata_impl]` does not accept arguments",
|
||||
)
|
||||
.to_compile_error()
|
||||
.into();
|
||||
}
|
||||
|
||||
let mut input = parse_macro_input!(item as ItemImpl);
|
||||
|
||||
let type_path = match &*input.self_ty {
|
||||
Type::Path(type_path) => &type_path.path,
|
||||
_ => {
|
||||
return syn::Error::new_spanned(&input.self_ty, "`#[userdata_impl]` requires a simple path type")
|
||||
.to_compile_error()
|
||||
.into();
|
||||
}
|
||||
};
|
||||
let type_name = (type_path.segments)
|
||||
.last()
|
||||
.map(|seg| seg.ident.clone())
|
||||
.ok_or_else(|| syn::Error::new_spanned(&input.self_ty, "cannot determine type name"));
|
||||
let type_name = try_compile!(type_name);
|
||||
|
||||
static COUNTER: AtomicUsize = AtomicUsize::new(0);
|
||||
let unique_suffix = COUNTER.fetch_add(1, Ordering::Relaxed);
|
||||
let register_fn_name = format_ident!("__mlua_register_{type_name}_{unique_suffix}");
|
||||
let registration_type_name = format_ident!("__MluaUserDataRegistration_{type_name}");
|
||||
|
||||
let mut registration_calls = Vec::new();
|
||||
for item in &input.items {
|
||||
match item {
|
||||
ImplItem::Const(const_item) => {
|
||||
let lua_attr = try_compile!(parse_lua_attr(&const_item.attrs));
|
||||
if lua_attr.skip {
|
||||
continue;
|
||||
}
|
||||
if lua_attr.getter || lua_attr.setter {
|
||||
return syn::Error::new(
|
||||
lua_attr.span(),
|
||||
"const items do not support `getter` or `setter`",
|
||||
)
|
||||
.to_compile_error()
|
||||
.into();
|
||||
}
|
||||
let const_name = &const_item.ident;
|
||||
let lua_name = lua_attr.name(const_name);
|
||||
if lua_attr.meta {
|
||||
let tokens = quote! {
|
||||
registry.add_meta_field(#lua_name, #type_path::#const_name);
|
||||
};
|
||||
registration_calls.push(with_cfg(tokens, &const_item.attrs));
|
||||
} else {
|
||||
let tokens = quote! {
|
||||
registry.add_field(#lua_name, #type_path::#const_name);
|
||||
};
|
||||
registration_calls.push(with_cfg(tokens, &const_item.attrs));
|
||||
}
|
||||
}
|
||||
ImplItem::Fn(method) => {
|
||||
let lua_attr = try_compile!(parse_lua_attr(&method.attrs));
|
||||
if lua_attr.skip {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Validate mutually exclusive role flags.
|
||||
// `getter`, `setter`, `field` are exclusive.
|
||||
// `meta` on its own means a metamethod.
|
||||
// `meta` combined with `field` means a meta static field.
|
||||
// `meta` with `getter` or `setter` is invalid.
|
||||
let primary = [lua_attr.getter, lua_attr.setter, lua_attr.field];
|
||||
let primary_count = primary.iter().filter(|&&x| x).count();
|
||||
if primary_count > 1 {
|
||||
return syn::Error::new(
|
||||
lua_attr.span(),
|
||||
"at most one of `getter`, `setter`, `field` can be specified",
|
||||
)
|
||||
.to_compile_error()
|
||||
.into();
|
||||
}
|
||||
if lua_attr.meta && primary_count == 1 && !lua_attr.field {
|
||||
return syn::Error::new(lua_attr.span(), "`meta` can only be combined with `field`")
|
||||
.to_compile_error()
|
||||
.into();
|
||||
}
|
||||
|
||||
let fn_name = &method.sig.ident;
|
||||
let info = try_compile!(analyze_self_and_args(&method.sig));
|
||||
let is_async = method.sig.asyncness.is_some();
|
||||
|
||||
if lua_attr.getter {
|
||||
if is_async {
|
||||
return syn::Error::new_spanned(&method.sig, "async field getter is not supported")
|
||||
.to_compile_error()
|
||||
.into();
|
||||
}
|
||||
if !matches!(info.self_kind, SelfKind::Ref(RefKind::Ref)) {
|
||||
return syn::Error::new_spanned(&method.sig, "field getter must take `&self`")
|
||||
.to_compile_error()
|
||||
.into();
|
||||
}
|
||||
if !info.args.is_empty() {
|
||||
return syn::Error::new_spanned(
|
||||
&method.sig,
|
||||
"field getter must not take additional arguments",
|
||||
)
|
||||
.to_compile_error()
|
||||
.into();
|
||||
}
|
||||
let tokens = gen_field_getter(type_path, fn_name, &lua_attr, &info);
|
||||
registration_calls.push(with_cfg(tokens, &method.attrs));
|
||||
continue;
|
||||
}
|
||||
if lua_attr.setter {
|
||||
if is_async {
|
||||
return syn::Error::new_spanned(&method.sig, "async field setter is not supported")
|
||||
.to_compile_error()
|
||||
.into();
|
||||
}
|
||||
if !matches!(info.self_kind, SelfKind::Ref(_)) {
|
||||
return syn::Error::new_spanned(&method.sig, "field setter must take `&[mut] self`")
|
||||
.to_compile_error()
|
||||
.into();
|
||||
}
|
||||
if info.args.len() != 1 {
|
||||
return syn::Error::new_spanned(
|
||||
&method.sig,
|
||||
"field setter must take exactly one value argument",
|
||||
)
|
||||
.to_compile_error()
|
||||
.into();
|
||||
}
|
||||
let tokens = gen_field_setter(type_path, fn_name, &lua_attr, &info);
|
||||
registration_calls.push(with_cfg(tokens, &method.attrs));
|
||||
continue;
|
||||
}
|
||||
if lua_attr.field {
|
||||
if is_async {
|
||||
return syn::Error::new_spanned(&method.sig, "async field function is not supported")
|
||||
.to_compile_error()
|
||||
.into();
|
||||
}
|
||||
if !matches!(info.self_kind, SelfKind::None) {
|
||||
return syn::Error::new_spanned(&method.sig, "field function must not take `self`")
|
||||
.to_compile_error()
|
||||
.into();
|
||||
}
|
||||
if !info.args.is_empty() {
|
||||
return syn::Error::new_spanned(
|
||||
&method.sig,
|
||||
"field function must not take arguments",
|
||||
)
|
||||
.to_compile_error()
|
||||
.into();
|
||||
}
|
||||
let lua_name = lua_attr.name(fn_name);
|
||||
if lua_attr.meta {
|
||||
let tokens = quote! {
|
||||
registry.add_meta_field(#lua_name, #type_path::#fn_name());
|
||||
};
|
||||
registration_calls.push(with_cfg(tokens, &method.attrs));
|
||||
} else {
|
||||
let tokens = quote! {
|
||||
registry.add_field(#lua_name, #type_path::#fn_name());
|
||||
};
|
||||
registration_calls.push(with_cfg(tokens, &method.attrs));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if lua_attr.meta {
|
||||
if matches!(info.self_kind, SelfKind::Owned) {
|
||||
return syn::Error::new_spanned(
|
||||
&method.sig,
|
||||
"meta methods cannot take `self`, use `&[mut] self` instead",
|
||||
)
|
||||
.to_compile_error()
|
||||
.into();
|
||||
}
|
||||
if is_async {
|
||||
let tokens = gen_async_meta(type_path, fn_name, &lua_attr, &info);
|
||||
registration_calls.push(with_cfg(tokens, &method.attrs));
|
||||
} else {
|
||||
let tokens = gen_meta(type_path, fn_name, &lua_attr, &info);
|
||||
registration_calls.push(with_cfg(tokens, &method.attrs));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if is_async {
|
||||
let tokens = gen_async_regular_method(type_path, fn_name, &lua_attr, &info);
|
||||
registration_calls.push(with_cfg(tokens, &method.attrs));
|
||||
} else {
|
||||
let tokens = gen_regular_method(type_path, fn_name, &lua_attr, &info);
|
||||
registration_calls.push(with_cfg(tokens, &method.attrs));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
for item in &mut input.items {
|
||||
match item {
|
||||
ImplItem::Const(c) => c.attrs = strip_item_attrs(&c.attrs),
|
||||
ImplItem::Fn(m) => m.attrs = strip_item_attrs(&m.attrs),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
input.attrs = strip_item_attrs(&input.attrs);
|
||||
|
||||
let output = quote! {
|
||||
#[allow(non_snake_case)]
|
||||
fn #register_fn_name(registry: &mut ::mlua::userdata::UserDataRegistry<#type_path>) {
|
||||
use ::mlua::userdata::{UserDataFields as _, UserDataMethods as _};
|
||||
#(#registration_calls)*
|
||||
}
|
||||
|
||||
::mlua::__inventory::submit! {
|
||||
#registration_type_name { register: #register_fn_name }
|
||||
}
|
||||
|
||||
#input
|
||||
};
|
||||
|
||||
output.into()
|
||||
}
|
||||
|
||||
/// Generate the closure argument destructuring pattern.
|
||||
fn gen_closure_destructure(info: &MethodInfo) -> TokenStream2 {
|
||||
if info.args.is_empty() {
|
||||
return quote! { () };
|
||||
}
|
||||
let idents: Vec<_> = (info.args)
|
||||
.iter()
|
||||
.map(|a| {
|
||||
let ident = &a.ident;
|
||||
if matches!(a.userdata_ref, Some(RefKind::Mut)) {
|
||||
quote! { mut #ident }
|
||||
} else {
|
||||
quote! { #ident }
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let types: Vec<_> = info.args.iter().map(|a| &a.callback_type).collect();
|
||||
quote! { (#(#idents),*): (#(#types),*) }
|
||||
}
|
||||
|
||||
/// Generate call arguments for invoking the original method.
|
||||
fn gen_call_args(info: &MethodInfo) -> TokenStream2 {
|
||||
let mut call_args: Vec<TokenStream2> = Vec::new();
|
||||
|
||||
match info.self_kind {
|
||||
SelfKind::None => {}
|
||||
_ => call_args.push(quote! { this }),
|
||||
}
|
||||
|
||||
if info.has_lua {
|
||||
call_args.push(quote! { lua });
|
||||
}
|
||||
|
||||
for arg in &info.args {
|
||||
let ident = &arg.ident;
|
||||
match arg.userdata_ref {
|
||||
Some(RefKind::Ref) => call_args.push(quote! { &*#ident }),
|
||||
Some(RefKind::Mut) => call_args.push(quote! { &mut *#ident }),
|
||||
None => call_args.push(quote! { #ident }),
|
||||
}
|
||||
}
|
||||
|
||||
quote! { #(#call_args),* }
|
||||
}
|
||||
|
||||
/// Generate call arguments for invoking the original async method.
|
||||
fn gen_async_call_args(info: &MethodInfo) -> TokenStream2 {
|
||||
let mut call_args: Vec<TokenStream2> = Vec::new();
|
||||
|
||||
match info.self_kind {
|
||||
SelfKind::None => {}
|
||||
SelfKind::Ref(RefKind::Ref) => call_args.push(quote! { &this }),
|
||||
SelfKind::Ref(RefKind::Mut) => call_args.push(quote! { &mut this }),
|
||||
SelfKind::Owned => call_args.push(quote! { this }),
|
||||
}
|
||||
|
||||
if info.has_lua {
|
||||
call_args.push(quote! { lua });
|
||||
}
|
||||
|
||||
for arg in &info.args {
|
||||
let ident = &arg.ident;
|
||||
match arg.userdata_ref {
|
||||
Some(RefKind::Ref) => call_args.push(quote! { &*#ident }),
|
||||
Some(RefKind::Mut) => call_args.push(quote! { &mut *#ident }),
|
||||
None => call_args.push(quote! { #ident }),
|
||||
}
|
||||
}
|
||||
|
||||
quote! { #(#call_args),* }
|
||||
}
|
||||
|
||||
/// Generate the closure params for the registration callback.
|
||||
fn gen_closure_params(info: &MethodInfo) -> TokenStream2 {
|
||||
let destructure = gen_closure_destructure(info);
|
||||
match info.self_kind {
|
||||
SelfKind::None => quote! { |lua, #destructure| },
|
||||
_ => quote! { |lua, this, #destructure| },
|
||||
}
|
||||
}
|
||||
|
||||
/// Generate the closure params for an async registration callback.
|
||||
fn gen_async_closure_params(info: &MethodInfo) -> TokenStream2 {
|
||||
let destructure = gen_closure_destructure(info);
|
||||
match info.self_kind {
|
||||
SelfKind::None => quote! { |lua, #destructure| },
|
||||
SelfKind::Ref(RefKind::Mut) => quote! { |lua, mut this, #destructure| },
|
||||
_ => quote! { |lua, this, #destructure| },
|
||||
}
|
||||
}
|
||||
|
||||
fn gen_field_getter(
|
||||
type_path: &syn::Path,
|
||||
fn_name: &Ident,
|
||||
lua_attr: &LuaAttr,
|
||||
info: &MethodInfo,
|
||||
) -> TokenStream2 {
|
||||
let lua_name = lua_attr.name(fn_name);
|
||||
let call_args = gen_call_args(info);
|
||||
|
||||
if lua_attr.infallible {
|
||||
return quote! {
|
||||
registry.add_field_method_get(#lua_name, |lua, this| {
|
||||
let _ = lua; // silence unused variable warning
|
||||
Ok(#type_path::#fn_name(#call_args))
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
quote! {
|
||||
registry.add_field_method_get(#lua_name, |lua, this| {
|
||||
let _ = lua; // silence unused variable warning
|
||||
#type_path::#fn_name(#call_args)
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn gen_field_setter(
|
||||
type_path: &syn::Path,
|
||||
fn_name: &Ident,
|
||||
lua_attr: &LuaAttr,
|
||||
info: &MethodInfo,
|
||||
) -> TokenStream2 {
|
||||
let lua_name = lua_attr.name(fn_name);
|
||||
let call_args = gen_call_args(info);
|
||||
|
||||
if lua_attr.infallible {
|
||||
let val_ident = info.args.first().map(|a| &a.ident);
|
||||
return quote! {
|
||||
registry.add_field_method_set(#lua_name, |lua, this, #val_ident| {
|
||||
let _ = lua; // silence unused variable warning
|
||||
Ok(#type_path::#fn_name(#call_args))
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
let val_ident = info.args.first().map(|a| &a.ident);
|
||||
quote! {
|
||||
registry.add_field_method_set(#lua_name, |lua, this, #val_ident| {
|
||||
let _ = lua; // silence unused variable warning
|
||||
#type_path::#fn_name(#call_args)
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn gen_meta(type_path: &syn::Path, fn_name: &Ident, lua_attr: &LuaAttr, info: &MethodInfo) -> TokenStream2 {
|
||||
let meta_name = match lua_attr.effective_meta_name(fn_name) {
|
||||
Ok(name) => name,
|
||||
Err(err) => return err.to_compile_error(),
|
||||
};
|
||||
let closure_params = if matches!(info.self_kind, SelfKind::None) {
|
||||
// Lua always passes `self` to the stack arg, just ignore it.
|
||||
if info.args.is_empty() {
|
||||
quote! { |lua, _this: ::mlua::AnyUserData| }
|
||||
} else {
|
||||
let idents: Vec<_> = info.args.iter().map(|a| &a.ident).collect();
|
||||
let types: Vec<_> = info.args.iter().map(|a| &a.callback_type).collect();
|
||||
quote! { |lua, (_this, #(#idents),*): (::mlua::AnyUserData, #(#types),*) | }
|
||||
}
|
||||
} else {
|
||||
gen_closure_params(info)
|
||||
};
|
||||
let call_args = gen_call_args(info);
|
||||
let fn_path = quote! { #type_path::#fn_name };
|
||||
|
||||
let body = if lua_attr.infallible {
|
||||
quote! { Ok(#fn_path(#call_args)) }
|
||||
} else {
|
||||
quote! { #fn_path(#call_args) }
|
||||
};
|
||||
match info.self_kind {
|
||||
SelfKind::None => quote! {
|
||||
registry.add_meta_function(#meta_name, #closure_params { #body });
|
||||
},
|
||||
SelfKind::Ref(RefKind::Mut) => quote! {
|
||||
registry.add_meta_method_mut(#meta_name, #closure_params { #body });
|
||||
},
|
||||
_ => quote! {
|
||||
registry.add_meta_method(#meta_name, #closure_params { #body });
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn gen_regular_method(
|
||||
type_path: &syn::Path,
|
||||
fn_name: &Ident,
|
||||
lua_attr: &LuaAttr,
|
||||
info: &MethodInfo,
|
||||
) -> TokenStream2 {
|
||||
let fn_path = quote! { #type_path::#fn_name };
|
||||
let closure_params = gen_closure_params(info);
|
||||
let call_args = gen_call_args(info);
|
||||
let lua_name = lua_attr.name(fn_name);
|
||||
|
||||
let body = if lua_attr.infallible {
|
||||
quote! { Ok(#fn_path(#call_args)) }
|
||||
} else {
|
||||
quote! { #fn_path(#call_args) }
|
||||
};
|
||||
match info.self_kind {
|
||||
SelfKind::Ref(RefKind::Ref) => quote! {
|
||||
registry.add_method(#lua_name, #closure_params { #body });
|
||||
},
|
||||
SelfKind::Ref(RefKind::Mut) => quote! {
|
||||
registry.add_method_mut(#lua_name, #closure_params { #body });
|
||||
},
|
||||
SelfKind::Owned => quote! {
|
||||
registry.add_method_once(#lua_name, #closure_params { #body });
|
||||
},
|
||||
SelfKind::None => quote! {
|
||||
registry.add_function(#lua_name, #closure_params { #body });
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn gen_async_regular_method(
|
||||
type_path: &syn::Path,
|
||||
fn_name: &Ident,
|
||||
lua_attr: &LuaAttr,
|
||||
info: &MethodInfo,
|
||||
) -> TokenStream2 {
|
||||
let fn_path = quote! { #type_path::#fn_name };
|
||||
let closure_params = gen_async_closure_params(info);
|
||||
let call_args = gen_async_call_args(info);
|
||||
let lua_name = lua_attr.name(fn_name);
|
||||
|
||||
let body = if lua_attr.infallible {
|
||||
quote! { async move { Ok(#fn_path(#call_args).await) } }
|
||||
} else {
|
||||
quote! { async move { #fn_path(#call_args).await } }
|
||||
};
|
||||
match info.self_kind {
|
||||
SelfKind::Ref(RefKind::Ref) => quote! {
|
||||
registry.add_async_method(#lua_name, #closure_params #body);
|
||||
},
|
||||
SelfKind::Ref(RefKind::Mut) => quote! {
|
||||
registry.add_async_method_mut(#lua_name, #closure_params #body);
|
||||
},
|
||||
SelfKind::Owned => quote! {
|
||||
registry.add_async_method_once(#lua_name, #closure_params #body);
|
||||
},
|
||||
SelfKind::None => quote! {
|
||||
registry.add_async_function(#lua_name, #closure_params #body);
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn gen_async_meta(
|
||||
type_path: &syn::Path,
|
||||
fn_name: &Ident,
|
||||
lua_attr: &LuaAttr,
|
||||
info: &MethodInfo,
|
||||
) -> TokenStream2 {
|
||||
let meta_name = match lua_attr.effective_meta_name(fn_name) {
|
||||
Ok(name) => name,
|
||||
Err(err) => return err.to_compile_error(),
|
||||
};
|
||||
let closure_params = if matches!(info.self_kind, SelfKind::None) {
|
||||
if info.args.is_empty() {
|
||||
quote! { |lua, _this: ::mlua::AnyUserData| }
|
||||
} else {
|
||||
let idents: Vec<_> = info.args.iter().map(|a| &a.ident).collect();
|
||||
let types: Vec<_> = info.args.iter().map(|a| &a.callback_type).collect();
|
||||
quote! { |lua, (_this, #(#idents),*): (::mlua::AnyUserData, #(#types),*) | }
|
||||
}
|
||||
} else {
|
||||
gen_async_closure_params(info)
|
||||
};
|
||||
let call_args = gen_async_call_args(info);
|
||||
let fn_path = quote! { #type_path::#fn_name };
|
||||
|
||||
let body = if lua_attr.infallible {
|
||||
quote! { async move { Ok(#fn_path(#call_args).await) } }
|
||||
} else {
|
||||
quote! { async move { #fn_path(#call_args).await } }
|
||||
};
|
||||
match info.self_kind {
|
||||
SelfKind::None => quote! {
|
||||
registry.add_async_meta_function(#meta_name, #closure_params #body);
|
||||
},
|
||||
SelfKind::Ref(RefKind::Mut) => quote! {
|
||||
registry.add_async_meta_method_mut(#meta_name, #closure_params #body);
|
||||
},
|
||||
_ => quote! {
|
||||
registry.add_async_meta_method(#meta_name, #closure_params #body);
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
imports_granularity = "Module"
|
||||
max_width = 110
|
||||
comment_width = 100
|
||||
wrap_comments = true
|
||||
+167
@@ -0,0 +1,167 @@
|
||||
use std::io;
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
use serde::ser::{Serialize, Serializer};
|
||||
|
||||
use crate::state::RawLua;
|
||||
use crate::types::ValueRef;
|
||||
|
||||
/// A Luau buffer type.
|
||||
///
|
||||
/// See the buffer [documentation] for more information.
|
||||
///
|
||||
/// [documentation]: https://luau.org/library#buffer-library
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "luau")))]
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Buffer(pub(crate) ValueRef);
|
||||
|
||||
#[cfg_attr(not(feature = "luau"), allow(unused))]
|
||||
impl Buffer {
|
||||
/// Copies the buffer data into a new `Vec<u8>`.
|
||||
pub fn to_vec(&self) -> Vec<u8> {
|
||||
let lua = self.0.lua.lock();
|
||||
self.as_slice(&lua).to_vec()
|
||||
}
|
||||
|
||||
/// Returns the length of the buffer.
|
||||
pub fn len(&self) -> usize {
|
||||
let lua = self.0.lua.lock();
|
||||
self.as_slice(&lua).len()
|
||||
}
|
||||
|
||||
/// Returns `true` if the buffer is empty.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.len() == 0
|
||||
}
|
||||
|
||||
/// Reads given number of bytes from the buffer at the given offset.
|
||||
///
|
||||
/// Offset is 0-based.
|
||||
#[track_caller]
|
||||
pub fn read_bytes<const N: usize>(&self, offset: usize) -> [u8; N] {
|
||||
let lua = self.0.lua.lock();
|
||||
let data = self.as_slice(&lua);
|
||||
let mut bytes = [0u8; N];
|
||||
bytes.copy_from_slice(&data[offset..offset + N]);
|
||||
bytes
|
||||
}
|
||||
|
||||
/// Writes given bytes to the buffer at the given offset.
|
||||
///
|
||||
/// Offset is 0-based.
|
||||
#[track_caller]
|
||||
pub fn write_bytes(&self, offset: usize, bytes: &[u8]) {
|
||||
let lua = self.0.lua.lock();
|
||||
let data = self.as_slice_mut(&lua);
|
||||
data[offset..offset + bytes.len()].copy_from_slice(bytes);
|
||||
}
|
||||
|
||||
/// Returns an adaptor implementing [`io::Read`], [`io::Write`] and [`io::Seek`] over the
|
||||
/// buffer.
|
||||
///
|
||||
/// Buffer operations are infallible, none of the read/write functions will return an Err.
|
||||
pub fn cursor(self) -> impl io::Read + io::Write + io::Seek {
|
||||
BufferCursor(self, 0)
|
||||
}
|
||||
|
||||
pub(crate) fn as_slice(&self, lua: &RawLua) -> &[u8] {
|
||||
unsafe {
|
||||
let (buf, size) = self.as_raw_parts(lua);
|
||||
std::slice::from_raw_parts(buf, size)
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::mut_from_ref)]
|
||||
fn as_slice_mut(&self, lua: &RawLua) -> &mut [u8] {
|
||||
unsafe {
|
||||
let (buf, size) = self.as_raw_parts(lua);
|
||||
std::slice::from_raw_parts_mut(buf, size)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "luau")]
|
||||
unsafe fn as_raw_parts(&self, lua: &RawLua) -> (*mut u8, usize) {
|
||||
let mut size = 0usize;
|
||||
let buf = ffi::lua_tobuffer(lua.ref_thread(), self.0.index, &mut size);
|
||||
mlua_assert!(!buf.is_null(), "invalid Luau buffer");
|
||||
(buf as *mut u8, size)
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "luau"))]
|
||||
unsafe fn as_raw_parts(&self, lua: &RawLua) -> (*mut u8, usize) {
|
||||
unreachable!()
|
||||
}
|
||||
}
|
||||
|
||||
struct BufferCursor(Buffer, usize);
|
||||
|
||||
impl io::Read for BufferCursor {
|
||||
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
|
||||
let lua = self.0.0.lua.lock();
|
||||
let data = self.0.as_slice(&lua);
|
||||
if self.1 == data.len() {
|
||||
return Ok(0);
|
||||
}
|
||||
let len = buf.len().min(data.len() - self.1);
|
||||
buf[..len].copy_from_slice(&data[self.1..self.1 + len]);
|
||||
self.1 += len;
|
||||
Ok(len)
|
||||
}
|
||||
}
|
||||
|
||||
impl io::Write for BufferCursor {
|
||||
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
|
||||
let lua = self.0.0.lua.lock();
|
||||
let data = self.0.as_slice_mut(&lua);
|
||||
if self.1 == data.len() {
|
||||
return Ok(0);
|
||||
}
|
||||
let len = buf.len().min(data.len() - self.1);
|
||||
data[self.1..self.1 + len].copy_from_slice(&buf[..len]);
|
||||
self.1 += len;
|
||||
Ok(len)
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl io::Seek for BufferCursor {
|
||||
fn seek(&mut self, pos: io::SeekFrom) -> io::Result<u64> {
|
||||
let lua = self.0.0.lua.lock();
|
||||
let data = self.0.as_slice(&lua);
|
||||
let new_offset = match pos {
|
||||
io::SeekFrom::Start(offset) => offset as i64,
|
||||
io::SeekFrom::End(offset) => data.len() as i64 + offset,
|
||||
io::SeekFrom::Current(offset) => self.1 as i64 + offset,
|
||||
};
|
||||
if new_offset < 0 {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"invalid seek to a negative position",
|
||||
));
|
||||
}
|
||||
if new_offset as usize > data.len() {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"invalid seek to a position beyond the end of the buffer",
|
||||
));
|
||||
}
|
||||
self.1 = new_offset as usize;
|
||||
Ok(self.1 as u64)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
impl Serialize for Buffer {
|
||||
fn serialize<S: Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
|
||||
let lua = self.0.lua.lock();
|
||||
serializer.serialize_bytes(self.as_slice(&lua))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "luau")]
|
||||
impl crate::types::LuaType for Buffer {
|
||||
const TYPE_ID: std::os::raw::c_int = ffi::LUA_TBUFFER;
|
||||
}
|
||||
+395
-143
@@ -1,30 +1,39 @@
|
||||
//! Lua chunk loading and execution.
|
||||
//!
|
||||
//! This module provides types for loading Lua source code or bytecode into a [`Chunk`],
|
||||
//! configuring how it is compiled and executed, and converting it into a callable [`Function`].
|
||||
//!
|
||||
//! Chunks can be loaded from strings, byte slices, or files via the [`AsChunk`] trait.
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::collections::HashMap;
|
||||
use std::ffi::CString;
|
||||
use std::io::Result as IoResult;
|
||||
use std::panic::Location;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::string::String as StdString;
|
||||
|
||||
use crate::error::{Error, ErrorContext, Result};
|
||||
use crate::error::{Error, Result};
|
||||
use crate::function::Function;
|
||||
use crate::lua::Lua;
|
||||
use crate::state::{Lua, WeakLua};
|
||||
use crate::table::Table;
|
||||
use crate::value::{FromLuaMulti, IntoLua, IntoLuaMulti};
|
||||
use crate::traits::{FromLuaMulti, IntoLua, IntoLuaMulti};
|
||||
use crate::value::Value;
|
||||
|
||||
/// Trait for types [loadable by Lua] and convertible to a [`Chunk`]
|
||||
///
|
||||
/// [loadable by Lua]: https://www.lua.org/manual/5.4/manual.html#3.3.2
|
||||
/// [`Chunk`]: crate::Chunk
|
||||
pub trait AsChunk<'lua, 'a> {
|
||||
pub trait AsChunk {
|
||||
/// Returns optional chunk name
|
||||
fn name(&self) -> Option<StdString> {
|
||||
///
|
||||
/// See [`Chunk::set_name`] for possible name prefixes.
|
||||
fn name(&self) -> Option<String> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Returns optional chunk [environment]
|
||||
///
|
||||
/// [environment]: https://www.lua.org/manual/5.4/manual.html#2.2
|
||||
fn environment(&self, lua: &'lua Lua) -> Result<Option<Table<'lua>>> {
|
||||
fn environment(&self, lua: &Lua) -> Result<Option<Table>> {
|
||||
let _lua = lua; // suppress warning
|
||||
Ok(None)
|
||||
}
|
||||
@@ -35,73 +44,106 @@ pub trait AsChunk<'lua, 'a> {
|
||||
}
|
||||
|
||||
/// Returns chunk data (can be text or binary)
|
||||
fn source(self) -> IoResult<Cow<'a, [u8]>>;
|
||||
fn source<'a>(&self) -> IoResult<Cow<'a, [u8]>>
|
||||
where
|
||||
Self: 'a;
|
||||
}
|
||||
|
||||
impl<'a> AsChunk<'_, 'a> for &'a str {
|
||||
fn source(self) -> IoResult<Cow<'a, [u8]>> {
|
||||
Ok(Cow::Borrowed(self.as_ref()))
|
||||
}
|
||||
}
|
||||
|
||||
impl AsChunk<'_, 'static> for StdString {
|
||||
fn source(self) -> IoResult<Cow<'static, [u8]>> {
|
||||
Ok(Cow::Owned(self.into_bytes()))
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> AsChunk<'_, 'a> for &'a StdString {
|
||||
fn source(self) -> IoResult<Cow<'a, [u8]>> {
|
||||
impl AsChunk for &str {
|
||||
fn source<'a>(&self) -> IoResult<Cow<'a, [u8]>>
|
||||
where
|
||||
Self: 'a,
|
||||
{
|
||||
Ok(Cow::Borrowed(self.as_bytes()))
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> AsChunk<'_, 'a> for &'a [u8] {
|
||||
fn source(self) -> IoResult<Cow<'a, [u8]>> {
|
||||
impl AsChunk for String {
|
||||
fn source<'a>(&self) -> IoResult<Cow<'a, [u8]>> {
|
||||
Ok(Cow::Owned(self.clone().into_bytes()))
|
||||
}
|
||||
}
|
||||
|
||||
impl AsChunk for &String {
|
||||
fn source<'a>(&self) -> IoResult<Cow<'a, [u8]>>
|
||||
where
|
||||
Self: 'a,
|
||||
{
|
||||
Ok(Cow::Borrowed(self.as_bytes()))
|
||||
}
|
||||
}
|
||||
|
||||
impl AsChunk for &[u8] {
|
||||
fn source<'a>(&self) -> IoResult<Cow<'a, [u8]>>
|
||||
where
|
||||
Self: 'a,
|
||||
{
|
||||
Ok(Cow::Borrowed(self))
|
||||
}
|
||||
}
|
||||
|
||||
impl AsChunk<'_, 'static> for Vec<u8> {
|
||||
fn source(self) -> IoResult<Cow<'static, [u8]>> {
|
||||
Ok(Cow::Owned(self))
|
||||
impl AsChunk for Vec<u8> {
|
||||
fn source<'a>(&self) -> IoResult<Cow<'a, [u8]>> {
|
||||
Ok(Cow::Owned(self.clone()))
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> AsChunk<'_, 'a> for &'a Vec<u8> {
|
||||
fn source(self) -> IoResult<Cow<'a, [u8]>> {
|
||||
Ok(Cow::Borrowed(self.as_ref()))
|
||||
impl AsChunk for &Vec<u8> {
|
||||
fn source<'a>(&self) -> IoResult<Cow<'a, [u8]>>
|
||||
where
|
||||
Self: 'a,
|
||||
{
|
||||
Ok(Cow::Borrowed(self))
|
||||
}
|
||||
}
|
||||
|
||||
impl AsChunk<'_, 'static> for &Path {
|
||||
fn name(&self) -> Option<StdString> {
|
||||
impl AsChunk for &Path {
|
||||
fn name(&self) -> Option<String> {
|
||||
Some(format!("@{}", self.display()))
|
||||
}
|
||||
|
||||
fn source(self) -> IoResult<Cow<'static, [u8]>> {
|
||||
fn source<'a>(&self) -> IoResult<Cow<'a, [u8]>> {
|
||||
std::fs::read(self).map(Cow::Owned)
|
||||
}
|
||||
}
|
||||
|
||||
impl AsChunk<'_, 'static> for PathBuf {
|
||||
fn name(&self) -> Option<StdString> {
|
||||
impl AsChunk for PathBuf {
|
||||
fn name(&self) -> Option<String> {
|
||||
Some(format!("@{}", self.display()))
|
||||
}
|
||||
|
||||
fn source(self) -> IoResult<Cow<'static, [u8]>> {
|
||||
fn source<'a>(&self) -> IoResult<Cow<'a, [u8]>> {
|
||||
std::fs::read(self).map(Cow::Owned)
|
||||
}
|
||||
}
|
||||
|
||||
impl<C: AsChunk + ?Sized> AsChunk for Box<C> {
|
||||
fn name(&self) -> Option<String> {
|
||||
(**self).name()
|
||||
}
|
||||
|
||||
fn environment(&self, lua: &Lua) -> Result<Option<Table>> {
|
||||
(**self).environment(lua)
|
||||
}
|
||||
|
||||
fn mode(&self) -> Option<ChunkMode> {
|
||||
(**self).mode()
|
||||
}
|
||||
|
||||
fn source<'a>(&self) -> IoResult<Cow<'a, [u8]>>
|
||||
where
|
||||
Self: 'a,
|
||||
{
|
||||
(**self).source()
|
||||
}
|
||||
}
|
||||
|
||||
/// Returned from [`Lua::load`] and is used to finalize loading and executing Lua main chunks.
|
||||
///
|
||||
/// [`Lua::load`]: crate::Lua::load
|
||||
#[must_use = "`Chunk`s do nothing unless one of `exec`, `eval`, `call`, or `into_function` are called on them"]
|
||||
pub struct Chunk<'lua, 'a> {
|
||||
pub(crate) lua: &'lua Lua,
|
||||
pub(crate) name: StdString,
|
||||
pub(crate) env: Result<Option<Table<'lua>>>,
|
||||
pub struct Chunk<'a> {
|
||||
pub(crate) lua: WeakLua,
|
||||
pub(crate) name: String,
|
||||
pub(crate) env: Result<Option<Table>>,
|
||||
pub(crate) mode: Option<ChunkMode>,
|
||||
pub(crate) source: IoResult<Cow<'a, [u8]>>,
|
||||
#[cfg(feature = "luau")]
|
||||
@@ -115,6 +157,50 @@ pub enum ChunkMode {
|
||||
Binary,
|
||||
}
|
||||
|
||||
/// Represents a constant value that can be used by Luau compiler.
|
||||
#[cfg(any(feature = "luau", doc))]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "luau")))]
|
||||
#[non_exhaustive]
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum CompileConstant {
|
||||
Nil,
|
||||
Boolean(bool),
|
||||
Number(crate::Number),
|
||||
Vector(crate::Vector),
|
||||
String(String),
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "luau", doc))]
|
||||
impl From<bool> for CompileConstant {
|
||||
fn from(b: bool) -> Self {
|
||||
CompileConstant::Boolean(b)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "luau", doc))]
|
||||
impl From<crate::Number> for CompileConstant {
|
||||
fn from(n: crate::Number) -> Self {
|
||||
CompileConstant::Number(n)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "luau", doc))]
|
||||
impl From<crate::Vector> for CompileConstant {
|
||||
fn from(v: crate::Vector) -> Self {
|
||||
CompileConstant::Vector(v)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "luau", doc))]
|
||||
impl From<&str> for CompileConstant {
|
||||
fn from(s: &str) -> Self {
|
||||
CompileConstant::String(s.to_owned())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "luau", doc))]
|
||||
type LibraryMemberConstantMap = HashMap<(String, String), CompileConstant>;
|
||||
|
||||
/// Luau compiler
|
||||
#[cfg(any(feature = "luau", doc))]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "luau")))]
|
||||
@@ -129,12 +215,15 @@ pub struct Compiler {
|
||||
vector_type: Option<String>,
|
||||
mutable_globals: Vec<String>,
|
||||
userdata_types: Vec<String>,
|
||||
libraries_with_known_members: Vec<String>,
|
||||
library_constants: Option<LibraryMemberConstantMap>,
|
||||
disabled_builtins: Vec<String>,
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "luau", doc))]
|
||||
impl Default for Compiler {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
const { Self::new() }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -153,6 +242,9 @@ impl Compiler {
|
||||
vector_type: None,
|
||||
mutable_globals: Vec::new(),
|
||||
userdata_types: Vec::new(),
|
||||
libraries_with_known_members: Vec::new(),
|
||||
library_constants: None,
|
||||
disabled_builtins: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -185,6 +277,7 @@ impl Compiler {
|
||||
/// Possible values:
|
||||
/// * 0 - generate for native modules (default)
|
||||
/// * 1 - generate for all modules
|
||||
#[must_use]
|
||||
pub const fn set_type_info_level(mut self, level: u8) -> Self {
|
||||
self.type_info_level = level;
|
||||
self
|
||||
@@ -202,20 +295,23 @@ impl Compiler {
|
||||
self
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
#[must_use]
|
||||
pub fn set_vector_lib(mut self, lib: impl Into<String>) -> Self {
|
||||
self.vector_lib = Some(lib.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets alternative global builtin to construct vectors, in addition to default builtin
|
||||
/// `vector.create`.
|
||||
///
|
||||
/// To set the library and method name, use the `lib.ctor` format.
|
||||
#[doc(hidden)]
|
||||
#[must_use]
|
||||
pub fn set_vector_ctor(mut self, ctor: impl Into<String>) -> Self {
|
||||
self.vector_ctor = Some(ctor.into());
|
||||
let ctor = ctor.into();
|
||||
let lib_ctor = ctor.split_once('.');
|
||||
self.vector_lib = lib_ctor.as_ref().map(|&(lib, _)| lib.to_owned());
|
||||
self.vector_ctor = (lib_ctor.as_ref())
|
||||
.map(|&(_, ctor)| ctor.to_owned())
|
||||
.or(Some(ctor));
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets alternative vector type name for type tables, in addition to default type `vector`.
|
||||
#[doc(hidden)]
|
||||
#[must_use]
|
||||
pub fn set_vector_type(mut self, r#type: impl Into<String>) -> Self {
|
||||
@@ -223,25 +319,86 @@ impl Compiler {
|
||||
self
|
||||
}
|
||||
|
||||
/// Adds a mutable global.
|
||||
///
|
||||
/// It disables the import optimization for fields accessed through it.
|
||||
#[must_use]
|
||||
pub fn add_mutable_global(mut self, global: impl Into<String>) -> Self {
|
||||
self.mutable_globals.push(global.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets a list of globals that are mutable.
|
||||
///
|
||||
/// It disables the import optimization for fields accessed through these.
|
||||
#[must_use]
|
||||
pub fn set_mutable_globals(mut self, globals: Vec<String>) -> Self {
|
||||
self.mutable_globals = globals;
|
||||
pub fn set_mutable_globals<S: Into<String>>(mut self, globals: impl IntoIterator<Item = S>) -> Self {
|
||||
self.mutable_globals = globals.into_iter().map(|s| s.into()).collect();
|
||||
self
|
||||
}
|
||||
|
||||
/// Adds a userdata type to the list that will be included in the type information.
|
||||
#[must_use]
|
||||
pub fn add_userdata_type(mut self, r#type: impl Into<String>) -> Self {
|
||||
self.userdata_types.push(r#type.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets a list of userdata types that will be included in the type information.
|
||||
#[must_use]
|
||||
pub fn set_userdata_types(mut self, types: Vec<String>) -> Self {
|
||||
self.userdata_types = types;
|
||||
pub fn set_userdata_types<S: Into<String>>(mut self, types: impl IntoIterator<Item = S>) -> Self {
|
||||
self.userdata_types = types.into_iter().map(|s| s.into()).collect();
|
||||
self
|
||||
}
|
||||
|
||||
/// Adds a constant for a known library member.
|
||||
///
|
||||
/// The constants are used by the compiler to optimize the generated bytecode.
|
||||
/// Optimization level must be at least 2 for this to have any effect.
|
||||
///
|
||||
/// The `name` is a string in the format `lib.member`, where `lib` is the library name
|
||||
/// and `member` is the member (constant) name.
|
||||
#[must_use]
|
||||
pub fn add_library_constant(
|
||||
mut self,
|
||||
name: impl AsRef<str>,
|
||||
r#const: impl Into<CompileConstant>,
|
||||
) -> Self {
|
||||
let Some((lib, member)) = name.as_ref().split_once('.') else {
|
||||
return self;
|
||||
};
|
||||
let (lib, member) = (lib.to_owned(), member.to_owned());
|
||||
|
||||
if !self.libraries_with_known_members.contains(&lib) {
|
||||
self.libraries_with_known_members.push(lib.clone());
|
||||
}
|
||||
self.library_constants
|
||||
.get_or_insert_default()
|
||||
.insert((lib, member), r#const.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Adds a builtin that should be disabled.
|
||||
#[must_use]
|
||||
pub fn add_disabled_builtin(mut self, builtin: impl Into<String>) -> Self {
|
||||
self.disabled_builtins.push(builtin.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets a list of builtins that should be disabled.
|
||||
#[must_use]
|
||||
pub fn set_disabled_builtins<S: Into<String>>(mut self, builtins: impl IntoIterator<Item = S>) -> Self {
|
||||
self.disabled_builtins = builtins.into_iter().map(|s| s.into()).collect();
|
||||
self
|
||||
}
|
||||
|
||||
/// Compiles the `source` into bytecode.
|
||||
pub fn compile(&self, source: impl AsRef<[u8]>) -> Vec<u8> {
|
||||
use std::os::raw::c_int;
|
||||
///
|
||||
/// Returns [`Error::SyntaxError`] if the source code is invalid.
|
||||
pub fn compile(&self, source: impl AsRef<[u8]>) -> Result<Vec<u8>> {
|
||||
use std::cell::RefCell;
|
||||
use std::ffi::CStr;
|
||||
use std::os::raw::{c_char, c_int};
|
||||
use std::ptr;
|
||||
|
||||
let vector_lib = self.vector_lib.clone();
|
||||
@@ -273,8 +430,46 @@ impl Compiler {
|
||||
|
||||
vec2cstring_ptr!(mutable_globals, mutable_globals_ptr);
|
||||
vec2cstring_ptr!(userdata_types, userdata_types_ptr);
|
||||
vec2cstring_ptr!(libraries_with_known_members, libraries_with_known_members_ptr);
|
||||
vec2cstring_ptr!(disabled_builtins, disabled_builtins_ptr);
|
||||
|
||||
unsafe {
|
||||
thread_local! {
|
||||
static LIBRARY_MEMBER_CONSTANT_MAP: RefCell<LibraryMemberConstantMap> = Default::default();
|
||||
}
|
||||
|
||||
#[cfg(feature = "luau")]
|
||||
unsafe extern "C-unwind" fn library_member_constant_callback(
|
||||
library: *const c_char,
|
||||
member: *const c_char,
|
||||
constant: *mut ffi::lua_CompileConstant,
|
||||
) {
|
||||
let library = CStr::from_ptr(library).to_string_lossy();
|
||||
let member = CStr::from_ptr(member).to_string_lossy();
|
||||
LIBRARY_MEMBER_CONSTANT_MAP.with_borrow(|map| {
|
||||
if let Some(cons) = map.get(&(library.to_string(), member.to_string())) {
|
||||
match cons {
|
||||
CompileConstant::Nil => ffi::luau_set_compile_constant_nil(constant),
|
||||
CompileConstant::Boolean(b) => {
|
||||
ffi::luau_set_compile_constant_boolean(constant, *b as c_int)
|
||||
}
|
||||
CompileConstant::Number(n) => ffi::luau_set_compile_constant_number(constant, *n),
|
||||
CompileConstant::Vector(v) => {
|
||||
#[cfg(not(feature = "luau-vector4"))]
|
||||
ffi::luau_set_compile_constant_vector(constant, v.x(), v.y(), v.z(), 0.0);
|
||||
#[cfg(feature = "luau-vector4")]
|
||||
ffi::luau_set_compile_constant_vector(constant, v.x(), v.y(), v.z(), v.w());
|
||||
}
|
||||
CompileConstant::String(s) => ffi::luau_set_compile_constant_string(
|
||||
constant,
|
||||
s.as_ptr() as *const c_char,
|
||||
s.len(),
|
||||
),
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
let bytecode = unsafe {
|
||||
let mut options = ffi::lua_CompileOptions::default();
|
||||
options.optimizationLevel = self.optimization_level as c_int;
|
||||
options.debugLevel = self.debug_level as c_int;
|
||||
@@ -285,22 +480,57 @@ impl Compiler {
|
||||
options.vectorType = vector_type.map_or(ptr::null(), |s| s.as_ptr());
|
||||
options.mutableGlobals = mutable_globals_ptr;
|
||||
options.userdataTypes = userdata_types_ptr;
|
||||
options.librariesWithKnownMembers = libraries_with_known_members_ptr;
|
||||
if let Some(map) = self.library_constants.as_ref()
|
||||
&& !self.libraries_with_known_members.is_empty()
|
||||
{
|
||||
LIBRARY_MEMBER_CONSTANT_MAP.with_borrow_mut(|gmap| *gmap = map.clone());
|
||||
options.libraryMemberConstantCallback = Some(library_member_constant_callback);
|
||||
}
|
||||
options.disabledBuiltins = disabled_builtins_ptr;
|
||||
ffi::luau_compile(source.as_ref(), options)
|
||||
};
|
||||
|
||||
if bytecode.first() == Some(&0) {
|
||||
// The rest of the bytecode is the error message starting with `:`
|
||||
// See https://github.com/luau-lang/luau/blob/0.640/Compiler/src/Compiler.cpp#L4336
|
||||
let message = String::from_utf8_lossy(&bytecode[2..]).into_owned();
|
||||
return Err(Error::SyntaxError {
|
||||
incomplete_input: message.ends_with("<eof>"),
|
||||
message,
|
||||
});
|
||||
}
|
||||
|
||||
Ok(bytecode)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'lua, 'a> Chunk<'lua, 'a> {
|
||||
impl Chunk<'_> {
|
||||
/// Returns the name of this chunk.
|
||||
pub fn name(&self) -> &str {
|
||||
&self.name
|
||||
}
|
||||
|
||||
/// Sets the name of this chunk, which results in more informative error traces.
|
||||
///
|
||||
/// Possible name prefixes:
|
||||
/// - `@` - file path (when truncation is needed, the end of the file path is kept, as this is
|
||||
/// more useful for identifying the file)
|
||||
/// - `=` - custom chunk name (when truncation is needed, the beginning of the name is kept)
|
||||
pub fn set_name(mut self, name: impl Into<String>) -> Self {
|
||||
self.name = name.into();
|
||||
self
|
||||
}
|
||||
|
||||
/// Returns the environment of this chunk.
|
||||
pub fn environment(&self) -> Option<&Table> {
|
||||
self.env.as_ref().ok()?.as_ref()
|
||||
}
|
||||
|
||||
/// Sets the environment of the loaded chunk to the given value.
|
||||
///
|
||||
/// In Lua >=5.2 main chunks always have exactly one upvalue, and this upvalue is used as the `_ENV`
|
||||
/// variable inside the chunk. By default this value is set to the global environment.
|
||||
/// In Lua >=5.2 main chunks always have exactly one upvalue, and this upvalue is used as the
|
||||
/// `_ENV` variable inside the chunk. By default this value is set to the global environment.
|
||||
///
|
||||
/// Calling this method changes the `_ENV` upvalue to the value provided, and variables inside
|
||||
/// the chunk will refer to the given environment rather than the global one.
|
||||
@@ -308,14 +538,16 @@ impl<'lua, 'a> Chunk<'lua, 'a> {
|
||||
/// All global variables (including the standard library!) are looked up in `_ENV`, so it may be
|
||||
/// necessary to populate the environment in order for scripts using custom environments to be
|
||||
/// useful.
|
||||
pub fn set_environment<V: IntoLua<'lua>>(mut self, env: V) -> Self {
|
||||
self.env = env
|
||||
.into_lua(self.lua)
|
||||
.and_then(|val| self.lua.unpack(val))
|
||||
.context("bad environment value");
|
||||
pub fn set_environment(mut self, env: Table) -> Self {
|
||||
self.env = Ok(Some(env));
|
||||
self
|
||||
}
|
||||
|
||||
/// Returns the mode (auto-detected by default) of this chunk.
|
||||
pub fn mode(&self) -> ChunkMode {
|
||||
self.detect_mode()
|
||||
}
|
||||
|
||||
/// Sets whether the chunk is text or binary (autodetected by default).
|
||||
///
|
||||
/// Be aware, Lua does not check the consistency of the code inside binary chunks.
|
||||
@@ -328,8 +560,6 @@ impl<'lua, 'a> Chunk<'lua, 'a> {
|
||||
/// Sets or overwrites a Luau compiler used for this chunk.
|
||||
///
|
||||
/// See [`Compiler`] for details and possible options.
|
||||
///
|
||||
/// Requires `feature = "luau"`
|
||||
#[cfg(any(feature = "luau", doc))]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "luau")))]
|
||||
pub fn set_compiler(mut self, compiler: Compiler) -> Self {
|
||||
@@ -341,17 +571,14 @@ impl<'lua, 'a> Chunk<'lua, 'a> {
|
||||
///
|
||||
/// This is equivalent to calling the chunk function with no arguments and no return values.
|
||||
pub fn exec(self) -> Result<()> {
|
||||
self.call::<_, ()>(())?;
|
||||
Ok(())
|
||||
self.call(())
|
||||
}
|
||||
|
||||
/// Asynchronously execute this chunk of code.
|
||||
///
|
||||
/// See [`exec`] for more details.
|
||||
///
|
||||
/// Requires `feature = "async"`
|
||||
///
|
||||
/// [`exec`]: #method.exec
|
||||
/// [`exec`]: Chunk::exec
|
||||
#[cfg(feature = "async")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
|
||||
pub async fn exec_async(self) -> Result<()> {
|
||||
@@ -363,7 +590,7 @@ impl<'lua, 'a> Chunk<'lua, 'a> {
|
||||
/// If the chunk can be parsed as an expression, this loads and executes the chunk and returns
|
||||
/// the value that it evaluates to. Otherwise, the chunk is interpreted as a block as normal,
|
||||
/// and this is equivalent to calling `exec`.
|
||||
pub fn eval<R: FromLuaMulti<'lua>>(self) -> Result<R> {
|
||||
pub fn eval<R: FromLuaMulti>(self) -> Result<R> {
|
||||
// Bytecode is always interpreted as a statement.
|
||||
// For source code, first try interpreting the lua as an expression by adding
|
||||
// "return", then as a statement. This is the same thing the
|
||||
@@ -381,14 +608,12 @@ impl<'lua, 'a> Chunk<'lua, 'a> {
|
||||
///
|
||||
/// See [`eval`] for more details.
|
||||
///
|
||||
/// Requires `feature = "async"`
|
||||
///
|
||||
/// [`eval`]: #method.eval
|
||||
/// [`eval`]: Chunk::eval
|
||||
#[cfg(feature = "async")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
|
||||
pub async fn eval_async<R>(self) -> Result<R>
|
||||
where
|
||||
R: FromLuaMulti<'lua> + 'lua,
|
||||
R: FromLuaMulti,
|
||||
{
|
||||
if self.detect_mode() == ChunkMode::Binary {
|
||||
self.call_async(()).await
|
||||
@@ -402,7 +627,7 @@ impl<'lua, 'a> Chunk<'lua, 'a> {
|
||||
/// Load the chunk function and call it with the given arguments.
|
||||
///
|
||||
/// This is equivalent to `into_function` and calling the resulting function.
|
||||
pub fn call<A: IntoLuaMulti<'lua>, R: FromLuaMulti<'lua>>(self, args: A) -> Result<R> {
|
||||
pub fn call<R: FromLuaMulti>(self, args: impl IntoLuaMulti) -> Result<R> {
|
||||
self.into_function()?.call(args)
|
||||
}
|
||||
|
||||
@@ -410,24 +635,21 @@ impl<'lua, 'a> Chunk<'lua, 'a> {
|
||||
///
|
||||
/// See [`call`] for more details.
|
||||
///
|
||||
/// Requires `feature = "async"`
|
||||
///
|
||||
/// [`call`]: #method.call
|
||||
/// [`call`]: Chunk::call
|
||||
#[cfg(feature = "async")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
|
||||
pub async fn call_async<A, R>(self, args: A) -> Result<R>
|
||||
pub async fn call_async<R>(self, args: impl IntoLuaMulti) -> Result<R>
|
||||
where
|
||||
A: IntoLuaMulti<'lua>,
|
||||
R: FromLuaMulti<'lua> + 'lua,
|
||||
R: FromLuaMulti,
|
||||
{
|
||||
self.into_function()?.call_async(args).await
|
||||
}
|
||||
|
||||
/// Load this chunk into a regular `Function`.
|
||||
/// Load this chunk into a regular [`Function`].
|
||||
///
|
||||
/// This simply compiles the chunk without actually executing it.
|
||||
#[cfg_attr(not(feature = "luau"), allow(unused_mut))]
|
||||
pub fn into_function(mut self) -> Result<Function<'lua>> {
|
||||
pub fn into_function(mut self) -> Result<Function> {
|
||||
#[cfg(feature = "luau")]
|
||||
if self.compiler.is_some() {
|
||||
// We don't need to compile source if no compiler set
|
||||
@@ -436,30 +658,27 @@ impl<'lua, 'a> Chunk<'lua, 'a> {
|
||||
|
||||
let name = Self::convert_name(self.name)?;
|
||||
self.lua
|
||||
.load_chunk(Some(&name), self.env?, self.mode, self.source?.as_ref())
|
||||
.lock()
|
||||
.load_chunk(Some(&name), self.env?.as_ref(), self.mode, self.source?.as_ref())
|
||||
}
|
||||
|
||||
/// Compiles the chunk and changes mode to binary.
|
||||
///
|
||||
/// It does nothing if the chunk is already binary.
|
||||
/// It does nothing if the chunk is already binary or invalid.
|
||||
fn compile(&mut self) {
|
||||
if let Ok(ref source) = self.source {
|
||||
if self.detect_mode() == ChunkMode::Text {
|
||||
#[cfg(feature = "luau")]
|
||||
{
|
||||
let data = self
|
||||
.compiler
|
||||
.get_or_insert_with(Default::default)
|
||||
.compile(source);
|
||||
self.source = Ok(Cow::Owned(data));
|
||||
self.mode = Some(ChunkMode::Binary);
|
||||
}
|
||||
#[cfg(not(feature = "luau"))]
|
||||
if let Ok(func) = self.lua.load_chunk(None, None, None, source.as_ref()) {
|
||||
let data = func.dump(false);
|
||||
self.source = Ok(Cow::Owned(data));
|
||||
self.mode = Some(ChunkMode::Binary);
|
||||
}
|
||||
if let Ok(ref source) = self.source
|
||||
&& self.detect_mode() == ChunkMode::Text
|
||||
{
|
||||
#[cfg(feature = "luau")]
|
||||
if let Ok(data) = self.compiler.get_or_insert_default().compile(source) {
|
||||
self.source = Ok(Cow::Owned(data));
|
||||
self.mode = Some(ChunkMode::Binary);
|
||||
}
|
||||
#[cfg(not(feature = "luau"))]
|
||||
if let Ok(func) = self.lua.lock().load_chunk(None, None, None, source.as_ref()) {
|
||||
let data = func.dump(false);
|
||||
self.source = Ok(Cow::Owned(data));
|
||||
self.mode = Some(ChunkMode::Binary);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -472,31 +691,33 @@ impl<'lua, 'a> Chunk<'lua, 'a> {
|
||||
|
||||
// Try to fetch compiled chunk from cache
|
||||
let mut text_source = None;
|
||||
if let Ok(ref source) = self.source {
|
||||
if self.detect_mode() == ChunkMode::Text {
|
||||
if let Some(cache) = self.lua.app_data_ref::<ChunksCache>() {
|
||||
if let Some(data) = cache.0.get(source.as_ref()) {
|
||||
self.source = Ok(Cow::Owned(data.clone()));
|
||||
self.mode = Some(ChunkMode::Binary);
|
||||
return self;
|
||||
}
|
||||
}
|
||||
text_source = Some(source.as_ref().to_vec());
|
||||
if let Ok(ref source) = self.source
|
||||
&& self.detect_mode() == ChunkMode::Text
|
||||
{
|
||||
let lua = self.lua.lock();
|
||||
if let Some(cache) = lua.priv_app_data_ref::<ChunksCache>()
|
||||
&& let Some(data) = cache.0.get(source.as_ref())
|
||||
{
|
||||
self.source = Ok(Cow::Owned(data.clone()));
|
||||
self.mode = Some(ChunkMode::Binary);
|
||||
return self;
|
||||
}
|
||||
text_source = Some(source.as_ref().to_vec());
|
||||
}
|
||||
|
||||
// Compile and cache the chunk
|
||||
if let Some(text_source) = text_source {
|
||||
self.compile();
|
||||
if let Ok(ref binary_source) = self.source {
|
||||
if self.detect_mode() == ChunkMode::Binary {
|
||||
if let Some(mut cache) = self.lua.app_data_mut::<ChunksCache>() {
|
||||
cache.0.insert(text_source, binary_source.as_ref().to_vec());
|
||||
} else {
|
||||
let mut cache = ChunksCache(HashMap::new());
|
||||
cache.0.insert(text_source, binary_source.as_ref().to_vec());
|
||||
let _ = self.lua.try_set_app_data(cache);
|
||||
}
|
||||
if let Ok(ref binary_source) = self.source
|
||||
&& self.detect_mode() == ChunkMode::Binary
|
||||
{
|
||||
let lua = self.lua.lock();
|
||||
if let Some(mut cache) = lua.priv_app_data_mut::<ChunksCache>() {
|
||||
cache.0.insert(text_source, binary_source.to_vec());
|
||||
} else {
|
||||
let mut cache = ChunksCache(HashMap::new());
|
||||
cache.0.insert(text_source, binary_source.to_vec());
|
||||
lua.set_priv_app_data(cache);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -504,7 +725,7 @@ impl<'lua, 'a> Chunk<'lua, 'a> {
|
||||
self
|
||||
}
|
||||
|
||||
fn to_expression(&self) -> Result<Function<'lua>> {
|
||||
fn to_expression(&self) -> Result<Function> {
|
||||
// We assume that mode is Text
|
||||
let source = self.source.as_ref();
|
||||
let source = source.map_err(Error::runtime)?;
|
||||
@@ -515,29 +736,33 @@ impl<'lua, 'a> Chunk<'lua, 'a> {
|
||||
.compiler
|
||||
.as_ref()
|
||||
.map(|c| c.compile(&source))
|
||||
.transpose()?
|
||||
.unwrap_or(source);
|
||||
|
||||
let name = Self::convert_name(self.name.clone())?;
|
||||
self.lua
|
||||
.load_chunk(Some(&name), self.env.clone()?, None, &source)
|
||||
let env = match &self.env {
|
||||
Ok(Some(env)) => Some(env),
|
||||
Ok(None) => None,
|
||||
Err(err) => return Err(err.clone()),
|
||||
};
|
||||
self.lua.lock().load_chunk(Some(&name), env, None, &source)
|
||||
}
|
||||
|
||||
fn detect_mode(&self) -> ChunkMode {
|
||||
match (self.mode, &self.source) {
|
||||
(Some(mode), _) => mode,
|
||||
(None, Ok(source)) => {
|
||||
#[cfg(not(feature = "luau"))]
|
||||
if source.starts_with(ffi::LUA_SIGNATURE) {
|
||||
return ChunkMode::Binary;
|
||||
}
|
||||
#[cfg(feature = "luau")]
|
||||
if *source.first().unwrap_or(&u8::MAX) < b'\n' {
|
||||
return ChunkMode::Binary;
|
||||
}
|
||||
ChunkMode::Text
|
||||
}
|
||||
(None, Err(_)) => ChunkMode::Text, // any value is fine
|
||||
if let Some(mode) = self.mode {
|
||||
return mode;
|
||||
}
|
||||
if let Ok(source) = &self.source {
|
||||
#[cfg(not(feature = "luau"))]
|
||||
if source.starts_with(ffi::LUA_SIGNATURE) {
|
||||
return ChunkMode::Binary;
|
||||
}
|
||||
#[cfg(feature = "luau")]
|
||||
if *source.first().unwrap_or(&u8::MAX) < b'\n' {
|
||||
return ChunkMode::Binary;
|
||||
}
|
||||
}
|
||||
ChunkMode::Text
|
||||
}
|
||||
|
||||
fn convert_name(name: String) -> Result<CString> {
|
||||
@@ -551,3 +776,30 @@ impl<'lua, 'a> Chunk<'lua, 'a> {
|
||||
buf
|
||||
}
|
||||
}
|
||||
|
||||
struct WrappedChunk<T: AsChunk> {
|
||||
chunk: T,
|
||||
caller: &'static Location<'static>,
|
||||
}
|
||||
|
||||
impl Chunk<'_> {
|
||||
/// Wraps a chunk of Lua code, returning an opaque type that implements [`IntoLua`] trait.
|
||||
///
|
||||
/// The resulted `IntoLua` implementation will convert the chunk into a Lua function without
|
||||
/// executing it.
|
||||
#[track_caller]
|
||||
pub fn wrap(chunk: impl AsChunk) -> impl IntoLua {
|
||||
WrappedChunk {
|
||||
chunk,
|
||||
caller: Location::caller(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: AsChunk> IntoLua for WrappedChunk<T> {
|
||||
fn into_lua(self, lua: &Lua) -> Result<Value> {
|
||||
lua.load_with_location(self.chunk, self.caller)
|
||||
.into_function()
|
||||
.map(Value::Function)
|
||||
}
|
||||
}
|
||||
|
||||
+585
-537
File diff suppressed because it is too large
Load Diff
+117
-106
@@ -1,51 +1,45 @@
|
||||
//! Lua debugging interface.
|
||||
//!
|
||||
//! This module provides access to the Lua debug interface, allowing inspection of the call stack,
|
||||
//! and function information. The main types are [`struct@Debug`] for accessing debug information
|
||||
//! and [`HookTriggers`] for configuring debug hooks.
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::cell::UnsafeCell;
|
||||
#[cfg(not(feature = "luau"))]
|
||||
use std::ops::{BitOr, BitOrAssign};
|
||||
use std::os::raw::c_int;
|
||||
|
||||
use ffi::lua_Debug;
|
||||
use ffi::{lua_Debug, lua_State};
|
||||
|
||||
use crate::lua::Lua;
|
||||
use crate::util::{linenumber_to_usize, ptr_to_lossy_str, ptr_to_str};
|
||||
use crate::function::Function;
|
||||
use crate::state::RawLua;
|
||||
use crate::util::{StackGuard, assert_stack, linenumber_to_usize, ptr_to_lossy_str, ptr_to_str};
|
||||
|
||||
/// Contains information about currently executing Lua code.
|
||||
///
|
||||
/// The `Debug` structure is provided as a parameter to the hook function set with
|
||||
/// [`Lua::set_hook`]. You may call the methods on this structure to retrieve information about the
|
||||
/// Lua code executing at the time that the hook function was called. Further information can be
|
||||
/// found in the Lua [documentation][lua_doc].
|
||||
/// You may call the methods on this structure to retrieve information about the Lua code executing
|
||||
/// at the specific level. Further information can be found in the Lua [documentation].
|
||||
///
|
||||
/// [lua_doc]: https://www.lua.org/manual/5.4/manual.html#lua_Debug
|
||||
/// [`Lua::set_hook`]: crate::Lua::set_hook
|
||||
pub struct Debug<'lua> {
|
||||
lua: &'lua Lua,
|
||||
ar: ActivationRecord,
|
||||
#[cfg(feature = "luau")]
|
||||
/// [documentation]: https://www.lua.org/manual/5.4/manual.html#lua_Debug
|
||||
pub struct Debug<'a> {
|
||||
state: *mut lua_State,
|
||||
lua: &'a RawLua,
|
||||
#[cfg_attr(not(feature = "luau"), allow(unused))]
|
||||
level: c_int,
|
||||
ar: *mut lua_Debug,
|
||||
}
|
||||
|
||||
impl<'lua> Debug<'lua> {
|
||||
#[cfg(not(feature = "luau"))]
|
||||
pub(crate) fn new(lua: &'lua Lua, ar: *mut lua_Debug) -> Self {
|
||||
impl<'a> Debug<'a> {
|
||||
pub(crate) fn new(lua: &'a RawLua, level: c_int, ar: *mut lua_Debug) -> Self {
|
||||
Debug {
|
||||
state: lua.state(),
|
||||
lua,
|
||||
ar: ActivationRecord::Borrowed(ar),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn new_owned(lua: &'lua Lua, _level: c_int, ar: lua_Debug) -> Self {
|
||||
Debug {
|
||||
lua,
|
||||
ar: ActivationRecord::Owned(UnsafeCell::new(ar)),
|
||||
#[cfg(feature = "luau")]
|
||||
level: _level,
|
||||
ar,
|
||||
level,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the specific event that triggered the hook.
|
||||
///
|
||||
/// For [Lua 5.1] `DebugEvent::TailCall` is used for return events to indicate a return
|
||||
/// For [Lua 5.1] [`DebugEvent::TailCall`] is used for return events to indicate a return
|
||||
/// from a function that did a tail call.
|
||||
///
|
||||
/// [Lua 5.1]: https://www.lua.org/manual/5.1/manual.html#pdf-LUA_HOOKTAILRET
|
||||
@@ -53,7 +47,7 @@ impl<'lua> Debug<'lua> {
|
||||
#[cfg_attr(docsrs, doc(cfg(not(feature = "luau"))))]
|
||||
pub fn event(&self) -> DebugEvent {
|
||||
unsafe {
|
||||
match (*self.ar.get()).event {
|
||||
match (*self.ar).event {
|
||||
ffi::LUA_HOOKCALL => DebugEvent::Call,
|
||||
ffi::LUA_HOOKRET => DebugEvent::Ret,
|
||||
ffi::LUA_HOOKTAILCALL => DebugEvent::TailCall,
|
||||
@@ -64,24 +58,48 @@ impl<'lua> Debug<'lua> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Corresponds to the `n` what mask.
|
||||
pub fn names(&self) -> DebugNames {
|
||||
/// Returns the function that is running at the given level.
|
||||
///
|
||||
/// Corresponds to the `f` "what" mask.
|
||||
pub fn function(&self) -> Function {
|
||||
unsafe {
|
||||
let _sg = StackGuard::new(self.state);
|
||||
assert_stack(self.state, 1);
|
||||
|
||||
#[cfg(not(feature = "luau"))]
|
||||
mlua_assert!(
|
||||
ffi::lua_getinfo(self.state, cstr!("f"), self.ar) != 0,
|
||||
"lua_getinfo failed with `f`"
|
||||
);
|
||||
#[cfg(feature = "luau")]
|
||||
mlua_assert!(
|
||||
ffi::lua_getinfo(self.state, self.level, cstr!("f"), self.ar) != 0,
|
||||
"lua_getinfo failed with `f`"
|
||||
);
|
||||
|
||||
ffi::lua_xmove(self.state, self.lua.ref_thread(), 1);
|
||||
Function(self.lua.pop_ref_thread())
|
||||
}
|
||||
}
|
||||
|
||||
/// Corresponds to the `n` "what" mask.
|
||||
pub fn names(&self) -> DebugNames<'_> {
|
||||
unsafe {
|
||||
#[cfg(not(feature = "luau"))]
|
||||
mlua_assert!(
|
||||
ffi::lua_getinfo(self.lua.state(), cstr!("n"), self.ar.get()) != 0,
|
||||
ffi::lua_getinfo(self.state, cstr!("n"), self.ar) != 0,
|
||||
"lua_getinfo failed with `n`"
|
||||
);
|
||||
#[cfg(feature = "luau")]
|
||||
mlua_assert!(
|
||||
ffi::lua_getinfo(self.lua.state(), self.level, cstr!("n"), self.ar.get()) != 0,
|
||||
ffi::lua_getinfo(self.state, self.level, cstr!("n"), self.ar) != 0,
|
||||
"lua_getinfo failed with `n`"
|
||||
);
|
||||
|
||||
DebugNames {
|
||||
name: ptr_to_lossy_str((*self.ar.get()).name),
|
||||
name: ptr_to_lossy_str((*self.ar).name),
|
||||
#[cfg(not(feature = "luau"))]
|
||||
name_what: match ptr_to_str((*self.ar.get()).namewhat) {
|
||||
name_what: match ptr_to_str((*self.ar).namewhat) {
|
||||
Some("") => None,
|
||||
val => val,
|
||||
},
|
||||
@@ -91,119 +109,107 @@ impl<'lua> Debug<'lua> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Corresponds to the `S` what mask.
|
||||
pub fn source(&self) -> DebugSource {
|
||||
/// Corresponds to the `S` "what" mask.
|
||||
pub fn source(&self) -> DebugSource<'_> {
|
||||
unsafe {
|
||||
#[cfg(not(feature = "luau"))]
|
||||
mlua_assert!(
|
||||
ffi::lua_getinfo(self.lua.state(), cstr!("S"), self.ar.get()) != 0,
|
||||
ffi::lua_getinfo(self.state, cstr!("S"), self.ar) != 0,
|
||||
"lua_getinfo failed with `S`"
|
||||
);
|
||||
#[cfg(feature = "luau")]
|
||||
mlua_assert!(
|
||||
ffi::lua_getinfo(self.lua.state(), self.level, cstr!("s"), self.ar.get()) != 0,
|
||||
ffi::lua_getinfo(self.state, self.level, cstr!("s"), self.ar) != 0,
|
||||
"lua_getinfo failed with `s`"
|
||||
);
|
||||
|
||||
DebugSource {
|
||||
source: ptr_to_lossy_str((*self.ar.get()).source),
|
||||
source: ptr_to_lossy_str((*self.ar).source),
|
||||
#[cfg(not(feature = "luau"))]
|
||||
short_src: ptr_to_lossy_str((*self.ar.get()).short_src.as_ptr()),
|
||||
short_src: ptr_to_lossy_str((*self.ar).short_src.as_ptr()),
|
||||
#[cfg(feature = "luau")]
|
||||
short_src: ptr_to_lossy_str((*self.ar.get()).short_src),
|
||||
line_defined: linenumber_to_usize((*self.ar.get()).linedefined),
|
||||
short_src: ptr_to_lossy_str((*self.ar).short_src),
|
||||
line_defined: linenumber_to_usize((*self.ar).linedefined),
|
||||
#[cfg(not(feature = "luau"))]
|
||||
last_line_defined: linenumber_to_usize((*self.ar.get()).lastlinedefined),
|
||||
last_line_defined: linenumber_to_usize((*self.ar).lastlinedefined),
|
||||
#[cfg(feature = "luau")]
|
||||
last_line_defined: None,
|
||||
what: ptr_to_str((*self.ar.get()).what).unwrap_or("main"),
|
||||
what: ptr_to_str((*self.ar).what).unwrap_or("main"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Corresponds to the `l` what mask. Returns the current line.
|
||||
pub fn curr_line(&self) -> i32 {
|
||||
/// Corresponds to the `l` "what" mask. Returns the current line.
|
||||
pub fn current_line(&self) -> Option<usize> {
|
||||
unsafe {
|
||||
#[cfg(not(feature = "luau"))]
|
||||
mlua_assert!(
|
||||
ffi::lua_getinfo(self.lua.state(), cstr!("l"), self.ar.get()) != 0,
|
||||
ffi::lua_getinfo(self.state, cstr!("l"), self.ar) != 0,
|
||||
"lua_getinfo failed with `l`"
|
||||
);
|
||||
#[cfg(feature = "luau")]
|
||||
mlua_assert!(
|
||||
ffi::lua_getinfo(self.lua.state(), self.level, cstr!("l"), self.ar.get()) != 0,
|
||||
ffi::lua_getinfo(self.state, self.level, cstr!("l"), self.ar) != 0,
|
||||
"lua_getinfo failed with `l`"
|
||||
);
|
||||
|
||||
(*self.ar.get()).currentline
|
||||
linenumber_to_usize((*self.ar).currentline)
|
||||
}
|
||||
}
|
||||
|
||||
/// Corresponds to the `t` what mask. Returns true if the hook is in a function tail call, false
|
||||
/// otherwise.
|
||||
#[cfg(not(feature = "luau"))]
|
||||
#[cfg_attr(docsrs, doc(cfg(not(feature = "luau"))))]
|
||||
/// Corresponds to the `t` "what" mask. Returns true if the hook is in a function tail call,
|
||||
/// false otherwise.
|
||||
#[cfg(any(feature = "lua55", feature = "lua54", feature = "lua53", feature = "lua52"))]
|
||||
#[cfg_attr(
|
||||
docsrs,
|
||||
doc(cfg(any(feature = "lua55", feature = "lua54", feature = "lua53", feature = "lua52")))
|
||||
)]
|
||||
pub fn is_tail_call(&self) -> bool {
|
||||
unsafe {
|
||||
mlua_assert!(
|
||||
ffi::lua_getinfo(self.lua.state(), cstr!("t"), self.ar.get()) != 0,
|
||||
ffi::lua_getinfo(self.state, cstr!("t"), self.ar) != 0,
|
||||
"lua_getinfo failed with `t`"
|
||||
);
|
||||
(*self.ar.get()).currentline != 0
|
||||
(*self.ar).istailcall != 0
|
||||
}
|
||||
}
|
||||
|
||||
/// Corresponds to the `u` what mask.
|
||||
/// Corresponds to the `u` "what" mask.
|
||||
pub fn stack(&self) -> DebugStack {
|
||||
unsafe {
|
||||
#[cfg(not(feature = "luau"))]
|
||||
mlua_assert!(
|
||||
ffi::lua_getinfo(self.lua.state(), cstr!("u"), self.ar.get()) != 0,
|
||||
ffi::lua_getinfo(self.state, cstr!("u"), self.ar) != 0,
|
||||
"lua_getinfo failed with `u`"
|
||||
);
|
||||
#[cfg(feature = "luau")]
|
||||
mlua_assert!(
|
||||
ffi::lua_getinfo(self.lua.state(), self.level, cstr!("a"), self.ar.get()) != 0,
|
||||
"lua_getinfo failed with `a`"
|
||||
ffi::lua_getinfo(self.state, self.level, cstr!("au"), self.ar) != 0,
|
||||
"lua_getinfo failed with `au`"
|
||||
);
|
||||
|
||||
#[cfg(not(feature = "luau"))]
|
||||
let stack = DebugStack {
|
||||
num_ups: (*self.ar.get()).nups as _,
|
||||
#[cfg(any(feature = "lua54", feature = "lua53", feature = "lua52"))]
|
||||
num_params: (*self.ar.get()).nparams as _,
|
||||
#[cfg(any(feature = "lua54", feature = "lua53", feature = "lua52"))]
|
||||
is_vararg: (*self.ar.get()).isvararg != 0,
|
||||
num_upvalues: (*self.ar).nups as _,
|
||||
#[cfg(not(any(feature = "lua51", feature = "luajit")))]
|
||||
num_params: (*self.ar).nparams as _,
|
||||
#[cfg(not(any(feature = "lua51", feature = "luajit")))]
|
||||
is_vararg: (*self.ar).isvararg != 0,
|
||||
};
|
||||
#[cfg(feature = "luau")]
|
||||
let stack = DebugStack {
|
||||
num_ups: (*self.ar.get()).nupvals as i32,
|
||||
num_params: (*self.ar.get()).nparams as i32,
|
||||
is_vararg: (*self.ar.get()).isvararg != 0,
|
||||
num_upvalues: (*self.ar).nupvals,
|
||||
num_params: (*self.ar).nparams,
|
||||
is_vararg: (*self.ar).isvararg != 0,
|
||||
};
|
||||
stack
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum ActivationRecord {
|
||||
#[cfg(not(feature = "luau"))]
|
||||
Borrowed(*mut lua_Debug),
|
||||
Owned(UnsafeCell<lua_Debug>),
|
||||
}
|
||||
|
||||
impl ActivationRecord {
|
||||
#[inline]
|
||||
fn get(&self) -> *mut lua_Debug {
|
||||
match self {
|
||||
#[cfg(not(feature = "luau"))]
|
||||
ActivationRecord::Borrowed(x) => *x,
|
||||
ActivationRecord::Owned(x) => x.get(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents a specific event that triggered the hook.
|
||||
#[cfg(not(feature = "luau"))]
|
||||
#[cfg_attr(docsrs, doc(cfg(not(feature = "luau"))))]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum DebugEvent {
|
||||
Call,
|
||||
@@ -214,6 +220,9 @@ pub enum DebugEvent {
|
||||
Unknown(c_int),
|
||||
}
|
||||
|
||||
/// Contains the name information of a function in the call stack.
|
||||
///
|
||||
/// Returned by the [`Debug::names`] method.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct DebugNames<'a> {
|
||||
/// A (reasonable) name of the function (`None` if the name cannot be found).
|
||||
@@ -224,6 +233,9 @@ pub struct DebugNames<'a> {
|
||||
pub name_what: Option<&'static str>,
|
||||
}
|
||||
|
||||
/// Contains the source information of a function in the call stack.
|
||||
///
|
||||
/// Returned by the [`Debug::source`] method.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct DebugSource<'a> {
|
||||
/// Source of the chunk that created the function.
|
||||
@@ -234,28 +246,25 @@ pub struct DebugSource<'a> {
|
||||
pub line_defined: Option<usize>,
|
||||
/// The line number where the definition of the function ends (not set by Luau).
|
||||
pub last_line_defined: Option<usize>,
|
||||
/// A string `Lua` if the function is a Lua function, `C` if it is a C function, `main` if it is the main part of a chunk.
|
||||
/// A string `Lua` if the function is a Lua function, `C` if it is a C function, `main` if it is
|
||||
/// the main part of a chunk.
|
||||
pub what: &'static str,
|
||||
}
|
||||
|
||||
/// Contains stack information about a function in the call stack.
|
||||
///
|
||||
/// Returned by the [`Debug::stack`] method.
|
||||
#[derive(Copy, Clone, Debug)]
|
||||
pub struct DebugStack {
|
||||
pub num_ups: i32,
|
||||
/// Requires `feature = "lua54/lua53/lua52/luau"`
|
||||
#[cfg(any(
|
||||
feature = "lua54",
|
||||
feature = "lua53",
|
||||
feature = "lua52",
|
||||
feature = "luau"
|
||||
))]
|
||||
pub num_params: i32,
|
||||
/// Requires `feature = "lua54/lua53/lua52/luau"`
|
||||
#[cfg(any(
|
||||
feature = "lua54",
|
||||
feature = "lua53",
|
||||
feature = "lua52",
|
||||
feature = "luau"
|
||||
))]
|
||||
/// The number of upvalues of the function.
|
||||
pub num_upvalues: u8,
|
||||
/// The number of parameters of the function (always 0 for C).
|
||||
#[cfg(any(not(any(feature = "lua51", feature = "luajit")), doc))]
|
||||
#[cfg_attr(docsrs, doc(cfg(not(any(feature = "lua51", feature = "luajit")))))]
|
||||
pub num_params: u8,
|
||||
/// Whether the function is a variadic function (always true for C).
|
||||
#[cfg(any(not(any(feature = "lua51", feature = "luajit")), doc))]
|
||||
#[cfg_attr(docsrs, doc(cfg(not(any(feature = "lua51", feature = "luajit")))))]
|
||||
pub is_vararg: bool,
|
||||
}
|
||||
|
||||
@@ -333,6 +342,7 @@ impl HookTriggers {
|
||||
}
|
||||
|
||||
// Compute the mask to pass to `lua_sethook`.
|
||||
#[cfg(not(feature = "luau"))]
|
||||
pub(crate) const fn mask(&self) -> c_int {
|
||||
let mut mask: c_int = 0;
|
||||
if self.on_calls {
|
||||
@@ -352,6 +362,7 @@ impl HookTriggers {
|
||||
|
||||
// Returns the `count` parameter to pass to `lua_sethook`, if applicable. Otherwise, zero is
|
||||
// returned.
|
||||
#[cfg(not(feature = "luau"))]
|
||||
pub(crate) const fn count(&self) -> c_int {
|
||||
match self.every_nth_instruction {
|
||||
Some(n) => n as c_int,
|
||||
@@ -361,7 +372,7 @@ impl HookTriggers {
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "luau"))]
|
||||
impl BitOr for HookTriggers {
|
||||
impl std::ops::BitOr for HookTriggers {
|
||||
type Output = Self;
|
||||
|
||||
fn bitor(mut self, rhs: Self) -> Self::Output {
|
||||
@@ -376,7 +387,7 @@ impl BitOr for HookTriggers {
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "luau"))]
|
||||
impl BitOrAssign for HookTriggers {
|
||||
impl std::ops::BitOrAssign for HookTriggers {
|
||||
fn bitor_assign(&mut self, rhs: Self) {
|
||||
*self = *self | rhs;
|
||||
}
|
||||
+179
-101
@@ -1,14 +1,24 @@
|
||||
//! Lua error handling.
|
||||
//!
|
||||
//! This module provides the [`Error`] type returned by all fallible `mlua` operations, together
|
||||
//! with extension traits for adapting Rust errors for use within Lua.
|
||||
|
||||
use std::error::Error as StdError;
|
||||
use std::fmt;
|
||||
use std::io::Error as IoError;
|
||||
use std::net::AddrParseError;
|
||||
use std::result::Result as StdResult;
|
||||
use std::str::Utf8Error;
|
||||
use std::string::String as StdString;
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::private::Sealed;
|
||||
|
||||
#[cfg(feature = "error-send")]
|
||||
type DynStdError = dyn StdError + Send + Sync;
|
||||
|
||||
#[cfg(not(feature = "error-send"))]
|
||||
type DynStdError = dyn StdError;
|
||||
|
||||
/// Error type returned by `mlua` methods.
|
||||
#[derive(Debug, Clone)]
|
||||
#[non_exhaustive]
|
||||
@@ -16,7 +26,7 @@ pub enum Error {
|
||||
/// Syntax error while parsing Lua source code.
|
||||
SyntaxError {
|
||||
/// The error message as returned by Lua.
|
||||
message: StdString,
|
||||
message: String,
|
||||
/// `true` if the error can likely be fixed by appending more input to the source code.
|
||||
///
|
||||
/// This is useful for implementing REPLs as they can query the user for more input if this
|
||||
@@ -28,25 +38,25 @@ pub enum Error {
|
||||
/// The Lua VM returns this error when a builtin operation is performed on incompatible types.
|
||||
/// Among other things, this includes invoking operators on wrong types (such as calling or
|
||||
/// indexing a `nil` value).
|
||||
RuntimeError(StdString),
|
||||
RuntimeError(String),
|
||||
/// Lua memory error, aka `LUA_ERRMEM`
|
||||
///
|
||||
/// The Lua VM returns this error when the allocator does not return the requested memory, aka
|
||||
/// it is an out-of-memory error.
|
||||
MemoryError(StdString),
|
||||
MemoryError(String),
|
||||
/// Lua garbage collector error, aka `LUA_ERRGCMM`.
|
||||
///
|
||||
/// The Lua VM returns this error when there is an error running a `__gc` metamethod.
|
||||
#[cfg(any(feature = "lua53", feature = "lua52", doc))]
|
||||
#[cfg_attr(docsrs, doc(cfg(any(feature = "lua53", feature = "lua52"))))]
|
||||
GarbageCollectorError(StdString),
|
||||
GarbageCollectorError(String),
|
||||
/// Potentially unsafe action in safe mode.
|
||||
SafetyError(StdString),
|
||||
/// Setting memory limit is not available.
|
||||
SafetyError(String),
|
||||
/// Memory control is not available.
|
||||
///
|
||||
/// This error can only happen when Lua state was not created by us and does not have the
|
||||
/// custom allocator attached.
|
||||
MemoryLimitNotAvailable,
|
||||
MemoryControlNotAvailable,
|
||||
/// A mutable callback has triggered Lua code that has called the same mutable callback again.
|
||||
///
|
||||
/// This is an error because a mutable callback can only be borrowed mutably once.
|
||||
@@ -61,10 +71,12 @@ pub enum Error {
|
||||
///
|
||||
/// Due to the way `mlua` works, it should not be directly possible to run out of stack space
|
||||
/// during normal use. The only way that this error can be triggered is if a `Function` is
|
||||
/// called with a huge number of arguments, or a rust callback returns a huge number of return
|
||||
/// called with a huge number of arguments, or a Rust callback returns a huge number of return
|
||||
/// values.
|
||||
StackError,
|
||||
/// Too many arguments to `Function::bind`.
|
||||
/// Too many arguments to [`Function::bind`].
|
||||
///
|
||||
/// [`Function::bind`]: crate::Function::bind
|
||||
BindError,
|
||||
/// Bad argument received from Lua (usually when calling a function).
|
||||
///
|
||||
@@ -72,43 +84,34 @@ pub enum Error {
|
||||
/// (which is stored in the corresponding field).
|
||||
BadArgument {
|
||||
/// Function that was called.
|
||||
to: Option<StdString>,
|
||||
to: Option<String>,
|
||||
/// Argument position (usually starts from 1).
|
||||
pos: usize,
|
||||
/// Argument name.
|
||||
name: Option<StdString>,
|
||||
name: Option<String>,
|
||||
/// Underlying error returned when converting argument to a Lua value.
|
||||
cause: Arc<Error>,
|
||||
},
|
||||
/// A Rust value could not be converted to a Lua value.
|
||||
ToLuaConversionError {
|
||||
/// Name of the Rust type that could not be converted.
|
||||
from: &'static str,
|
||||
/// Name of the Lua type that could not be created.
|
||||
to: &'static str,
|
||||
/// A message indicating why the conversion failed in more detail.
|
||||
message: Option<StdString>,
|
||||
},
|
||||
/// A Lua value could not be converted to the expected Rust type.
|
||||
FromLuaConversionError {
|
||||
/// Name of the Lua type that could not be converted.
|
||||
from: &'static str,
|
||||
/// Name of the Rust type that could not be created.
|
||||
to: &'static str,
|
||||
to: String,
|
||||
/// A string containing more detailed error information.
|
||||
message: Option<StdString>,
|
||||
message: Option<String>,
|
||||
},
|
||||
/// [`Thread::resume`] was called on an inactive coroutine.
|
||||
/// [`Thread::resume`] was called on an unresumable coroutine.
|
||||
///
|
||||
/// A coroutine is inactive if its main function has returned or if an error has occurred inside
|
||||
/// the coroutine. Already running coroutines are also marked as inactive (unresumable).
|
||||
/// A coroutine is unresumable if its main function has returned or if an error has occurred
|
||||
/// inside the coroutine. Already running coroutines are also marked as unresumable.
|
||||
///
|
||||
/// [`Thread::status`] can be used to check if the coroutine can be resumed without causing this
|
||||
/// error.
|
||||
///
|
||||
/// [`Thread::resume`]: crate::Thread::resume
|
||||
/// [`Thread::status`]: crate::Thread::status
|
||||
CoroutineInactive,
|
||||
CoroutineUnresumable,
|
||||
/// An [`AnyUserData`] is not the expected type in a borrow.
|
||||
///
|
||||
/// This error can only happen when manually using [`AnyUserData`], or when implementing
|
||||
@@ -146,17 +149,17 @@ pub enum Error {
|
||||
/// A [`MetaMethod`] operation is restricted (typically for `__gc` or `__metatable`).
|
||||
///
|
||||
/// [`MetaMethod`]: crate::MetaMethod
|
||||
MetaMethodRestricted(StdString),
|
||||
MetaMethodRestricted(String),
|
||||
/// A [`MetaMethod`] (eg. `__index` or `__newindex`) has invalid type.
|
||||
///
|
||||
/// [`MetaMethod`]: crate::MetaMethod
|
||||
MetaMethodTypeError {
|
||||
/// Name of the metamethod.
|
||||
method: StdString,
|
||||
method: String,
|
||||
/// Passed value type.
|
||||
type_name: &'static str,
|
||||
/// A string containing more detailed error information.
|
||||
message: Option<StdString>,
|
||||
message: Option<String>,
|
||||
},
|
||||
/// A [`RegistryKey`] produced from a different Lua state was used.
|
||||
///
|
||||
@@ -165,7 +168,7 @@ pub enum Error {
|
||||
/// A Rust callback returned `Err`, raising the contained `Error` as a Lua error.
|
||||
CallbackError {
|
||||
/// Lua call stack backtrace.
|
||||
traceback: StdString,
|
||||
traceback: String,
|
||||
/// Original error returned by the Rust code.
|
||||
cause: Arc<Error>,
|
||||
},
|
||||
@@ -175,13 +178,13 @@ pub enum Error {
|
||||
/// and returned again.
|
||||
PreviouslyResumedPanic,
|
||||
/// Serialization error.
|
||||
#[cfg(feature = "serialize")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "serialize")))]
|
||||
SerializeError(StdString),
|
||||
#[cfg(feature = "serde")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
|
||||
SerializeError(String),
|
||||
/// Deserialization error.
|
||||
#[cfg(feature = "serialize")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "serialize")))]
|
||||
DeserializeError(StdString),
|
||||
#[cfg(feature = "serde")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
|
||||
DeserializeError(String),
|
||||
/// A custom error.
|
||||
///
|
||||
/// This can be used for returning user-defined errors from callbacks.
|
||||
@@ -189,11 +192,11 @@ pub enum Error {
|
||||
/// Returning `Err(ExternalError(...))` from a Rust callback will raise the error as a Lua
|
||||
/// error. The Rust code that originally invoked the Lua code then receives a `CallbackError`,
|
||||
/// from which the original error (and a stack traceback) can be recovered.
|
||||
ExternalError(Arc<dyn StdError + Send + Sync>),
|
||||
ExternalError(Arc<DynStdError>),
|
||||
/// An error with additional context.
|
||||
WithContext {
|
||||
/// A string containing additional context.
|
||||
context: StdString,
|
||||
context: String,
|
||||
/// Underlying error.
|
||||
cause: Arc<Error>,
|
||||
},
|
||||
@@ -205,21 +208,21 @@ pub type Result<T> = StdResult<T, Error>;
|
||||
#[cfg(not(tarpaulin_include))]
|
||||
impl fmt::Display for Error {
|
||||
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
|
||||
match *self {
|
||||
Error::SyntaxError { ref message, .. } => write!(fmt, "syntax error: {message}"),
|
||||
Error::RuntimeError(ref msg) => write!(fmt, "runtime error: {msg}"),
|
||||
Error::MemoryError(ref msg) => {
|
||||
match self {
|
||||
Error::SyntaxError { message, .. } => write!(fmt, "syntax error: {message}"),
|
||||
Error::RuntimeError(msg) => write!(fmt, "runtime error: {msg}"),
|
||||
Error::MemoryError(msg) => {
|
||||
write!(fmt, "memory error: {msg}")
|
||||
}
|
||||
#[cfg(any(feature = "lua53", feature = "lua52"))]
|
||||
Error::GarbageCollectorError(ref msg) => {
|
||||
Error::GarbageCollectorError(msg) => {
|
||||
write!(fmt, "garbage collector error: {msg}")
|
||||
}
|
||||
Error::SafetyError(ref msg) => {
|
||||
Error::SafetyError(msg) => {
|
||||
write!(fmt, "safety error: {msg}")
|
||||
},
|
||||
Error::MemoryLimitNotAvailable => {
|
||||
write!(fmt, "setting memory limit is not available")
|
||||
}
|
||||
Error::MemoryControlNotAvailable => {
|
||||
write!(fmt, "memory control is not available")
|
||||
}
|
||||
Error::RecursiveMutCallback => write!(fmt, "mutable callback called recursively"),
|
||||
Error::CallbackDestructed => write!(
|
||||
@@ -230,11 +233,8 @@ impl fmt::Display for Error {
|
||||
fmt,
|
||||
"out of Lua stack, too many arguments to a Lua function or too many return values from a callback"
|
||||
),
|
||||
Error::BindError => write!(
|
||||
fmt,
|
||||
"too many arguments to Function::bind"
|
||||
),
|
||||
Error::BadArgument { ref to, pos, ref name, ref cause } => {
|
||||
Error::BindError => write!(fmt, "too many arguments to Function::bind"),
|
||||
Error::BadArgument { to, pos, name, cause } => {
|
||||
if let Some(name) = name {
|
||||
write!(fmt, "bad argument `{name}`")?;
|
||||
} else {
|
||||
@@ -244,41 +244,42 @@ impl fmt::Display for Error {
|
||||
write!(fmt, " to `{to}`")?;
|
||||
}
|
||||
write!(fmt, ": {cause}")
|
||||
},
|
||||
Error::ToLuaConversionError { from, to, ref message } => {
|
||||
write!(fmt, "error converting {from} to Lua {to}")?;
|
||||
match *message {
|
||||
None => Ok(()),
|
||||
Some(ref message) => write!(fmt, " ({message})"),
|
||||
}
|
||||
}
|
||||
Error::FromLuaConversionError { from, to, ref message } => {
|
||||
Error::FromLuaConversionError { from, to, message } => {
|
||||
write!(fmt, "error converting Lua {from} to {to}")?;
|
||||
match *message {
|
||||
match message {
|
||||
None => Ok(()),
|
||||
Some(ref message) => write!(fmt, " ({message})"),
|
||||
Some(message) => write!(fmt, " ({message})"),
|
||||
}
|
||||
}
|
||||
Error::CoroutineInactive => write!(fmt, "cannot resume inactive coroutine"),
|
||||
Error::CoroutineUnresumable => write!(fmt, "coroutine is non-resumable"),
|
||||
Error::UserDataTypeMismatch => write!(fmt, "userdata is not expected type"),
|
||||
Error::UserDataDestructed => write!(fmt, "userdata has been destructed"),
|
||||
Error::UserDataBorrowError => write!(fmt, "error borrowing userdata"),
|
||||
Error::UserDataBorrowMutError => write!(fmt, "error mutably borrowing userdata"),
|
||||
Error::MetaMethodRestricted(ref method) => write!(fmt, "metamethod {method} is restricted"),
|
||||
Error::MetaMethodTypeError { ref method, type_name, ref message } => {
|
||||
Error::MetaMethodRestricted(method) => write!(fmt, "metamethod {method} is restricted"),
|
||||
Error::MetaMethodTypeError {
|
||||
method,
|
||||
type_name,
|
||||
message,
|
||||
} => {
|
||||
write!(fmt, "metamethod {method} has unsupported type {type_name}")?;
|
||||
match *message {
|
||||
match message {
|
||||
None => Ok(()),
|
||||
Some(ref message) => write!(fmt, " ({message})"),
|
||||
Some(message) => write!(fmt, " ({message})"),
|
||||
}
|
||||
}
|
||||
Error::MismatchedRegistryKey => {
|
||||
write!(fmt, "RegistryKey used from different Lua state")
|
||||
}
|
||||
Error::CallbackError { ref cause, ref traceback } => {
|
||||
Error::CallbackError { cause, traceback } => {
|
||||
// Trace errors down to the root
|
||||
let (mut cause, mut full_traceback) = (cause, None);
|
||||
while let Error::CallbackError { cause: ref cause2, traceback: ref traceback2 } = **cause {
|
||||
while let Error::CallbackError {
|
||||
cause: cause2,
|
||||
traceback: traceback2,
|
||||
} = &**cause
|
||||
{
|
||||
cause = cause2;
|
||||
full_traceback = Some(traceback2);
|
||||
}
|
||||
@@ -289,7 +290,7 @@ impl fmt::Display for Error {
|
||||
// Try to find local traceback within the full traceback
|
||||
if let Some(pos) = full_traceback.find(traceback) {
|
||||
write!(fmt, "{}", &full_traceback[..pos])?;
|
||||
writeln!(fmt, ">{}", &full_traceback[pos..].trim_end())?;
|
||||
writeln!(fmt, ">{}", full_traceback[pos..].trim_end())?;
|
||||
} else {
|
||||
writeln!(fmt, "{}", full_traceback.trim_end())?;
|
||||
}
|
||||
@@ -301,16 +302,16 @@ impl fmt::Display for Error {
|
||||
Error::PreviouslyResumedPanic => {
|
||||
write!(fmt, "previously resumed panic returned again")
|
||||
}
|
||||
#[cfg(feature = "serialize")]
|
||||
Error::SerializeError(ref err) => {
|
||||
#[cfg(feature = "serde")]
|
||||
Error::SerializeError(err) => {
|
||||
write!(fmt, "serialize error: {err}")
|
||||
},
|
||||
#[cfg(feature = "serialize")]
|
||||
Error::DeserializeError(ref err) => {
|
||||
}
|
||||
#[cfg(feature = "serde")]
|
||||
Error::DeserializeError(err) => {
|
||||
write!(fmt, "deserialize error: {err}")
|
||||
},
|
||||
Error::ExternalError(ref err) => write!(fmt, "{err}"),
|
||||
Error::WithContext { ref context, ref cause } => {
|
||||
}
|
||||
Error::ExternalError(err) => err.fmt(fmt),
|
||||
Error::WithContext { context, cause } => {
|
||||
writeln!(fmt, "{context}")?;
|
||||
write!(fmt, "{cause}")
|
||||
}
|
||||
@@ -320,17 +321,15 @@ impl fmt::Display for Error {
|
||||
|
||||
impl StdError for Error {
|
||||
fn source(&self) -> Option<&(dyn StdError + 'static)> {
|
||||
match *self {
|
||||
match self {
|
||||
// An error type with a source error should either return that error via source or
|
||||
// include that source's error message in its own Display output, but never both.
|
||||
// https://blog.rust-lang.org/inside-rust/2021/07/01/What-the-error-handling-project-group-is-working-towards.html
|
||||
// Given that we include source to fmt::Display implementation for `CallbackError`, this call returns nothing.
|
||||
// Given that we include source to fmt::Display implementation for `CallbackError`, this call
|
||||
// returns nothing.
|
||||
Error::CallbackError { .. } => None,
|
||||
Error::ExternalError(ref err) => err.source(),
|
||||
Error::WithContext { ref cause, .. } => match cause.as_ref() {
|
||||
Error::ExternalError(err) => err.source(),
|
||||
_ => None,
|
||||
},
|
||||
Error::ExternalError(err) => err.source(),
|
||||
Error::WithContext { cause, .. } => Self::source(cause),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -345,8 +344,12 @@ impl Error {
|
||||
|
||||
/// Wraps an external error object.
|
||||
#[inline]
|
||||
pub fn external<T: Into<Box<dyn StdError + Send + Sync>>>(err: T) -> Self {
|
||||
Error::ExternalError(err.into().into())
|
||||
pub fn external<T: Into<Box<DynStdError>>>(err: T) -> Self {
|
||||
let boxed = err.into();
|
||||
match boxed.downcast::<Self>() {
|
||||
Ok(err) => *err,
|
||||
Err(boxed) => Error::ExternalError(boxed.into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Attempts to downcast the external error object to a concrete type by reference.
|
||||
@@ -356,10 +359,25 @@ impl Error {
|
||||
{
|
||||
match self {
|
||||
Error::ExternalError(err) => err.downcast_ref(),
|
||||
Error::WithContext { cause, .. } => match cause.as_ref() {
|
||||
Error::ExternalError(err) => err.downcast_ref(),
|
||||
_ => None,
|
||||
},
|
||||
Error::WithContext { cause, .. } => Self::downcast_ref(cause),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// An iterator over the chain of nested errors wrapped by this Error.
|
||||
pub fn chain(&self) -> impl Iterator<Item = &(dyn StdError + 'static)> {
|
||||
Chain {
|
||||
root: self,
|
||||
current: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the parent of this error.
|
||||
#[doc(hidden)]
|
||||
pub fn parent(&self) -> Option<&Error> {
|
||||
match self {
|
||||
Error::CallbackError { cause, .. } => Some(cause.as_ref()),
|
||||
Error::WithContext { cause, .. } => Some(cause.as_ref()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -373,15 +391,16 @@ impl Error {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn from_lua_conversion<'a>(
|
||||
#[inline]
|
||||
pub(crate) fn from_lua_conversion(
|
||||
from: &'static str,
|
||||
to: &'static str,
|
||||
message: impl Into<Option<&'a str>>,
|
||||
to: impl ToString,
|
||||
message: impl Into<Option<String>>,
|
||||
) -> Self {
|
||||
Error::FromLuaConversionError {
|
||||
from,
|
||||
to,
|
||||
message: message.into().map(|s| s.into()),
|
||||
to: to.to_string(),
|
||||
message: message.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -391,7 +410,7 @@ pub trait ExternalError {
|
||||
fn into_lua_err(self) -> Error;
|
||||
}
|
||||
|
||||
impl<E: Into<Box<dyn StdError + Send + Sync>>> ExternalError for E {
|
||||
impl<E: Into<Box<DynStdError>>> ExternalError for E {
|
||||
fn into_lua_err(self) -> Error {
|
||||
Error::external(self)
|
||||
}
|
||||
@@ -445,7 +464,7 @@ impl ErrorContext for Error {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> ErrorContext for StdResult<T, Error> {
|
||||
impl<T> ErrorContext for Result<T> {
|
||||
fn context<C: fmt::Display>(self, context: C) -> Self {
|
||||
self.map_err(|err| err.context(context))
|
||||
}
|
||||
@@ -473,16 +492,75 @@ impl From<Utf8Error> for Error {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "serialize")]
|
||||
#[cfg(feature = "serde")]
|
||||
impl serde::ser::Error for Error {
|
||||
fn custom<T: fmt::Display>(msg: T) -> Self {
|
||||
Self::SerializeError(msg.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "serialize")]
|
||||
#[cfg(feature = "serde")]
|
||||
impl serde::de::Error for Error {
|
||||
fn custom<T: fmt::Display>(msg: T) -> Self {
|
||||
Self::DeserializeError(msg.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "anyhow")]
|
||||
impl From<anyhow::Error> for Error {
|
||||
fn from(err: anyhow::Error) -> Self {
|
||||
match err.downcast::<Self>() {
|
||||
Ok(err) => err,
|
||||
Err(err) => Error::external(err),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Chain<'a> {
|
||||
root: &'a Error,
|
||||
current: Option<&'a (dyn StdError + 'static)>,
|
||||
}
|
||||
|
||||
impl<'a> Iterator for Chain<'a> {
|
||||
type Item = &'a (dyn StdError + 'static);
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
loop {
|
||||
let error: Option<&dyn StdError> = match self.current {
|
||||
None => {
|
||||
self.current = Some(self.root);
|
||||
self.current
|
||||
}
|
||||
Some(current) => match current.downcast_ref::<Error>()? {
|
||||
Error::BadArgument { cause, .. }
|
||||
| Error::CallbackError { cause, .. }
|
||||
| Error::WithContext { cause, .. } => {
|
||||
self.current = Some(&**cause);
|
||||
self.current
|
||||
}
|
||||
Error::ExternalError(err) => {
|
||||
self.current = Some(&**err);
|
||||
self.current
|
||||
}
|
||||
_ => None,
|
||||
},
|
||||
};
|
||||
|
||||
// Skip `ExternalError` as it only wraps the underlying error
|
||||
// without meaningful context
|
||||
if let Some(Error::ExternalError(_)) = error?.downcast_ref::<Error>() {
|
||||
continue;
|
||||
}
|
||||
|
||||
return self.current;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod assertions {
|
||||
#[cfg(not(feature = "error-send"))]
|
||||
static_assertions::assert_not_impl_any!(super::Error: Send, Sync);
|
||||
#[cfg(feature = "send")]
|
||||
static_assertions::assert_impl_all!(super::Error: Send, Sync);
|
||||
}
|
||||
|
||||
+423
-189
@@ -1,49 +1,105 @@
|
||||
use std::cell::RefCell;
|
||||
use std::mem;
|
||||
use std::os::raw::{c_int, c_void};
|
||||
use std::ptr;
|
||||
use std::slice;
|
||||
//! Lua function handling.
|
||||
//!
|
||||
//! This module provides types for working with Lua functions from Rust, including
|
||||
//! both Lua-defined functions and native Rust callbacks.
|
||||
//!
|
||||
//! # Calling Functions
|
||||
//!
|
||||
//! Use [`Function::call`] to invoke a Lua function synchronously:
|
||||
//!
|
||||
//! ```
|
||||
//! # use mlua::{Function, Lua, Result};
|
||||
//! # fn main() -> Result<()> {
|
||||
//! let lua = Lua::new();
|
||||
//!
|
||||
//! // Get a built-in function
|
||||
//! let print: Function = lua.globals().get("print")?;
|
||||
//! print.call::<()>("Hello from Rust!")?;
|
||||
//!
|
||||
//! // Call a function that returns values
|
||||
//! let tonumber: Function = lua.globals().get("tonumber")?;
|
||||
//! let n: i32 = tonumber.call("42")?;
|
||||
//! assert_eq!(n, 42);
|
||||
//! # Ok(())
|
||||
//! # }
|
||||
//! ```
|
||||
//!
|
||||
//! For asynchronous execution, use `Function::call_async` (requires `async` feature):
|
||||
//!
|
||||
//! ```ignore
|
||||
//! let result: String = my_async_func.call_async(args).await?;
|
||||
//! ```
|
||||
//!
|
||||
//! # Creating Functions
|
||||
//!
|
||||
//! Functions can be created from Rust closures using [`Lua::create_function`]:
|
||||
//!
|
||||
//! ```
|
||||
//! # use mlua::{Lua, Result};
|
||||
//! # fn main() -> Result<()> {
|
||||
//! let lua = Lua::new();
|
||||
//!
|
||||
//! let greet = lua.create_function(|_, name: String| {
|
||||
//! Ok(format!("Hello, {}!", name))
|
||||
//! })?;
|
||||
//!
|
||||
//! lua.globals().set("greet", greet)?;
|
||||
//! let result: String = lua.load(r#"greet("World")"#).eval()?;
|
||||
//! assert_eq!(result, "Hello, World!");
|
||||
//! # Ok(())
|
||||
//! # }
|
||||
//! ```
|
||||
//!
|
||||
//! For simpler cases, use [`Function::wrap`] or [`Function::wrap_raw`] to convert a Rust function
|
||||
//! directly:
|
||||
//!
|
||||
//! ```
|
||||
//! # use mlua::{Function, Lua, Result};
|
||||
//! # fn main() -> Result<()> {
|
||||
//! let lua = Lua::new();
|
||||
//!
|
||||
//! fn add(a: i32, b: i32) -> i32 { a + b }
|
||||
//!
|
||||
//! lua.globals().set("add", Function::wrap_raw(add))?;
|
||||
//! let sum: i32 = lua.load("add(2, 3)").eval()?;
|
||||
//! assert_eq!(sum, 5);
|
||||
//! # Ok(())
|
||||
//! # }
|
||||
//! ```
|
||||
//!
|
||||
//! # Function Environments
|
||||
//!
|
||||
//! Lua functions have an associated environment table that determines how global
|
||||
//! variables are resolved. Use [`Function::environment`] and [`Function::set_environment`]
|
||||
//! to inspect or modify this environment.
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::lua::Lua;
|
||||
use std::cell::RefCell;
|
||||
use std::os::raw::{c_int, c_void};
|
||||
use std::result::Result as StdResult;
|
||||
use std::{mem, ptr, slice};
|
||||
|
||||
use crate::error::{Error, ExternalError, ExternalResult, Result};
|
||||
use crate::state::Lua;
|
||||
use crate::table::Table;
|
||||
use crate::types::{Callback, LuaRef, MaybeSend};
|
||||
use crate::traits::{FromLuaMulti, IntoLua, IntoLuaMulti};
|
||||
use crate::types::{Callback, LuaType, MaybeSend, ValueRef};
|
||||
use crate::util::{
|
||||
assert_stack, check_stack, linenumber_to_usize, pop_error, ptr_to_lossy_str, ptr_to_str,
|
||||
StackGuard,
|
||||
StackGuard, assert_stack, check_stack, linenumber_to_usize, pop_error, ptr_to_lossy_str, ptr_to_str,
|
||||
};
|
||||
use crate::value::{FromLuaMulti, IntoLua, IntoLuaMulti, Value};
|
||||
use crate::value::Value;
|
||||
|
||||
#[cfg(feature = "async")]
|
||||
use {
|
||||
crate::thread::AsyncThread,
|
||||
crate::types::AsyncCallback,
|
||||
futures_util::future::{self, Future},
|
||||
std::future::{self, Future},
|
||||
std::pin::{Pin, pin},
|
||||
std::task::{Context, Poll},
|
||||
};
|
||||
|
||||
/// Handle to an internal Lua function.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Function<'lua>(pub(crate) LuaRef<'lua>);
|
||||
|
||||
/// Owned handle to an internal Lua function.
|
||||
///
|
||||
/// The owned handle holds a *strong* reference to the current Lua instance.
|
||||
/// Be warned, if you place it into a Lua type (eg. [`UserData`] or a Rust callback), it is *very easy*
|
||||
/// to accidentally cause reference cycles that would prevent destroying Lua instance.
|
||||
///
|
||||
/// [`UserData`]: crate::UserData
|
||||
#[cfg(feature = "unstable")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "unstable")))]
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct OwnedFunction(pub(crate) crate::types::LuaOwnedRef);
|
||||
|
||||
#[cfg(feature = "unstable")]
|
||||
impl OwnedFunction {
|
||||
/// Get borrowed handle to the underlying Lua function.
|
||||
#[cfg_attr(feature = "send", allow(unused))]
|
||||
pub const fn to_ref(&self) -> Function {
|
||||
Function(self.0.to_ref())
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Function(pub(crate) ValueRef);
|
||||
|
||||
/// Contains information about a function.
|
||||
///
|
||||
@@ -51,6 +107,7 @@ impl OwnedFunction {
|
||||
///
|
||||
/// [`Lua Debug Interface`]: https://www.lua.org/manual/5.4/manual.html#4.7
|
||||
#[derive(Clone, Debug)]
|
||||
#[non_exhaustive]
|
||||
pub struct FunctionInfo {
|
||||
/// A (reasonable) name of the function (`None` if the name cannot be found).
|
||||
pub name: Option<String>,
|
||||
@@ -58,7 +115,8 @@ pub struct FunctionInfo {
|
||||
///
|
||||
/// Always `None` for Luau.
|
||||
pub name_what: Option<&'static str>,
|
||||
/// A string `Lua` if the function is a Lua function, `C` if it is a C function, `main` if it is the main part of a chunk.
|
||||
/// A string `Lua` if the function is a Lua function, `C` if it is a C function, `main` if it is
|
||||
/// the main part of a chunk.
|
||||
pub what: &'static str,
|
||||
/// Source of the chunk that created the function.
|
||||
pub source: Option<String>,
|
||||
@@ -68,6 +126,16 @@ pub struct FunctionInfo {
|
||||
pub line_defined: Option<usize>,
|
||||
/// The line number where the definition of the function ends (not set by Luau).
|
||||
pub last_line_defined: Option<usize>,
|
||||
/// The number of upvalues of the function.
|
||||
pub num_upvalues: u8,
|
||||
/// The number of parameters of the function (always 0 for C).
|
||||
#[cfg(any(not(any(feature = "lua51", feature = "luajit")), doc))]
|
||||
#[cfg_attr(docsrs, doc(cfg(not(any(feature = "lua51", feature = "luajit")))))]
|
||||
pub num_params: u8,
|
||||
/// Whether the function is a variadic function (always true for C).
|
||||
#[cfg(any(not(any(feature = "lua51", feature = "luajit")), doc))]
|
||||
#[cfg_attr(docsrs, doc(cfg(not(any(feature = "lua51", feature = "luajit")))))]
|
||||
pub is_vararg: bool,
|
||||
}
|
||||
|
||||
/// Luau function coverage snapshot.
|
||||
@@ -81,7 +149,7 @@ pub struct CoverageInfo {
|
||||
pub hits: Vec<i32>,
|
||||
}
|
||||
|
||||
impl<'lua> Function<'lua> {
|
||||
impl Function {
|
||||
/// Calls the function, passing `args` as function arguments.
|
||||
///
|
||||
/// The function's return values are converted to the generic type `R`.
|
||||
@@ -98,7 +166,7 @@ impl<'lua> Function<'lua> {
|
||||
///
|
||||
/// let tostring: Function = globals.get("tostring")?;
|
||||
///
|
||||
/// assert_eq!(tostring.call::<_, String>(123)?, "123");
|
||||
/// assert_eq!(tostring.call::<String>(123)?, "123");
|
||||
///
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
@@ -117,13 +185,13 @@ impl<'lua> Function<'lua> {
|
||||
/// end
|
||||
/// "#).eval()?;
|
||||
///
|
||||
/// assert_eq!(sum.call::<_, u32>((3, 4))?, 3 + 4);
|
||||
/// assert_eq!(sum.call::<u32>((3, 4))?, 3 + 4);
|
||||
///
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
pub fn call<A: IntoLuaMulti<'lua>, R: FromLuaMulti<'lua>>(&self, args: A) -> Result<R> {
|
||||
let lua = self.0.lua;
|
||||
pub fn call<R: FromLuaMulti>(&self, args: impl IntoLuaMulti) -> Result<R> {
|
||||
let lua = self.0.lua.lock();
|
||||
let state = lua.state();
|
||||
unsafe {
|
||||
let _sg = StackGuard::new(state);
|
||||
@@ -134,7 +202,7 @@ impl<'lua> Function<'lua> {
|
||||
let stack_start = ffi::lua_gettop(state);
|
||||
// Push function and the arguments
|
||||
lua.push_ref(&self.0);
|
||||
let nargs = args.push_into_stack_multi(lua)?;
|
||||
let nargs = args.push_into_stack_multi(&lua)?;
|
||||
// Call the function
|
||||
let ret = ffi::lua_pcall(state, nargs, ffi::LUA_MULTRET, stack_start);
|
||||
if ret != ffi::LUA_OK {
|
||||
@@ -142,16 +210,15 @@ impl<'lua> Function<'lua> {
|
||||
}
|
||||
// Get the results
|
||||
let nresults = ffi::lua_gettop(state) - stack_start;
|
||||
R::from_stack_multi(nresults, lua)
|
||||
R::from_stack_multi(nresults, &lua)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a future that, when polled, calls `self`, passing `args` as function arguments,
|
||||
/// and drives the execution.
|
||||
///
|
||||
/// Internally it wraps the function to an [`AsyncThread`].
|
||||
///
|
||||
/// Requires `feature = "async"`
|
||||
/// Internally it wraps the function to an [`AsyncThread`]. The returned type implements
|
||||
/// `Future<Output = Result<R>>` and can be awaited.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
@@ -167,27 +234,27 @@ impl<'lua> Function<'lua> {
|
||||
/// Ok(())
|
||||
/// })?;
|
||||
///
|
||||
/// sleep.call_async(10).await?;
|
||||
/// sleep.call_async::<()>(10).await?;
|
||||
///
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
///
|
||||
/// [`AsyncThread`]: crate::AsyncThread
|
||||
/// [`AsyncThread`]: crate::thread::AsyncThread
|
||||
#[cfg(feature = "async")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
|
||||
pub fn call_async<A, R>(&self, args: A) -> impl Future<Output = Result<R>> + 'lua
|
||||
pub fn call_async<R>(&self, args: impl IntoLuaMulti) -> AsyncCallFuture<R>
|
||||
where
|
||||
A: IntoLuaMulti<'lua>,
|
||||
R: FromLuaMulti<'lua> + 'lua,
|
||||
R: FromLuaMulti,
|
||||
{
|
||||
let lua = self.0.lua;
|
||||
let thread_res = lua.create_recycled_thread(self).map(|th| {
|
||||
let mut th = th.into_async(args);
|
||||
th.set_recyclable(true);
|
||||
th
|
||||
});
|
||||
async move { thread_res?.await }
|
||||
let lua = self.0.lua.lock();
|
||||
AsyncCallFuture(unsafe {
|
||||
lua.create_recycled_thread(self).and_then(|th| {
|
||||
let mut th = th.into_async(args)?;
|
||||
th.set_recyclable(true);
|
||||
Ok(th)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns a function that, when called, calls `self`, passing `args` as the first set of
|
||||
@@ -209,15 +276,15 @@ impl<'lua> Function<'lua> {
|
||||
/// "#).eval()?;
|
||||
///
|
||||
/// let bound_a = sum.bind(1)?;
|
||||
/// assert_eq!(bound_a.call::<_, u32>(2)?, 1 + 2);
|
||||
/// assert_eq!(bound_a.call::<u32>(2)?, 1 + 2);
|
||||
///
|
||||
/// let bound_a_and_b = sum.bind(13)?.bind(57)?;
|
||||
/// assert_eq!(bound_a_and_b.call::<_, u32>(())?, 13 + 57);
|
||||
/// assert_eq!(bound_a_and_b.call::<u32>(())?, 13 + 57);
|
||||
///
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
pub fn bind<A: IntoLuaMulti<'lua>>(&self, args: A) -> Result<Function<'lua>> {
|
||||
pub fn bind(&self, args: impl IntoLuaMulti) -> Result<Function> {
|
||||
unsafe extern "C-unwind" fn args_wrapper_impl(state: *mut ffi::lua_State) -> c_int {
|
||||
let nargs = ffi::lua_gettop(state);
|
||||
let nbinds = ffi::lua_tointeger(state, ffi::lua_upvalueindex(1)) as c_int;
|
||||
@@ -233,10 +300,10 @@ impl<'lua> Function<'lua> {
|
||||
nargs + nbinds
|
||||
}
|
||||
|
||||
let lua = self.0.lua;
|
||||
let lua = self.0.lua.lock();
|
||||
let state = lua.state();
|
||||
|
||||
let args = args.into_lua_multi(lua)?;
|
||||
let args = args.into_lua_multi(lua.lua())?;
|
||||
let nargs = args.len() as c_int;
|
||||
|
||||
if nargs == 0 {
|
||||
@@ -252,7 +319,7 @@ impl<'lua> Function<'lua> {
|
||||
check_stack(state, nargs + 3)?;
|
||||
|
||||
ffi::lua_pushinteger(state, nargs as ffi::lua_Integer);
|
||||
for arg in args {
|
||||
for arg in &args {
|
||||
lua.push_value(arg)?;
|
||||
}
|
||||
protect_lua!(state, nargs + 1, 1, fn(state) {
|
||||
@@ -262,6 +329,7 @@ impl<'lua> Function<'lua> {
|
||||
Function(lua.pop_ref())
|
||||
};
|
||||
|
||||
let lua = lua.lua();
|
||||
lua.load(
|
||||
r#"
|
||||
local func, args_wrapper = ...
|
||||
@@ -271,8 +339,8 @@ impl<'lua> Function<'lua> {
|
||||
"#,
|
||||
)
|
||||
.try_cache()
|
||||
.set_name("__mlua_bind")
|
||||
.call((self.clone(), args_wrapper))
|
||||
.set_name("=__mlua_bind")
|
||||
.call((self, args_wrapper))
|
||||
}
|
||||
|
||||
/// Returns the environment of the Lua function.
|
||||
@@ -281,7 +349,7 @@ impl<'lua> Function<'lua> {
|
||||
///
|
||||
/// This function always returns `None` for Rust/C functions.
|
||||
pub fn environment(&self) -> Option<Table> {
|
||||
let lua = self.0.lua;
|
||||
let lua = self.0.lua.lock();
|
||||
let state = lua.state();
|
||||
unsafe {
|
||||
let _sg = StackGuard::new(state);
|
||||
@@ -294,12 +362,12 @@ impl<'lua> Function<'lua> {
|
||||
|
||||
#[cfg(any(feature = "lua51", feature = "luajit", feature = "luau"))]
|
||||
ffi::lua_getfenv(state, -1);
|
||||
#[cfg(any(feature = "lua54", feature = "lua53", feature = "lua52"))]
|
||||
#[cfg(any(feature = "lua55", feature = "lua54", feature = "lua53", feature = "lua52"))]
|
||||
for i in 1..=255 {
|
||||
// Traverse upvalues until we find the _ENV one
|
||||
match ffi::lua_getupvalue(state, -1, i) {
|
||||
s if s.is_null() => break,
|
||||
s if std::ffi::CStr::from_ptr(s as _).to_bytes() == b"_ENV" => break,
|
||||
s if std::ffi::CStr::from_ptr(s as _) == c"_ENV" => break,
|
||||
_ => ffi::lua_pop(state, 1),
|
||||
}
|
||||
}
|
||||
@@ -318,7 +386,7 @@ impl<'lua> Function<'lua> {
|
||||
///
|
||||
/// This function does nothing for Rust/C functions.
|
||||
pub fn set_environment(&self, env: Table) -> Result<bool> {
|
||||
let lua = self.0.lua;
|
||||
let lua = self.0.lua.lock();
|
||||
let state = lua.state();
|
||||
unsafe {
|
||||
let _sg = StackGuard::new(state);
|
||||
@@ -334,14 +402,15 @@ impl<'lua> Function<'lua> {
|
||||
lua.push_ref(&env.0);
|
||||
ffi::lua_setfenv(state, -2);
|
||||
}
|
||||
#[cfg(any(feature = "lua54", feature = "lua53", feature = "lua52"))]
|
||||
#[cfg(any(feature = "lua55", feature = "lua54", feature = "lua53", feature = "lua52"))]
|
||||
for i in 1..=255 {
|
||||
match ffi::lua_getupvalue(state, -1, i) {
|
||||
s if s.is_null() => return Ok(false),
|
||||
s if std::ffi::CStr::from_ptr(s as _).to_bytes() == b"_ENV" => {
|
||||
s if std::ffi::CStr::from_ptr(s as _) == c"_ENV" => {
|
||||
ffi::lua_pop(state, 1);
|
||||
// Create an anonymous function with the new environment
|
||||
let f_with_env = lua
|
||||
.lua()
|
||||
.load("return _ENV")
|
||||
.set_environment(env)
|
||||
.try_cache()
|
||||
@@ -360,11 +429,12 @@ impl<'lua> Function<'lua> {
|
||||
|
||||
/// Returns information about the function.
|
||||
///
|
||||
/// Corresponds to the `>Sn` what mask for [`lua_getinfo`] when applied to the function.
|
||||
/// Corresponds to the `>Snu` (`>Sn` for Luau) what mask for
|
||||
/// [`lua_getinfo`] when applied to the function.
|
||||
///
|
||||
/// [`lua_getinfo`]: https://www.lua.org/manual/5.4/manual.html#lua_getinfo
|
||||
pub fn info(&self) -> FunctionInfo {
|
||||
let lua = self.0.lua;
|
||||
let lua = self.0.lua.lock();
|
||||
let state = lua.state();
|
||||
unsafe {
|
||||
let _sg = StackGuard::new(state);
|
||||
@@ -372,11 +442,16 @@ impl<'lua> Function<'lua> {
|
||||
|
||||
let mut ar: ffi::lua_Debug = mem::zeroed();
|
||||
lua.push_ref(&self.0);
|
||||
|
||||
#[cfg(not(feature = "luau"))]
|
||||
let res = ffi::lua_getinfo(state, cstr!(">Sn"), &mut ar);
|
||||
let res = ffi::lua_getinfo(state, cstr!(">Snu"), &mut ar);
|
||||
#[cfg(not(feature = "luau"))]
|
||||
mlua_assert!(res != 0, "lua_getinfo failed with `>Snu`");
|
||||
|
||||
#[cfg(feature = "luau")]
|
||||
let res = ffi::lua_getinfo(state, -1, cstr!("sn"), &mut ar);
|
||||
mlua_assert!(res != 0, "lua_getinfo failed with `>Sn`");
|
||||
let res = ffi::lua_getinfo(state, -1, cstr!("snau"), &mut ar);
|
||||
#[cfg(feature = "luau")]
|
||||
mlua_assert!(res != 0, "lua_getinfo failed with `snau`");
|
||||
|
||||
FunctionInfo {
|
||||
name: ptr_to_lossy_str(ar.name).map(|s| s.into_owned()),
|
||||
@@ -398,6 +473,14 @@ impl<'lua> Function<'lua> {
|
||||
last_line_defined: linenumber_to_usize(ar.lastlinedefined),
|
||||
#[cfg(feature = "luau")]
|
||||
last_line_defined: None,
|
||||
#[cfg(not(feature = "luau"))]
|
||||
num_upvalues: ar.nups as _,
|
||||
#[cfg(feature = "luau")]
|
||||
num_upvalues: ar.nupvals,
|
||||
#[cfg(not(any(feature = "lua51", feature = "luajit")))]
|
||||
num_params: ar.nparams,
|
||||
#[cfg(not(any(feature = "lua51", feature = "luajit")))]
|
||||
is_vararg: ar.isvararg != 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -407,9 +490,9 @@ impl<'lua> Function<'lua> {
|
||||
/// If `strip` is true, the binary representation may not include all debug information
|
||||
/// about the function, to save space.
|
||||
///
|
||||
/// For Luau a [Compiler] can be used to compile Lua chunks to bytecode.
|
||||
/// For Luau a [`Compiler`] can be used to compile Lua chunks to bytecode.
|
||||
///
|
||||
/// [Compiler]: crate::chunk::Compiler
|
||||
/// [`Compiler`]: crate::chunk::Compiler
|
||||
#[cfg(not(feature = "luau"))]
|
||||
#[cfg_attr(docsrs, doc(cfg(not(feature = "luau"))))]
|
||||
pub fn dump(&self, strip: bool) -> Vec<u8> {
|
||||
@@ -417,15 +500,18 @@ impl<'lua> Function<'lua> {
|
||||
_state: *mut ffi::lua_State,
|
||||
buf: *const c_void,
|
||||
buf_len: usize,
|
||||
data: *mut c_void,
|
||||
data_ptr: *mut c_void,
|
||||
) -> c_int {
|
||||
let data = &mut *(data as *mut Vec<u8>);
|
||||
let buf = slice::from_raw_parts(buf as *const u8, buf_len);
|
||||
data.extend_from_slice(buf);
|
||||
// If `data` is null, then it's a signal that write is finished.
|
||||
if !data_ptr.is_null() && buf_len > 0 {
|
||||
let data = &mut *(data_ptr as *mut Vec<u8>);
|
||||
let buf = slice::from_raw_parts(buf as *const u8, buf_len);
|
||||
data.extend_from_slice(buf);
|
||||
}
|
||||
0
|
||||
}
|
||||
|
||||
let lua = self.0.lua;
|
||||
let lua = self.0.lua.lock();
|
||||
let state = lua.state();
|
||||
let mut data: Vec<u8> = Vec::new();
|
||||
unsafe {
|
||||
@@ -443,17 +529,15 @@ impl<'lua> Function<'lua> {
|
||||
|
||||
/// Retrieves recorded coverage information about this Lua function including inner calls.
|
||||
///
|
||||
/// This function takes a callback as an argument and calls it providing [`CoverageInfo`] snapshot
|
||||
/// per each executed inner function.
|
||||
/// This function takes a callback as an argument and calls it providing [`CoverageInfo`]
|
||||
/// snapshot per each executed inner function.
|
||||
///
|
||||
/// Recording of coverage information is controlled by [`Compiler::set_coverage_level`] option.
|
||||
///
|
||||
/// Requires `feature = "luau"`
|
||||
///
|
||||
/// [`Compiler::set_coverage_level`]: crate::chunk::Compiler::set_coverage_level
|
||||
#[cfg(any(feature = "luau", doc))]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "luau")))]
|
||||
pub fn coverage<F>(&self, mut func: F)
|
||||
pub fn coverage<F>(&self, func: F)
|
||||
where
|
||||
F: FnMut(CoverageInfo),
|
||||
{
|
||||
@@ -473,23 +557,27 @@ impl<'lua> Function<'lua> {
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let rust_callback = &mut *(data as *mut F);
|
||||
rust_callback(CoverageInfo {
|
||||
function,
|
||||
line_defined,
|
||||
depth,
|
||||
hits: slice::from_raw_parts(hits, size).to_vec(),
|
||||
});
|
||||
let rust_callback = &*(data as *const RefCell<F>);
|
||||
if let Ok(mut rust_callback) = rust_callback.try_borrow_mut() {
|
||||
// Call the Rust callback with CoverageInfo
|
||||
rust_callback(CoverageInfo {
|
||||
function,
|
||||
line_defined,
|
||||
depth,
|
||||
hits: slice::from_raw_parts(hits, size).to_vec(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
let lua = self.0.lua;
|
||||
let lua = self.0.lua.lock();
|
||||
let state = lua.state();
|
||||
unsafe {
|
||||
let _sg = StackGuard::new(state);
|
||||
assert_stack(state, 1);
|
||||
|
||||
lua.push_ref(&self.0);
|
||||
let func_ptr = &mut func as *mut F as *mut c_void;
|
||||
let func = RefCell::new(func);
|
||||
let func_ptr = &func as *const RefCell<F> as *mut c_void;
|
||||
ffi::lua_getcoverage(state, -1, func_ptr, callback::<F>);
|
||||
}
|
||||
}
|
||||
@@ -508,149 +596,295 @@ impl<'lua> Function<'lua> {
|
||||
///
|
||||
/// Copies the function prototype and all its upvalues to the
|
||||
/// newly created function.
|
||||
///
|
||||
/// This function returns shallow clone (same handle) for Rust/C functions.
|
||||
/// Requires `feature = "luau"`
|
||||
#[cfg(feature = "luau")]
|
||||
#[cfg(any(feature = "luau", doc))]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "luau")))]
|
||||
pub fn deep_clone(&self) -> Self {
|
||||
let ref_thread = self.0.lua.ref_thread();
|
||||
pub fn deep_clone(&self) -> Result<Self> {
|
||||
let lua = self.0.lua.lock();
|
||||
let state = lua.state();
|
||||
unsafe {
|
||||
if ffi::lua_iscfunction(ref_thread, self.0.index) != 0 {
|
||||
return self.clone();
|
||||
let _sg = StackGuard::new(state);
|
||||
check_stack(state, 2)?;
|
||||
|
||||
lua.push_ref(&self.0);
|
||||
if ffi::lua_iscfunction(state, -1) != 0 {
|
||||
return Ok(self.clone());
|
||||
}
|
||||
|
||||
ffi::lua_clonefunction(ref_thread, self.0.index);
|
||||
Function(self.0.lua.pop_ref_thread())
|
||||
if lua.unlikely_memory_error() {
|
||||
ffi::lua_clonefunction(state, -1);
|
||||
} else {
|
||||
protect_lua!(state, 1, 1, fn(state) ffi::lua_clonefunction(state, -1))?;
|
||||
}
|
||||
Ok(Function(lua.pop_ref()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Convert this handle to owned version.
|
||||
#[cfg(all(feature = "unstable", any(not(feature = "send"), doc)))]
|
||||
#[cfg_attr(docsrs, doc(cfg(all(feature = "unstable", not(feature = "send")))))]
|
||||
#[inline]
|
||||
pub fn into_owned(self) -> OwnedFunction {
|
||||
OwnedFunction(self.0.into_owned())
|
||||
}
|
||||
}
|
||||
|
||||
impl<'lua> PartialEq for Function<'lua> {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.0 == other.0
|
||||
}
|
||||
}
|
||||
|
||||
// Additional shortcuts
|
||||
#[cfg(feature = "unstable")]
|
||||
impl OwnedFunction {
|
||||
/// Calls the function, passing `args` as function arguments.
|
||||
///
|
||||
/// This is a shortcut for [`Function::call()`].
|
||||
#[inline]
|
||||
pub fn call<'lua, A, R>(&'lua self, args: A) -> Result<R>
|
||||
where
|
||||
A: IntoLuaMulti<'lua>,
|
||||
R: FromLuaMulti<'lua>,
|
||||
{
|
||||
self.to_ref().call(args)
|
||||
}
|
||||
|
||||
/// Returns a future that, when polled, calls `self`, passing `args` as function arguments,
|
||||
/// and drives the execution.
|
||||
///
|
||||
/// This is a shortcut for [`Function::call_async()`].
|
||||
#[cfg(feature = "async")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
|
||||
#[inline]
|
||||
pub async fn call_async<'lua, A, R>(&'lua self, args: A) -> Result<R>
|
||||
where
|
||||
A: IntoLuaMulti<'lua>,
|
||||
R: FromLuaMulti<'lua> + 'lua,
|
||||
{
|
||||
self.to_ref().call_async(args).await
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct WrappedFunction<'lua>(pub(crate) Callback<'lua, 'static>);
|
||||
struct WrappedFunction(pub(crate) Callback);
|
||||
|
||||
#[cfg(feature = "async")]
|
||||
pub(crate) struct WrappedAsyncFunction<'lua>(pub(crate) AsyncCallback<'lua, 'static>);
|
||||
struct WrappedAsyncFunction(pub(crate) AsyncCallback);
|
||||
|
||||
impl<'lua> Function<'lua> {
|
||||
/// Wraps a Rust function or closure, returning an opaque type that implements [`IntoLua`] trait.
|
||||
impl Function {
|
||||
/// Wraps a Rust function or closure, returning an opaque type that implements [`IntoLua`]
|
||||
/// trait.
|
||||
#[inline]
|
||||
pub fn wrap<A, R, F>(func: F) -> impl IntoLua<'lua>
|
||||
pub fn wrap<F, A, R, E>(func: F) -> impl IntoLua
|
||||
where
|
||||
A: FromLuaMulti<'lua>,
|
||||
R: IntoLuaMulti<'lua>,
|
||||
F: Fn(&'lua Lua, A) -> Result<R> + MaybeSend + 'static,
|
||||
F: LuaNativeFn<A, Output = StdResult<R, E>> + MaybeSend + 'static,
|
||||
A: FromLuaMulti,
|
||||
R: IntoLuaMulti,
|
||||
E: ExternalError,
|
||||
{
|
||||
WrappedFunction(Box::new(move |lua, nargs| unsafe {
|
||||
let args = A::from_stack_args(nargs, 1, None, lua)?;
|
||||
func(lua, args)?.push_into_stack_multi(lua)
|
||||
func.call(args).into_lua_err()?.push_into_stack_multi(lua)
|
||||
}))
|
||||
}
|
||||
|
||||
/// Wraps a Rust mutable closure, returning an opaque type that implements [`IntoLua`] trait.
|
||||
#[inline]
|
||||
pub fn wrap_mut<A, R, F>(func: F) -> impl IntoLua<'lua>
|
||||
pub fn wrap_mut<F, A, R, E>(func: F) -> impl IntoLua
|
||||
where
|
||||
A: FromLuaMulti<'lua>,
|
||||
R: IntoLuaMulti<'lua>,
|
||||
F: FnMut(&'lua Lua, A) -> Result<R> + MaybeSend + 'static,
|
||||
F: LuaNativeFnMut<A, Output = StdResult<R, E>> + MaybeSend + 'static,
|
||||
A: FromLuaMulti,
|
||||
R: IntoLuaMulti,
|
||||
E: ExternalError,
|
||||
{
|
||||
let func = RefCell::new(func);
|
||||
WrappedFunction(Box::new(move |lua, nargs| unsafe {
|
||||
let mut func = func
|
||||
.try_borrow_mut()
|
||||
.map_err(|_| Error::RecursiveMutCallback)?;
|
||||
let mut func = func.try_borrow_mut().map_err(|_| Error::RecursiveMutCallback)?;
|
||||
let args = A::from_stack_args(nargs, 1, None, lua)?;
|
||||
func(lua, args)?.push_into_stack_multi(lua)
|
||||
func.call(args).into_lua_err()?.push_into_stack_multi(lua)
|
||||
}))
|
||||
}
|
||||
|
||||
/// Wraps a Rust async function or closure, returning an opaque type that implements [`IntoLua`] trait.
|
||||
/// Wraps a Rust function or closure, returning an opaque type that implements [`IntoLua`]
|
||||
/// trait.
|
||||
///
|
||||
/// This function is similar to [`Function::wrap`] but any returned `Result` will be converted
|
||||
/// to a `ok, err` tuple without throwing an exception.
|
||||
#[inline]
|
||||
pub fn wrap_raw<F, A>(func: F) -> impl IntoLua
|
||||
where
|
||||
F: LuaNativeFn<A> + MaybeSend + 'static,
|
||||
F::Output: IntoLuaMulti,
|
||||
A: FromLuaMulti,
|
||||
{
|
||||
WrappedFunction(Box::new(move |lua, nargs| unsafe {
|
||||
let args = A::from_stack_args(nargs, 1, None, lua)?;
|
||||
func.call(args).push_into_stack_multi(lua)
|
||||
}))
|
||||
}
|
||||
|
||||
/// Wraps a Rust mutable closure, returning an opaque type that implements [`IntoLua`] trait.
|
||||
///
|
||||
/// This function is similar to [`Function::wrap_mut`] but any returned `Result` will be
|
||||
/// converted to a `ok, err` tuple without throwing an exception.
|
||||
#[inline]
|
||||
pub fn wrap_raw_mut<F, A>(func: F) -> impl IntoLua
|
||||
where
|
||||
F: LuaNativeFnMut<A> + MaybeSend + 'static,
|
||||
F::Output: IntoLuaMulti,
|
||||
A: FromLuaMulti,
|
||||
{
|
||||
let func = RefCell::new(func);
|
||||
WrappedFunction(Box::new(move |lua, nargs| unsafe {
|
||||
let mut func = func.try_borrow_mut().map_err(|_| Error::RecursiveMutCallback)?;
|
||||
let args = A::from_stack_args(nargs, 1, None, lua)?;
|
||||
func.call(args).push_into_stack_multi(lua)
|
||||
}))
|
||||
}
|
||||
|
||||
/// Wraps a Rust async function or closure, returning an opaque type that implements [`IntoLua`]
|
||||
/// trait.
|
||||
#[cfg(feature = "async")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
|
||||
pub fn wrap_async<A, R, F, FR>(func: F) -> impl IntoLua<'lua>
|
||||
pub fn wrap_async<F, A, R, E>(func: F) -> impl IntoLua
|
||||
where
|
||||
A: FromLuaMulti<'lua>,
|
||||
R: IntoLuaMulti<'lua>,
|
||||
F: Fn(&'lua Lua, A) -> FR + MaybeSend + 'static,
|
||||
FR: Future<Output = Result<R>> + 'lua,
|
||||
F: LuaNativeAsyncFn<A, Output = StdResult<R, E>> + MaybeSend + 'static,
|
||||
A: FromLuaMulti,
|
||||
R: IntoLuaMulti,
|
||||
E: ExternalError,
|
||||
{
|
||||
WrappedAsyncFunction(Box::new(move |lua, args| unsafe {
|
||||
let args = match A::from_lua_args(args, 1, None, lua) {
|
||||
WrappedAsyncFunction(Box::new(move |rawlua, nargs| unsafe {
|
||||
let args = match A::from_stack_args(nargs, 1, None, rawlua) {
|
||||
Ok(args) => args,
|
||||
Err(e) => return Box::pin(future::err(e)),
|
||||
Err(e) => return Box::pin(future::ready(Err(e))),
|
||||
};
|
||||
let fut = func(lua, args);
|
||||
Box::pin(async move { fut.await?.push_into_stack_multi(lua) })
|
||||
let lua = rawlua.lua();
|
||||
let fut = func.call(args);
|
||||
Box::pin(async move { fut.await.into_lua_err()?.push_into_stack_multi(lua.raw_lua()) })
|
||||
}))
|
||||
}
|
||||
|
||||
/// Wraps a Rust async function or closure, returning an opaque type that implements [`IntoLua`]
|
||||
/// trait.
|
||||
///
|
||||
/// This function is similar to [`Function::wrap_async`] but any returned `Result` will be
|
||||
/// converted to a `ok, err` tuple without throwing an exception.
|
||||
#[cfg(feature = "async")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
|
||||
pub fn wrap_raw_async<F, A>(func: F) -> impl IntoLua
|
||||
where
|
||||
F: LuaNativeAsyncFn<A> + MaybeSend + 'static,
|
||||
F::Output: IntoLuaMulti,
|
||||
A: FromLuaMulti,
|
||||
{
|
||||
WrappedAsyncFunction(Box::new(move |rawlua, nargs| unsafe {
|
||||
let args = match A::from_stack_args(nargs, 1, None, rawlua) {
|
||||
Ok(args) => args,
|
||||
Err(e) => return Box::pin(future::ready(Err(e))),
|
||||
};
|
||||
let lua = rawlua.lua();
|
||||
let fut = func.call(args);
|
||||
Box::pin(async move { fut.await.push_into_stack_multi(lua.raw_lua()) })
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
impl<'lua> IntoLua<'lua> for WrappedFunction<'lua> {
|
||||
impl IntoLua for WrappedFunction {
|
||||
#[inline]
|
||||
fn into_lua(self, lua: &'lua Lua) -> Result<Value<'lua>> {
|
||||
lua.create_callback(self.0).map(Value::Function)
|
||||
fn into_lua(self, lua: &Lua) -> Result<Value> {
|
||||
lua.lock().create_callback(self.0).map(Value::Function)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "async")]
|
||||
impl<'lua> IntoLua<'lua> for WrappedAsyncFunction<'lua> {
|
||||
impl IntoLua for WrappedAsyncFunction {
|
||||
#[inline]
|
||||
fn into_lua(self, lua: &'lua Lua) -> Result<Value<'lua>> {
|
||||
lua.create_async_callback(self.0).map(Value::Function)
|
||||
fn into_lua(self, lua: &Lua) -> Result<Value> {
|
||||
lua.lock().create_async_callback(self.0).map(Value::Function)
|
||||
}
|
||||
}
|
||||
|
||||
impl LuaType for Function {
|
||||
const TYPE_ID: c_int = ffi::LUA_TFUNCTION;
|
||||
}
|
||||
|
||||
/// Future for asynchronous function calls.
|
||||
#[cfg(feature = "async")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
|
||||
#[must_use = "futures do nothing unless you `.await` or poll them"]
|
||||
pub struct AsyncCallFuture<R: FromLuaMulti>(Result<AsyncThread<R>>);
|
||||
|
||||
#[cfg(feature = "async")]
|
||||
impl<R: FromLuaMulti> AsyncCallFuture<R> {
|
||||
pub(crate) fn error(err: Error) -> Self {
|
||||
AsyncCallFuture(Err(err))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "async")]
|
||||
impl<R: FromLuaMulti> Future for AsyncCallFuture<R> {
|
||||
type Output = Result<R>;
|
||||
|
||||
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
||||
let this = self.get_mut();
|
||||
match &mut this.0 {
|
||||
Ok(thread) => pin!(thread).poll(cx),
|
||||
Err(err) => Poll::Ready(Err(err.clone())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A trait for types that can be used as Lua functions.
|
||||
pub trait LuaNativeFn<A: FromLuaMulti> {
|
||||
type Output;
|
||||
|
||||
fn call(&self, args: A) -> Self::Output;
|
||||
}
|
||||
|
||||
/// A trait for types with mutable state that can be used as Lua functions.
|
||||
pub trait LuaNativeFnMut<A: FromLuaMulti> {
|
||||
type Output;
|
||||
|
||||
fn call(&mut self, args: A) -> Self::Output;
|
||||
}
|
||||
|
||||
/// A trait for types that returns a future and can be used as Lua functions.
|
||||
#[cfg(feature = "async")]
|
||||
pub trait LuaNativeAsyncFn<A: FromLuaMulti> {
|
||||
type Output;
|
||||
|
||||
fn call(&self, args: A) -> impl Future<Output = Self::Output> + MaybeSend + 'static;
|
||||
}
|
||||
|
||||
macro_rules! impl_lua_native_fn {
|
||||
($($A:ident),*) => {
|
||||
impl<FN, $($A,)* R> LuaNativeFn<($($A,)*)> for FN
|
||||
where
|
||||
FN: Fn($($A,)*) -> R + MaybeSend + 'static,
|
||||
($($A,)*): FromLuaMulti,
|
||||
{
|
||||
type Output = R;
|
||||
|
||||
#[allow(non_snake_case)]
|
||||
fn call(&self, args: ($($A,)*)) -> Self::Output {
|
||||
let ($($A,)*) = args;
|
||||
self($($A,)*)
|
||||
}
|
||||
}
|
||||
|
||||
impl<FN, $($A,)* R> LuaNativeFnMut<($($A,)*)> for FN
|
||||
where
|
||||
FN: FnMut($($A,)*) -> R + MaybeSend + 'static,
|
||||
($($A,)*): FromLuaMulti,
|
||||
{
|
||||
type Output = R;
|
||||
|
||||
#[allow(non_snake_case)]
|
||||
fn call(&mut self, args: ($($A,)*)) -> Self::Output {
|
||||
let ($($A,)*) = args;
|
||||
self($($A,)*)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "async")]
|
||||
impl<FN, $($A,)* Fut, R> LuaNativeAsyncFn<($($A,)*)> for FN
|
||||
where
|
||||
FN: Fn($($A,)*) -> Fut + MaybeSend + 'static,
|
||||
($($A,)*): FromLuaMulti,
|
||||
Fut: Future<Output = R> + MaybeSend + 'static,
|
||||
{
|
||||
type Output = R;
|
||||
|
||||
#[allow(non_snake_case)]
|
||||
fn call(&self, args: ($($A,)*)) -> impl Future<Output = Self::Output> + MaybeSend + 'static {
|
||||
let ($($A,)*) = args;
|
||||
self($($A,)*)
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
impl_lua_native_fn!();
|
||||
impl_lua_native_fn!(A);
|
||||
impl_lua_native_fn!(A, B);
|
||||
impl_lua_native_fn!(A, B, C);
|
||||
impl_lua_native_fn!(A, B, C, D);
|
||||
impl_lua_native_fn!(A, B, C, D, E);
|
||||
impl_lua_native_fn!(A, B, C, D, E, F);
|
||||
impl_lua_native_fn!(A, B, C, D, E, F, G);
|
||||
impl_lua_native_fn!(A, B, C, D, E, F, G, H);
|
||||
impl_lua_native_fn!(A, B, C, D, E, F, G, H, I);
|
||||
impl_lua_native_fn!(A, B, C, D, E, F, G, H, I, J);
|
||||
impl_lua_native_fn!(A, B, C, D, E, F, G, H, I, J, K);
|
||||
impl_lua_native_fn!(A, B, C, D, E, F, G, H, I, J, K, L);
|
||||
impl_lua_native_fn!(A, B, C, D, E, F, G, H, I, J, K, L, M);
|
||||
impl_lua_native_fn!(A, B, C, D, E, F, G, H, I, J, K, L, M, N);
|
||||
impl_lua_native_fn!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O);
|
||||
impl_lua_native_fn!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P);
|
||||
|
||||
#[cfg(test)]
|
||||
mod assertions {
|
||||
use super::*;
|
||||
|
||||
#[cfg(not(feature = "send"))]
|
||||
static_assertions::assert_not_impl_any!(Function: Send);
|
||||
#[cfg(feature = "send")]
|
||||
static_assertions::assert_impl_all!(Function: Send, Sync);
|
||||
|
||||
#[cfg(all(feature = "unstable", not(feature = "send")))]
|
||||
static_assertions::assert_not_impl_any!(OwnedFunction: Send);
|
||||
#[cfg(all(feature = "async", feature = "send"))]
|
||||
static_assertions::assert_impl_all!(AsyncCallFuture<()>: Send);
|
||||
}
|
||||
|
||||
+108
-175
@@ -27,126 +27,145 @@
|
||||
//!
|
||||
//! # Serde support
|
||||
//!
|
||||
//! The [`LuaSerdeExt`] trait implemented for [`Lua`] allows conversion from Rust types to Lua values
|
||||
//! and vice versa using serde. Any user defined data type that implements [`serde::Serialize`] or
|
||||
//! [`serde::Deserialize`] can be converted.
|
||||
//! The [`LuaSerdeExt`] trait implemented for [`Lua`] allows conversion from Rust types to Lua
|
||||
//! values and vice versa using serde. Any user defined data type that implements
|
||||
//! [`serde::Serialize`] or [`serde::Deserialize`] can be converted.
|
||||
//! For convenience, additional functionality to handle `NULL` values and arrays is provided.
|
||||
//!
|
||||
//! The [`Value`] enum implements [`serde::Serialize`] trait to support serializing Lua values
|
||||
//! (including [`UserData`]) into Rust values.
|
||||
//! The [`Value`] enum and other types implement [`serde::Serialize`] trait to support serializing
|
||||
//! Lua values into Rust values.
|
||||
//!
|
||||
//! Requires `feature = "serialize"`.
|
||||
//! Requires `feature = "serde"`.
|
||||
//!
|
||||
//! # Async/await support
|
||||
//!
|
||||
//! The [`create_async_function`] allows creating non-blocking functions that returns [`Future`].
|
||||
//! Lua code with async capabilities can be executed by [`call_async`] family of functions or polling
|
||||
//! [`AsyncThread`] using any runtime (eg. Tokio).
|
||||
//! The [`Lua::create_async_function`] allows creating non-blocking functions that returns
|
||||
//! [`Future`]. Lua code with async capabilities can be executed by [`Function::call_async`] family
|
||||
//! of functions or polling [`AsyncThread`] using any runtime (eg. Tokio).
|
||||
//!
|
||||
//! Requires `feature = "async"`.
|
||||
//!
|
||||
//! # `Send` requirement
|
||||
//! By default `mlua` is `!Send`. This can be changed by enabling `feature = "send"` that adds `Send` requirement
|
||||
//! to [`Function`]s and [`UserData`].
|
||||
//! # `Send` and `Sync` support
|
||||
//!
|
||||
//! By default `mlua` is `!Send`. This can be changed by enabling `feature = "send"` that adds
|
||||
//! `Send` requirement to Rust functions and [`UserData`] types.
|
||||
//!
|
||||
//! In this case [`Lua`] object and their types can be send or used from other threads. Internally
|
||||
//! access to Lua VM is synchronized using a reentrant mutex that can be locked many times within
|
||||
//! the same thread.
|
||||
//!
|
||||
//! [Lua programming language]: https://www.lua.org/
|
||||
//! [`Lua`]: crate::Lua
|
||||
//! [executing]: crate::Chunk::exec
|
||||
//! [evaluating]: crate::Chunk::eval
|
||||
//! [globals]: crate::Lua::globals
|
||||
//! [`IntoLua`]: crate::IntoLua
|
||||
//! [`FromLua`]: crate::FromLua
|
||||
//! [`IntoLuaMulti`]: crate::IntoLuaMulti
|
||||
//! [`FromLuaMulti`]: crate::FromLuaMulti
|
||||
//! [`Function`]: crate::Function
|
||||
//! [`UserData`]: crate::UserData
|
||||
//! [`UserDataFields`]: crate::UserDataFields
|
||||
//! [`UserDataMethods`]: crate::UserDataMethods
|
||||
//! [`LuaSerdeExt`]: crate::LuaSerdeExt
|
||||
//! [`Value`]: crate::Value
|
||||
//! [`create_async_function`]: crate::Lua::create_async_function
|
||||
//! [`call_async`]: crate::Function::call_async
|
||||
//! [`AsyncThread`]: crate::AsyncThread
|
||||
//! [`Future`]: std::future::Future
|
||||
//! [`serde::Serialize`]: https://docs.serde.rs/serde/ser/trait.Serialize.html
|
||||
//! [`serde::Deserialize`]: https://docs.serde.rs/serde/de/trait.Deserialize.html
|
||||
//! [`AsyncThread`]: crate::thread::AsyncThread
|
||||
|
||||
// Deny warnings inside doc tests / examples. When this isn't present, rustdoc doesn't show *any*
|
||||
// warnings at all.
|
||||
#![doc(test(attr(warn(warnings))))] // FIXME: Remove this when rust-lang/rust#123748 is fixed
|
||||
#![cfg_attr(docsrs, feature(doc_cfg))]
|
||||
#![cfg_attr(not(send), allow(clippy::arc_with_non_send_sync))]
|
||||
#![allow(unsafe_op_in_unsafe_fn)]
|
||||
|
||||
#[macro_use]
|
||||
mod macros;
|
||||
|
||||
mod chunk;
|
||||
mod buffer;
|
||||
mod conversion;
|
||||
mod error;
|
||||
mod function;
|
||||
mod hook;
|
||||
mod lua;
|
||||
#[cfg(feature = "luau")]
|
||||
mod luau;
|
||||
mod memory;
|
||||
mod multi;
|
||||
mod scope;
|
||||
mod stdlib;
|
||||
mod string;
|
||||
mod table;
|
||||
mod thread;
|
||||
mod traits;
|
||||
mod types;
|
||||
mod userdata;
|
||||
mod userdata_ext;
|
||||
mod userdata_impl;
|
||||
mod util;
|
||||
mod value;
|
||||
mod vector;
|
||||
|
||||
pub mod chunk;
|
||||
pub mod debug;
|
||||
pub mod error;
|
||||
pub mod function;
|
||||
#[cfg(any(feature = "luau", doc))]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "luau")))]
|
||||
pub mod luau;
|
||||
pub mod prelude;
|
||||
pub mod state;
|
||||
pub mod string;
|
||||
pub mod table;
|
||||
pub mod thread;
|
||||
pub mod userdata;
|
||||
|
||||
pub use bstr::BString;
|
||||
pub use ffi::{self, lua_CFunction, lua_State};
|
||||
#[cfg(feature = "macros")]
|
||||
#[doc(hidden)]
|
||||
pub use inventory as __inventory;
|
||||
|
||||
pub use crate::chunk::{AsChunk, Chunk, ChunkMode};
|
||||
pub use crate::error::{Error, ErrorContext, ExternalError, ExternalResult, Result};
|
||||
pub use crate::function::{Function, FunctionInfo};
|
||||
pub use crate::hook::{Debug, DebugEvent, DebugNames, DebugSource, DebugStack};
|
||||
pub use crate::lua::{GCMode, Lua, LuaOptions};
|
||||
pub use crate::multi::Variadic;
|
||||
#[doc(inline)]
|
||||
pub use crate::error::{Error, Result};
|
||||
#[doc(inline)]
|
||||
pub use crate::function::Function;
|
||||
pub use crate::multi::{MultiValue, Variadic};
|
||||
pub use crate::scope::Scope;
|
||||
#[doc(inline)]
|
||||
pub use crate::state::{Lua, LuaOptions, WeakLua};
|
||||
pub use crate::stdlib::StdLib;
|
||||
pub use crate::string::String;
|
||||
pub use crate::table::{Table, TableExt, TablePairs, TableSequence};
|
||||
pub use crate::thread::{Thread, ThreadStatus};
|
||||
pub use crate::types::{AppDataRef, AppDataRefMut, Integer, LightUserData, Number, RegistryKey};
|
||||
pub use crate::userdata::{
|
||||
AnyUserData, MetaMethod, UserData, UserDataFields, UserDataMetatable, UserDataMethods,
|
||||
UserDataRef, UserDataRefMut,
|
||||
#[doc(inline)]
|
||||
pub use crate::string::{BorrowedBytes, BorrowedStr, LuaString};
|
||||
#[doc(inline)]
|
||||
pub use crate::table::Table;
|
||||
#[doc(inline)]
|
||||
pub use crate::thread::Thread;
|
||||
#[doc(inline)]
|
||||
pub use crate::traits::{FromLua, FromLuaMulti, IntoLua, IntoLuaMulti, ObjectLike};
|
||||
pub use crate::types::{
|
||||
AppDataRef, AppDataRefMut, Either, Integer, LightUserData, MaybeSend, MaybeSync, Number, RegistryKey,
|
||||
VmState,
|
||||
};
|
||||
#[doc(inline)]
|
||||
pub use crate::userdata::AnyUserData;
|
||||
pub use crate::value::{Nil, Value};
|
||||
|
||||
// Re-export some types to keep backward compatibility and avoid breaking changes in the public API.
|
||||
#[doc(hidden)]
|
||||
pub use crate::chunk::{AsChunk, Chunk, ChunkMode};
|
||||
#[cfg(feature = "luau")]
|
||||
#[doc(hidden)]
|
||||
pub use crate::chunk::{CompileConstant, Compiler};
|
||||
#[doc(hidden)]
|
||||
pub use crate::error::{ErrorContext, ExternalError, ExternalResult};
|
||||
#[doc(hidden)]
|
||||
pub use crate::string::LuaString as String;
|
||||
#[doc(hidden)]
|
||||
pub use crate::table::{TablePairs, TableSequence};
|
||||
#[doc(hidden)]
|
||||
pub use crate::thread::{ThreadEvent, ThreadStatus, ThreadTriggers};
|
||||
#[doc(hidden)]
|
||||
pub use crate::userdata::{
|
||||
MetaMethod, UserData, UserDataFields, UserDataMetatable, UserDataMethods, UserDataOwned, UserDataRef,
|
||||
UserDataRefMut, UserDataRegistry,
|
||||
};
|
||||
pub use crate::userdata_ext::AnyUserDataExt;
|
||||
pub use crate::userdata_impl::UserDataRegistry;
|
||||
pub use crate::value::{FromLua, FromLuaMulti, IntoLua, IntoLuaMulti, MultiValue, Nil, Value};
|
||||
|
||||
#[cfg(not(feature = "luau"))]
|
||||
pub use crate::hook::HookTriggers;
|
||||
#[doc(inline)]
|
||||
pub use crate::debug::HookTriggers;
|
||||
|
||||
#[cfg(any(feature = "luau", doc))]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "luau")))]
|
||||
pub use crate::{
|
||||
chunk::Compiler,
|
||||
function::CoverageInfo,
|
||||
types::{Vector, VmState},
|
||||
};
|
||||
pub use crate::{buffer::Buffer, vector::Vector};
|
||||
|
||||
#[cfg(feature = "async")]
|
||||
pub use crate::thread::AsyncThread;
|
||||
|
||||
#[cfg(feature = "serialize")]
|
||||
#[cfg(feature = "serde")]
|
||||
#[doc(hidden)]
|
||||
pub use crate::serde::{DeserializeOptions, SerializeOptions};
|
||||
#[cfg(feature = "serde")]
|
||||
#[doc(inline)]
|
||||
pub use crate::serde::{
|
||||
de::Options as DeserializeOptions, ser::Options as SerializeOptions, LuaSerdeExt,
|
||||
};
|
||||
pub use crate::{serde::LuaSerdeExt, value::SerializableValue};
|
||||
|
||||
#[cfg(feature = "serialize")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "serialize")))]
|
||||
#[cfg(feature = "serde")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
|
||||
pub mod serde;
|
||||
|
||||
#[cfg(feature = "mlua_derive")]
|
||||
@@ -154,65 +173,7 @@ pub mod serde;
|
||||
#[macro_use]
|
||||
extern crate mlua_derive;
|
||||
|
||||
// Unstable features
|
||||
#[cfg(feature = "unstable")]
|
||||
pub use crate::{
|
||||
function::OwnedFunction, string::OwnedString, table::OwnedTable, thread::OwnedThread,
|
||||
userdata::OwnedAnyUserData,
|
||||
};
|
||||
|
||||
/// Create a type that implements [`AsChunk`] and can capture Rust variables.
|
||||
///
|
||||
/// This macro allows to write Lua code directly in Rust code.
|
||||
///
|
||||
/// Rust variables can be referenced from Lua using `$` prefix, as shown in the example below.
|
||||
/// User's Rust types needs to implement [`UserData`] or [`IntoLua`] traits.
|
||||
///
|
||||
/// Captured variables are **moved** into the chunk.
|
||||
///
|
||||
/// ```
|
||||
/// use mlua::{Lua, Result, chunk};
|
||||
///
|
||||
/// fn main() -> Result<()> {
|
||||
/// let lua = Lua::new();
|
||||
/// let name = "Rustacean";
|
||||
/// lua.load(chunk! {
|
||||
/// print("hello, " .. $name)
|
||||
/// }).exec()
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// ## Syntax issues
|
||||
///
|
||||
/// Since the Rust tokenizer will tokenize Lua code, this imposes some restrictions.
|
||||
/// The main thing to remember is:
|
||||
///
|
||||
/// - Use double quoted strings (`""`) instead of single quoted strings (`''`).
|
||||
///
|
||||
/// (Single quoted strings only work if they contain a single character, since in Rust,
|
||||
/// `'a'` is a character literal).
|
||||
///
|
||||
/// - Using Lua comments `--` is not desirable in **stable** Rust and can have bad side effects.
|
||||
///
|
||||
/// This is because procedural macros have Line/Column information available only in
|
||||
/// **nightly** Rust. Instead, Lua chunks represented as a big single line of code in stable Rust.
|
||||
///
|
||||
/// As workaround, Rust comments `//` can be used.
|
||||
///
|
||||
/// Other minor limitations:
|
||||
///
|
||||
/// - Certain escape codes in string literals don't work.
|
||||
/// (Specifically: `\a`, `\b`, `\f`, `\v`, `\123` (octal escape codes), `\u`, and `\U`).
|
||||
///
|
||||
/// These are accepted: : `\\`, `\n`, `\t`, `\r`, `\xAB` (hex escape codes), and `\0`.
|
||||
///
|
||||
/// - The `//` (floor division) operator is unusable, as its start a comment.
|
||||
///
|
||||
/// Everything else should work.
|
||||
///
|
||||
/// [`AsChunk`]: crate::AsChunk
|
||||
/// [`UserData`]: crate::UserData
|
||||
/// [`IntoLua`]: crate::IntoLua
|
||||
#[doc = include_str!("../docs/chunk.md")]
|
||||
#[cfg(feature = "macros")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "macros")))]
|
||||
pub use mlua_derive::chunk;
|
||||
@@ -225,52 +186,24 @@ pub use mlua_derive::chunk;
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "macros")))]
|
||||
pub use mlua_derive::FromLua;
|
||||
|
||||
/// Registers Lua module entrypoint.
|
||||
///
|
||||
/// You can register multiple entrypoints as required.
|
||||
///
|
||||
/// ```
|
||||
/// use mlua::{Lua, Result, Table};
|
||||
///
|
||||
/// #[mlua::lua_module]
|
||||
/// fn my_module(lua: &Lua) -> Result<Table> {
|
||||
/// let exports = lua.create_table()?;
|
||||
/// exports.set("hello", "world")?;
|
||||
/// Ok(exports)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Internally in the code above the compiler defines C function `luaopen_my_module`.
|
||||
///
|
||||
/// You can also pass options to the attribute:
|
||||
///
|
||||
/// * name - name of the module, defaults to the name of the function
|
||||
///
|
||||
/// ```ignore
|
||||
/// #[mlua::lua_module(name = "alt_module")]
|
||||
/// fn my_module(lua: &Lua) -> Result<Table> {
|
||||
/// ...
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// * skip_memory_check - skip memory allocation checks for some operations.
|
||||
///
|
||||
/// In module mode, mlua runs in unknown environment and cannot say are there any memory
|
||||
/// limits or not. As result, some operations that require memory allocation runs in
|
||||
/// protected mode. Setting this attribute will improve performance of such operations
|
||||
/// with risk of having uncaught exceptions and memory leaks.
|
||||
///
|
||||
/// ```ignore
|
||||
/// #[mlua::lua_module(skip_memory_check)]
|
||||
/// fn my_module(lua: &Lua) -> Result<Table> {
|
||||
/// ...
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
#[cfg(any(feature = "module", docsrs))]
|
||||
#[doc = include_str!("../docs/UserData.md")]
|
||||
#[cfg(feature = "macros")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "macros")))]
|
||||
pub use mlua_derive::UserData;
|
||||
|
||||
#[doc(hidden)]
|
||||
#[cfg(feature = "macros")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "macros")))]
|
||||
pub use mlua_derive::userdata_impl;
|
||||
|
||||
#[doc = include_str!("../docs/lua_module.md")]
|
||||
#[cfg(all(feature = "mlua_derive", any(feature = "module", doc)))]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "module")))]
|
||||
pub use mlua_derive::lua_module;
|
||||
|
||||
#[cfg(all(feature = "module", feature = "send"))]
|
||||
compile_error!("`send` feature is not supported in module mode");
|
||||
|
||||
pub(crate) mod private {
|
||||
use super::*;
|
||||
|
||||
@@ -279,6 +212,6 @@ pub(crate) mod private {
|
||||
impl Sealed for Error {}
|
||||
impl<T> Sealed for std::result::Result<T, Error> {}
|
||||
impl Sealed for Lua {}
|
||||
impl Sealed for Table<'_> {}
|
||||
impl Sealed for AnyUserData<'_> {}
|
||||
impl Sealed for Table {}
|
||||
impl Sealed for AnyUserData {}
|
||||
}
|
||||
|
||||
-3667
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,178 @@
|
||||
use std::collections::HashMap;
|
||||
use std::hash::Hash;
|
||||
use std::mem;
|
||||
use std::os::raw::c_char;
|
||||
|
||||
use crate::state::ExtraData;
|
||||
|
||||
use super::json::{self, Json};
|
||||
|
||||
/// Represents a heap dump of a Luau memory state.
|
||||
#[cfg(any(feature = "luau", doc))]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "luau")))]
|
||||
pub struct HeapDump {
|
||||
data: Json<'static>, // refers to the contents of `buf`
|
||||
buf: Box<str>,
|
||||
}
|
||||
|
||||
impl HeapDump {
|
||||
/// Dumps the current Lua heap state.
|
||||
pub(crate) unsafe fn new(state: *mut ffi::lua_State) -> Option<Self> {
|
||||
unsafe extern "C" fn category_name(state: *mut ffi::lua_State, cat: u8) -> *const c_char {
|
||||
(&*ExtraData::get(state))
|
||||
.mem_categories
|
||||
.get(cat as usize)
|
||||
.map(|s| s.as_ptr())
|
||||
.unwrap_or(cstr!("unknown"))
|
||||
}
|
||||
|
||||
let mut buf = Vec::new();
|
||||
unsafe {
|
||||
let file = libc::tmpfile();
|
||||
if file.is_null() {
|
||||
return None;
|
||||
}
|
||||
ffi::lua_gcdump(state, file as *mut _, Some(category_name));
|
||||
libc::fseek(file, 0, libc::SEEK_END);
|
||||
let len = libc::ftell(file) as usize;
|
||||
libc::rewind(file);
|
||||
if len > 0 {
|
||||
buf.reserve(len);
|
||||
libc::fread(buf.as_mut_ptr() as *mut _, 1, len, file);
|
||||
buf.set_len(len);
|
||||
}
|
||||
libc::fclose(file);
|
||||
}
|
||||
|
||||
let buf = String::from_utf8(buf).ok()?.into_boxed_str();
|
||||
let data = json::parse(unsafe { mem::transmute::<&str, &'static str>(&buf) }).ok()?;
|
||||
Some(HeapDump { data, buf })
|
||||
}
|
||||
|
||||
/// Returns the raw JSON representation of the heap dump.
|
||||
///
|
||||
/// The JSON structure is an internal detail and may change in future versions.
|
||||
#[doc(hidden)]
|
||||
pub fn to_json(&self) -> &str {
|
||||
&self.buf
|
||||
}
|
||||
|
||||
/// Returns the total size of the Lua heap in bytes.
|
||||
pub fn size(&self) -> u64 {
|
||||
self.data["stats"]["size"].as_u64().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Returns a mapping from object type to (count, total size in bytes).
|
||||
///
|
||||
/// If `category` is provided, only objects in that category are considered.
|
||||
pub fn size_by_type<'a>(&'a self, category: Option<&str>) -> HashMap<&'a str, (usize, u64)> {
|
||||
self.size_by_type_inner(category).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn size_by_type_inner<'a>(&'a self, category: Option<&str>) -> Option<HashMap<&'a str, (usize, u64)>> {
|
||||
let category_id = match category {
|
||||
// If we cannot find the category, return empty result
|
||||
Some(cat) => Some(self.find_category_id(cat)?),
|
||||
None => None,
|
||||
};
|
||||
|
||||
let mut size_by_type = HashMap::new();
|
||||
let objects = self.data["objects"].as_object()?;
|
||||
for obj in objects.values() {
|
||||
if let Some(cat_id) = category_id
|
||||
&& obj["cat"].as_i64()? != cat_id
|
||||
{
|
||||
continue;
|
||||
}
|
||||
update_size(&mut size_by_type, obj["type"].as_str()?, obj["size"].as_u64()?);
|
||||
}
|
||||
Some(size_by_type)
|
||||
}
|
||||
|
||||
/// Returns a mapping from category name to total size in bytes.
|
||||
pub fn size_by_category(&self) -> HashMap<&str, u64> {
|
||||
let mut size_by_category = HashMap::new();
|
||||
if let Some(categories) = self.data["stats"]["categories"].as_object() {
|
||||
for cat in categories.values() {
|
||||
if let Some(cat_name) = cat["name"].as_str() {
|
||||
size_by_category.insert(cat_name, cat["size"].as_u64().unwrap_or_default());
|
||||
}
|
||||
}
|
||||
}
|
||||
size_by_category
|
||||
}
|
||||
|
||||
/// Returns a mapping from userdata type to (count, total size in bytes).
|
||||
pub fn size_by_userdata<'a>(&'a self, category: Option<&str>) -> HashMap<&'a str, (usize, u64)> {
|
||||
self.size_by_userdata_inner(category).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn size_by_userdata_inner<'a>(
|
||||
&'a self,
|
||||
category: Option<&str>,
|
||||
) -> Option<HashMap<&'a str, (usize, u64)>> {
|
||||
let category_id = match category {
|
||||
// If we cannot find the category, return empty result
|
||||
Some(cat) => Some(self.find_category_id(cat)?),
|
||||
None => None,
|
||||
};
|
||||
|
||||
let mut size_by_userdata = HashMap::new();
|
||||
let objects = self.data["objects"].as_object()?;
|
||||
for obj in objects.values() {
|
||||
if obj["type"] != "userdata" {
|
||||
continue;
|
||||
}
|
||||
if let Some(cat_id) = category_id
|
||||
&& obj["cat"].as_i64()? != cat_id
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// Determine userdata type from metatable
|
||||
let mut ud_type = "unknown";
|
||||
if let Some(metatable_addr) = obj["metatable"].as_str()
|
||||
&& let Some(t) = get_key(objects, &objects[metatable_addr], "__type")
|
||||
{
|
||||
ud_type = t;
|
||||
}
|
||||
update_size(&mut size_by_userdata, ud_type, obj["size"].as_u64()?);
|
||||
}
|
||||
Some(size_by_userdata)
|
||||
}
|
||||
|
||||
/// Finds the category ID for a given category name.
|
||||
fn find_category_id(&self, category: &str) -> Option<i64> {
|
||||
let categories = self.data["stats"]["categories"].as_object()?;
|
||||
for (cat_id, cat) in categories {
|
||||
if cat["name"].as_str() == Some(category) {
|
||||
return cat_id.parse().ok();
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Updates the size mapping for a given key.
|
||||
fn update_size<K: Eq + Hash>(size_type: &mut HashMap<K, (usize, u64)>, key: K, size: u64) {
|
||||
let (count, total_size) = size_type.entry(key).or_insert((0, 0));
|
||||
*count += 1;
|
||||
*total_size += size;
|
||||
}
|
||||
|
||||
/// Retrieves the value associated with a given `key` from a Lua table `tbl`.
|
||||
fn get_key<'a>(objects: &'a HashMap<&'a str, Json>, tbl: &Json, key: &str) -> Option<&'a str> {
|
||||
let pairs = tbl["pairs"].as_array()?;
|
||||
for kv in pairs.chunks_exact(2) {
|
||||
#[rustfmt::skip]
|
||||
let (Some(key_addr), Some(val_addr)) = (kv[0].as_str(), kv[1].as_str()) else { continue; };
|
||||
if objects[key_addr]["type"] == "string" && objects[key_addr]["data"].as_str() == Some(key) {
|
||||
if objects[val_addr]["type"] == "string" {
|
||||
return objects[val_addr]["data"].as_str();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
@@ -0,0 +1,327 @@
|
||||
use std::array;
|
||||
use std::collections::HashMap;
|
||||
use std::iter::Peekable;
|
||||
use std::ops::Index;
|
||||
use std::str::CharIndices;
|
||||
|
||||
// A simple JSON parser and representation.
|
||||
// This parser supports only a subset of JSON specification and is intended for Luau's use cases.
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub(crate) enum Json<'a> {
|
||||
Null,
|
||||
Bool(bool),
|
||||
Integer(i64),
|
||||
Number(f64),
|
||||
String(&'a str),
|
||||
Array(Vec<Json<'a>>),
|
||||
Object(HashMap<&'a str, Json<'a>>),
|
||||
}
|
||||
|
||||
impl<'a> Index<&str> for Json<'a> {
|
||||
type Output = Json<'a>;
|
||||
|
||||
fn index(&self, key: &str) -> &Self::Output {
|
||||
match self {
|
||||
Json::Object(map) => map.get(key).unwrap_or(&Json::Null),
|
||||
_ => &Json::Null,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq<&str> for Json<'_> {
|
||||
fn eq(&self, other: &&str) -> bool {
|
||||
matches!(self, Json::String(s) if s == other)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Json<'a> {
|
||||
pub(crate) fn as_str(&self) -> Option<&'a str> {
|
||||
match self {
|
||||
Json::String(s) => Some(s),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn as_i64(&self) -> Option<i64> {
|
||||
match self {
|
||||
Json::Integer(i) => Some(*i),
|
||||
Json::Number(n) if n.fract() == 0.0 => Some(*n as i64),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn as_u64(&self) -> Option<u64> {
|
||||
self.as_i64()
|
||||
.and_then(|i| if i >= 0 { Some(i as u64) } else { None })
|
||||
}
|
||||
|
||||
pub(crate) fn as_array(&self) -> Option<&[Json<'a>]> {
|
||||
match self {
|
||||
Json::Array(arr) => Some(arr),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn as_object(&self) -> Option<&HashMap<&'a str, Json<'a>>> {
|
||||
match self {
|
||||
Json::Object(map) => Some(map),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn parse<'a>(s: &'a str) -> Result<Json<'a>, &'static str> {
|
||||
let s = s.trim_ascii();
|
||||
let mut chars = s.char_indices().peekable();
|
||||
let value = parse_value(s, &mut chars)?;
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
fn parse_value<'a>(s: &'a str, chars: &mut Peekable<CharIndices>) -> Result<Json<'a>, &'static str> {
|
||||
skip_whitespace(chars);
|
||||
match chars.peek() {
|
||||
Some((_, '{')) => parse_object(s, chars),
|
||||
Some((_, '[')) => parse_array(s, chars),
|
||||
Some((_, '"')) => parse_string(s, chars).map(Json::String),
|
||||
Some((_, 't' | 'f')) => parse_bool(chars),
|
||||
Some((_, 'n')) => parse_null(chars),
|
||||
Some((_, '-' | '0'..='9')) => parse_number(chars),
|
||||
Some(_) => Err("unexpected character"),
|
||||
None => Err("unexpected end of input"),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_object<'a>(s: &'a str, chars: &mut Peekable<CharIndices>) -> Result<Json<'a>, &'static str> {
|
||||
chars.next(); // consume '{'
|
||||
|
||||
let mut map = HashMap::new();
|
||||
skip_whitespace(chars);
|
||||
if matches!(chars.peek(), Some((_, '}'))) {
|
||||
chars.next();
|
||||
return Ok(Json::Object(map));
|
||||
}
|
||||
loop {
|
||||
skip_whitespace(chars);
|
||||
let key = parse_string(s, chars)?;
|
||||
skip_whitespace(chars);
|
||||
if !matches!(chars.next(), Some((_, ':'))) {
|
||||
return Err("expected ':'");
|
||||
}
|
||||
let value = parse_value(s, chars)?;
|
||||
map.insert(key, value);
|
||||
skip_whitespace(chars);
|
||||
match chars.next() {
|
||||
Some((_, ',')) => continue,
|
||||
Some((_, '}')) => break,
|
||||
_ => return Err("expected ',' or '}'"),
|
||||
}
|
||||
}
|
||||
Ok(Json::Object(map))
|
||||
}
|
||||
|
||||
fn parse_array<'a>(s: &'a str, chars: &mut Peekable<CharIndices>) -> Result<Json<'a>, &'static str> {
|
||||
chars.next(); // consume '['
|
||||
|
||||
let mut arr = Vec::new();
|
||||
skip_whitespace(chars);
|
||||
if matches!(chars.peek(), Some((_, ']'))) {
|
||||
chars.next();
|
||||
return Ok(Json::Array(arr));
|
||||
}
|
||||
loop {
|
||||
skip_whitespace(chars);
|
||||
arr.push(parse_value(s, chars)?);
|
||||
skip_whitespace(chars);
|
||||
match chars.next() {
|
||||
Some((_, ',')) => continue,
|
||||
Some((_, ']')) => return Ok(Json::Array(arr)),
|
||||
_ => return Err("expected ',' or ']'"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_string<'a>(s: &'a str, chars: &mut Peekable<CharIndices>) -> Result<&'a str, &'static str> {
|
||||
if !matches!(chars.next(), Some((_, '"'))) {
|
||||
return Err("expected string starting with '\"'");
|
||||
}
|
||||
let start = chars.peek().map(|(i, _)| *i).unwrap_or(0);
|
||||
for (i, c) in chars {
|
||||
if c == '"' {
|
||||
return Ok(&s[start..i]);
|
||||
}
|
||||
}
|
||||
Err("unterminated string")
|
||||
}
|
||||
|
||||
fn parse_number(chars: &mut Peekable<CharIndices>) -> Result<Json<'static>, &'static str> {
|
||||
let mut is_float = false;
|
||||
let mut num = String::new();
|
||||
while let Some((_, c @ ('0'..='9' | '-' | '.' | 'e' | 'E' | '+'))) = chars.peek() {
|
||||
num.push(*c);
|
||||
is_float = is_float || matches!(c, '.' | 'e' | 'E');
|
||||
chars.next();
|
||||
}
|
||||
if !is_float {
|
||||
let i = num.parse::<i64>().map_err(|_| "invalid integer")?;
|
||||
return Ok(Json::Integer(i));
|
||||
}
|
||||
let n = num.parse::<f64>().map_err(|_| "invalid number")?;
|
||||
Ok(Json::Number(n))
|
||||
}
|
||||
|
||||
fn parse_bool(chars: &mut Peekable<CharIndices>) -> Result<Json<'static>, &'static str> {
|
||||
let bool = next_chars(chars);
|
||||
if bool == [Some('t'), Some('r'), Some('u'), Some('e')] {
|
||||
return Ok(Json::Bool(true));
|
||||
}
|
||||
if bool == [Some('f'), Some('a'), Some('l'), Some('s')] && matches!(chars.next(), Some((_, 'e'))) {
|
||||
return Ok(Json::Bool(false));
|
||||
}
|
||||
Err("invalid boolean literal")
|
||||
}
|
||||
|
||||
fn parse_null(chars: &mut Peekable<CharIndices>) -> Result<Json<'static>, &'static str> {
|
||||
if next_chars(chars) == [Some('n'), Some('u'), Some('l'), Some('l')] {
|
||||
return Ok(Json::Null);
|
||||
}
|
||||
Err("invalid \"null\" literal")
|
||||
}
|
||||
|
||||
fn skip_whitespace(chars: &mut Peekable<CharIndices>) {
|
||||
while let Some((_, ' ' | '\n' | '\r' | '\t')) = chars.peek() {
|
||||
chars.next();
|
||||
}
|
||||
}
|
||||
|
||||
fn next_chars<const N: usize>(chars: &mut Peekable<CharIndices>) -> [Option<char>; N] {
|
||||
array::from_fn(|_| chars.next().map(|(_, c)| c))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_parse() {
|
||||
assert_eq!(parse("null").unwrap(), Json::Null);
|
||||
assert_eq!(parse("true").unwrap(), Json::Bool(true));
|
||||
assert_eq!(parse("false").unwrap(), Json::Bool(false));
|
||||
assert_eq!(parse("42").unwrap(), Json::Integer(42));
|
||||
assert_eq!(parse("42.0").unwrap(), Json::Number(42.0));
|
||||
assert_eq!(parse(r#""hello""#).unwrap(), Json::String("hello"));
|
||||
assert_eq!(
|
||||
parse("[1,2.0,3]").unwrap(),
|
||||
Json::Array(vec![Json::Integer(1), Json::Number(2.0), Json::Integer(3)])
|
||||
);
|
||||
let mut obj = HashMap::new();
|
||||
obj.insert("key", Json::String("value"));
|
||||
assert_eq!(parse(r#"{"key":"value"}"#).unwrap(), Json::Object(obj));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_whitespace_handling() {
|
||||
assert_eq!(parse(" null ").unwrap(), Json::Null);
|
||||
assert_eq!(parse(" true ").unwrap(), Json::Bool(true));
|
||||
assert_eq!(
|
||||
parse(" [ 1 , 2.0 , 3 ] ").unwrap(),
|
||||
Json::Array(vec![Json::Integer(1), Json::Number(2.0), Json::Integer(3)])
|
||||
);
|
||||
let mut obj = HashMap::new();
|
||||
obj.insert("key", Json::String("value"));
|
||||
assert_eq!(parse(r#" { "key" : "value" } "#).unwrap(), Json::Object(obj));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_empty_collections() {
|
||||
assert_eq!(parse("[]").unwrap(), Json::Array(vec![]));
|
||||
assert_eq!(parse("{}").unwrap(), Json::Object(HashMap::new()));
|
||||
assert_eq!(parse("[ ]").unwrap(), Json::Array(vec![]));
|
||||
assert_eq!(parse("{ }").unwrap(), Json::Object(HashMap::new()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_nested_structures() {
|
||||
assert_eq!(
|
||||
parse(r#"{"nested":{"inner":"value"}}"#).unwrap(),
|
||||
Json::Object({
|
||||
let mut outer = HashMap::new();
|
||||
let mut inner = HashMap::new();
|
||||
inner.insert("inner", Json::String("value"));
|
||||
outer.insert("nested", Json::Object(inner));
|
||||
outer
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
parse("[[1,2],[3,4]]").unwrap(),
|
||||
Json::Array(vec![
|
||||
Json::Array(vec![Json::Integer(1), Json::Integer(2)]),
|
||||
Json::Array(vec![Json::Integer(3), Json::Integer(4)])
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_numbers() {
|
||||
assert_eq!(parse("0").unwrap(), Json::Integer(0));
|
||||
assert_eq!(parse("-42").unwrap(), Json::Integer(-42));
|
||||
assert_eq!(parse("3.14").unwrap(), Json::Number(3.14));
|
||||
assert_eq!(parse("-3.14").unwrap(), Json::Number(-3.14));
|
||||
assert_eq!(parse("1e10").unwrap(), Json::Number(1e10));
|
||||
assert_eq!(parse("1E10").unwrap(), Json::Number(1E10));
|
||||
assert_eq!(parse("1e-10").unwrap(), Json::Number(1e-10));
|
||||
assert_eq!(parse("1.5e+10").unwrap(), Json::Number(1.5e+10));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_strings() {
|
||||
assert_eq!(parse(r#""""#).unwrap(), Json::String(""));
|
||||
assert_eq!(parse(r#""hello world""#).unwrap(), Json::String("hello world"));
|
||||
assert_eq!(
|
||||
parse(r#""with spaces and 123""#).unwrap(),
|
||||
Json::String("with spaces and 123")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_mixed_array() {
|
||||
assert_eq!(
|
||||
parse(r#"[null, true, false, 35.1, 42, "text", [], {}]"#).unwrap(),
|
||||
Json::Array(vec![
|
||||
Json::Null,
|
||||
Json::Bool(true),
|
||||
Json::Bool(false),
|
||||
Json::Number(35.1),
|
||||
Json::Integer(42),
|
||||
Json::String("text"),
|
||||
Json::Array(vec![]),
|
||||
Json::Object(HashMap::new())
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_object_multiple_keys() {
|
||||
let mut obj = HashMap::new();
|
||||
obj.insert("a", Json::Integer(1));
|
||||
obj.insert("b", Json::Bool(true));
|
||||
obj.insert("c", Json::Null);
|
||||
assert_eq!(parse(r#"{"a":1,"b":true,"c":null}"#).unwrap(), Json::Object(obj));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_error_cases() {
|
||||
assert!(parse("").is_err());
|
||||
assert!(parse("nul").is_err());
|
||||
assert!(parse("tru").is_err()); // typos:ignore
|
||||
assert!(parse("fals").is_err()); // typos:ignore
|
||||
assert!(parse(r#""unterminated"#).is_err());
|
||||
assert!(parse("[1,2,]").is_err());
|
||||
assert!(parse(r#"{"key""#).is_err());
|
||||
assert!(parse(r#"{"key":"value""#).is_err());
|
||||
assert!(parse(r#"{"key":"value",}"#).is_err());
|
||||
assert!(parse("invalid").is_err());
|
||||
assert!(parse("[1 2]").is_err());
|
||||
assert!(parse(r#"{"key":"value" "key2":"value2"}"#).is_err());
|
||||
}
|
||||
}
|
||||
+106
-35
@@ -1,20 +1,90 @@
|
||||
use std::ffi::CStr;
|
||||
use std::os::raw::{c_float, c_int};
|
||||
//! Luau-specific extensions and types.
|
||||
//!
|
||||
//! This module provides Luau-specific functionality including custom [`require`] implementations,
|
||||
//! heap memory analysis, and Luau VM integration utilities.
|
||||
//!
|
||||
//! [`require`]: crate::Lua::create_require_function
|
||||
|
||||
use crate::error::Result;
|
||||
use crate::lua::Lua;
|
||||
use std::ffi::{CStr, CString};
|
||||
use std::os::raw::c_int;
|
||||
use std::ptr;
|
||||
|
||||
use crate::chunk::ChunkMode;
|
||||
use crate::error::{Error, Result};
|
||||
use crate::function::Function;
|
||||
use crate::state::{ExtraData, Lua, callback_error_ext};
|
||||
use crate::traits::{FromLuaMulti, IntoLua};
|
||||
use crate::types::MaybeSend;
|
||||
|
||||
pub use heap_dump::HeapDump;
|
||||
pub use require::{FsRequirer, NavigateError, Require};
|
||||
|
||||
// Since Luau has some missing standard functions, we re-implement them here
|
||||
|
||||
impl Lua {
|
||||
/// Create a custom Luau `require` function using provided [`Require`] implementation to find
|
||||
/// and load modules.
|
||||
#[cfg(any(feature = "luau", doc))]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "luau")))]
|
||||
pub fn create_require_function<R: Require + MaybeSend + 'static>(&self, require: R) -> Result<Function> {
|
||||
require::create_require_function(self, require)
|
||||
}
|
||||
|
||||
/// Set the memory category for subsequent allocations from this Lua state.
|
||||
///
|
||||
/// The category "main" is reserved for the default memory category.
|
||||
/// Maximum of 255 categories can be registered.
|
||||
/// The category is set per Lua thread (state) and affects all allocations made from that
|
||||
/// thread.
|
||||
///
|
||||
/// Return error if too many categories are registered or if the category name is invalid.
|
||||
///
|
||||
/// See [`Lua::heap_dump`] for tracking memory usage by category.
|
||||
#[cfg(any(feature = "luau", doc))]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "luau")))]
|
||||
pub fn set_memory_category(&self, category: &str) -> Result<()> {
|
||||
let lua = self.lock();
|
||||
|
||||
if category.contains(|c| !matches!(c, 'a'..='z' | 'A'..='Z' | '0'..='9' | '-' | '_')) {
|
||||
return Err(Error::runtime("invalid memory category name"));
|
||||
}
|
||||
let cat_id = unsafe {
|
||||
let extra = ExtraData::get(lua.state());
|
||||
match ((*extra).mem_categories.iter().enumerate())
|
||||
.find(|&(_, name)| name.as_bytes() == category.as_bytes())
|
||||
{
|
||||
Some((id, _)) => id as u8,
|
||||
None => {
|
||||
let new_id = (*extra).mem_categories.len() as u8;
|
||||
if new_id == 255 {
|
||||
return Err(Error::runtime("too many memory categories registered"));
|
||||
}
|
||||
(*extra).mem_categories.push(CString::new(category).unwrap());
|
||||
new_id
|
||||
}
|
||||
}
|
||||
};
|
||||
unsafe { ffi::lua_setmemcat(lua.state(), cat_id as i32) };
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Dumps the current Lua VM heap state.
|
||||
///
|
||||
/// The returned `HeapDump` can be used to analyze memory usage.
|
||||
/// It's recommended to call [`Lua::gc_collect`] before dumping the heap.
|
||||
#[cfg(any(feature = "luau", doc))]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "luau")))]
|
||||
pub fn heap_dump(&self) -> Result<HeapDump> {
|
||||
let lua = self.lock();
|
||||
unsafe { heap_dump::HeapDump::new(lua.state()).ok_or_else(|| Error::runtime("unable to dump heap")) }
|
||||
}
|
||||
|
||||
pub(crate) unsafe fn configure_luau(&self) -> Result<()> {
|
||||
let globals = self.globals();
|
||||
|
||||
globals.raw_set(
|
||||
"collectgarbage",
|
||||
self.create_c_function(lua_collectgarbage)?,
|
||||
)?;
|
||||
globals.raw_set("vector", self.create_c_function(lua_vector)?)?;
|
||||
globals.raw_set("collectgarbage", self.create_c_function(lua_collectgarbage)?)?;
|
||||
globals.raw_set("loadstring", self.create_c_function(lua_loadstring)?)?;
|
||||
|
||||
// Set `_VERSION` global to include version number
|
||||
// The environment variable `LUAU_VERSION` set by the build script
|
||||
@@ -22,11 +92,10 @@ impl Lua {
|
||||
globals.raw_set("_VERSION", format!("Luau {version}"))?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
// Enable default `require` implementation
|
||||
let require = self.create_require_function(FsRequirer::new())?;
|
||||
self.globals().raw_set("require", require)?;
|
||||
|
||||
pub(crate) fn disable_c_modules(&self) -> Result<()> {
|
||||
package::disable_dylibs(self);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -35,16 +104,17 @@ unsafe extern "C-unwind" fn lua_collectgarbage(state: *mut ffi::lua_State) -> c_
|
||||
let option = ffi::luaL_optstring(state, 1, cstr!("collect"));
|
||||
let option = CStr::from_ptr(option);
|
||||
let arg = ffi::luaL_optinteger(state, 2, 0);
|
||||
let is_sandboxed = (*ExtraData::get(state)).sandboxed;
|
||||
match option.to_str() {
|
||||
Ok("collect") => {
|
||||
Ok("collect") if !is_sandboxed => {
|
||||
ffi::lua_gc(state, ffi::LUA_GCCOLLECT, 0);
|
||||
0
|
||||
}
|
||||
Ok("stop") => {
|
||||
Ok("stop") if !is_sandboxed => {
|
||||
ffi::lua_gc(state, ffi::LUA_GCSTOP, 0);
|
||||
0
|
||||
}
|
||||
Ok("restart") => {
|
||||
Ok("restart") if !is_sandboxed => {
|
||||
ffi::lua_gc(state, ffi::LUA_GCRESTART, 0);
|
||||
0
|
||||
}
|
||||
@@ -54,12 +124,12 @@ unsafe extern "C-unwind" fn lua_collectgarbage(state: *mut ffi::lua_State) -> c_
|
||||
ffi::lua_pushnumber(state, kbytes + kbytes_rem / 1024.0);
|
||||
1
|
||||
}
|
||||
Ok("step") => {
|
||||
let res = ffi::lua_gc(state, ffi::LUA_GCSTEP, arg);
|
||||
Ok("step") if !is_sandboxed => {
|
||||
let res = ffi::lua_gc(state, ffi::LUA_GCSTEP, arg as _);
|
||||
ffi::lua_pushboolean(state, res);
|
||||
1
|
||||
}
|
||||
Ok("isrunning") => {
|
||||
Ok("isrunning") if !is_sandboxed => {
|
||||
let res = ffi::lua_gc(state, ffi::LUA_GCISRUNNING, 0);
|
||||
ffi::lua_pushboolean(state, res);
|
||||
1
|
||||
@@ -68,21 +138,22 @@ unsafe extern "C-unwind" fn lua_collectgarbage(state: *mut ffi::lua_State) -> c_
|
||||
}
|
||||
}
|
||||
|
||||
// Luau vector datatype constructor
|
||||
unsafe extern "C-unwind" fn lua_vector(state: *mut ffi::lua_State) -> c_int {
|
||||
let x = ffi::luaL_checknumber(state, 1) as c_float;
|
||||
let y = ffi::luaL_checknumber(state, 2) as c_float;
|
||||
let z = ffi::luaL_checknumber(state, 3) as c_float;
|
||||
#[cfg(feature = "luau-vector4")]
|
||||
let w = ffi::luaL_checknumber(state, 4) as c_float;
|
||||
|
||||
#[cfg(not(feature = "luau-vector4"))]
|
||||
ffi::lua_pushvector(state, x, y, z);
|
||||
#[cfg(feature = "luau-vector4")]
|
||||
ffi::lua_pushvector(state, x, y, z, w);
|
||||
1
|
||||
unsafe extern "C-unwind" fn lua_loadstring(state: *mut ffi::lua_State) -> c_int {
|
||||
callback_error_ext(state, ptr::null_mut(), false, move |extra, nargs| {
|
||||
let rawlua = (*extra).raw_lua();
|
||||
let (chunk, chunk_name) =
|
||||
<(String, Option<String>)>::from_stack_args(nargs, 1, Some("loadstring"), rawlua)?;
|
||||
let chunk_name = chunk_name.as_deref().unwrap_or("=(loadstring)");
|
||||
(rawlua.lua())
|
||||
.load(chunk)
|
||||
.set_name(chunk_name)
|
||||
.set_mode(ChunkMode::Text)
|
||||
.into_function()?
|
||||
.push_into_stack(rawlua)?;
|
||||
Ok(1)
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) use package::register_package_module;
|
||||
|
||||
mod package;
|
||||
mod heap_dump;
|
||||
mod json;
|
||||
mod require;
|
||||
|
||||
@@ -1,269 +0,0 @@
|
||||
use std::ffi::CStr;
|
||||
use std::fmt::Write;
|
||||
use std::os::raw::c_int;
|
||||
use std::path::{PathBuf, MAIN_SEPARATOR_STR};
|
||||
use std::string::String as StdString;
|
||||
use std::{env, fs};
|
||||
|
||||
use crate::chunk::ChunkMode;
|
||||
use crate::error::Result;
|
||||
use crate::lua::Lua;
|
||||
use crate::table::Table;
|
||||
use crate::types::RegistryKey;
|
||||
use crate::value::{IntoLua, Value};
|
||||
|
||||
#[cfg(unix)]
|
||||
use {libloading::Library, rustc_hash::FxHashMap};
|
||||
|
||||
//
|
||||
// Luau package module
|
||||
//
|
||||
|
||||
#[cfg(unix)]
|
||||
const TARGET_MLUA_LUAU_ABI_VERSION: u32 = 1;
|
||||
|
||||
#[cfg(all(unix, feature = "module"))]
|
||||
#[no_mangle]
|
||||
#[used]
|
||||
pub static MLUA_LUAU_ABI_VERSION: u32 = TARGET_MLUA_LUAU_ABI_VERSION;
|
||||
|
||||
// We keep reference to the `package` table in registry under this key
|
||||
struct PackageKey(RegistryKey);
|
||||
|
||||
// We keep reference to the loaded dylibs in application data
|
||||
#[cfg(unix)]
|
||||
struct LoadedDylibs(FxHashMap<PathBuf, Library>);
|
||||
|
||||
#[cfg(unix)]
|
||||
impl std::ops::Deref for LoadedDylibs {
|
||||
type Target = FxHashMap<PathBuf, Library>;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
impl std::ops::DerefMut for LoadedDylibs {
|
||||
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||
&mut self.0
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn register_package_module(lua: &Lua) -> Result<()> {
|
||||
// Create the package table and store it in app_data for later use (bypassing globals lookup)
|
||||
let package = lua.create_table()?;
|
||||
lua.set_app_data(PackageKey(lua.create_registry_value(package.clone())?));
|
||||
|
||||
// Set `package.path`
|
||||
let mut search_path = env::var("LUAU_PATH")
|
||||
.or_else(|_| env::var("LUA_PATH"))
|
||||
.unwrap_or_default();
|
||||
if search_path.is_empty() {
|
||||
search_path = "?.luau;?.lua".to_string();
|
||||
}
|
||||
package.raw_set("path", search_path)?;
|
||||
|
||||
// Set `package.cpath`
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let mut search_cpath = env::var("LUAU_CPATH")
|
||||
.or_else(|_| env::var("LUA_CPATH"))
|
||||
.unwrap_or_default();
|
||||
if search_cpath.is_empty() {
|
||||
if cfg!(any(target_os = "macos", target_os = "ios")) {
|
||||
search_cpath = "?.dylib".to_string();
|
||||
} else {
|
||||
search_cpath = "?.so".to_string();
|
||||
}
|
||||
}
|
||||
package.raw_set("cpath", search_cpath)?;
|
||||
}
|
||||
|
||||
// Set `package.loaded` (table with a list of loaded modules)
|
||||
let loaded = lua.create_table()?;
|
||||
package.raw_set("loaded", loaded.clone())?;
|
||||
lua.set_named_registry_value("_LOADED", loaded)?;
|
||||
|
||||
// Set `package.loaders`
|
||||
let loaders = lua.create_sequence_from([lua.create_function(lua_loader)?])?;
|
||||
package.raw_set("loaders", loaders.clone())?;
|
||||
#[cfg(unix)]
|
||||
{
|
||||
loaders.push(lua.create_function(dylib_loader)?)?;
|
||||
lua.set_app_data(LoadedDylibs(FxHashMap::default()));
|
||||
}
|
||||
lua.set_named_registry_value("_LOADERS", loaders)?;
|
||||
|
||||
// Register the module and `require` function in globals
|
||||
let globals = lua.globals();
|
||||
globals.raw_set("package", package)?;
|
||||
globals.raw_set("require", unsafe { lua.create_c_function(lua_require)? })?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[allow(unused_variables)]
|
||||
pub(crate) fn disable_dylibs(lua: &Lua) {
|
||||
// Presence of `LoadedDylibs` in app data is used as a flag
|
||||
// to check whether binary modules are enabled
|
||||
#[cfg(unix)]
|
||||
lua.remove_app_data::<LoadedDylibs>();
|
||||
}
|
||||
|
||||
unsafe extern "C-unwind" fn lua_require(state: *mut ffi::lua_State) -> c_int {
|
||||
ffi::lua_settop(state, 1);
|
||||
let name = ffi::luaL_checkstring(state, 1);
|
||||
ffi::luaL_getsubtable(state, ffi::LUA_REGISTRYINDEX, cstr!("_LOADED")); // _LOADED is at index 2
|
||||
if ffi::lua_rawgetfield(state, 2, name) != ffi::LUA_TNIL {
|
||||
return 1; // module is already loaded
|
||||
}
|
||||
ffi::lua_pop(state, 1); // remove nil
|
||||
|
||||
// load the module
|
||||
let err_buf = ffi::lua_newuserdata_t::<StdString>(state);
|
||||
err_buf.write(StdString::new());
|
||||
ffi::luaL_getsubtable(state, ffi::LUA_REGISTRYINDEX, cstr!("_LOADERS")); // _LOADERS is at index 3
|
||||
for i in 1.. {
|
||||
if ffi::lua_rawgeti(state, -1, i) == ffi::LUA_TNIL {
|
||||
// no more loaders?
|
||||
if (*err_buf).is_empty() {
|
||||
ffi::luaL_error(state, cstr!("module '%s' not found"), name);
|
||||
} else {
|
||||
let bytes = (*err_buf).as_bytes();
|
||||
let extra = ffi::lua_pushlstring(state, bytes.as_ptr() as *const _, bytes.len());
|
||||
ffi::luaL_error(state, cstr!("module '%s' not found:%s"), name, extra);
|
||||
}
|
||||
}
|
||||
ffi::lua_pushvalue(state, 1); // name arg
|
||||
ffi::lua_call(state, 1, 2); // call loader
|
||||
match ffi::lua_type(state, -2) {
|
||||
ffi::LUA_TFUNCTION => break, // loader found
|
||||
ffi::LUA_TSTRING => {
|
||||
// error message
|
||||
let msg = ffi::lua_tostring(state, -2);
|
||||
let msg = CStr::from_ptr(msg).to_string_lossy();
|
||||
_ = write!(&mut *err_buf, "\n\t{msg}");
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
ffi::lua_pop(state, 2); // remove both results
|
||||
}
|
||||
ffi::lua_pushvalue(state, 1); // name is 1st argument to module loader
|
||||
ffi::lua_rotate(state, -2, 1); // loader data <-> name
|
||||
|
||||
// stack: ...; loader function; module name; loader data
|
||||
ffi::lua_call(state, 2, 1);
|
||||
// stack: ...; result from loader function
|
||||
if ffi::lua_isnil(state, -1) != 0 {
|
||||
ffi::lua_pop(state, 1);
|
||||
ffi::lua_pushboolean(state, 1); // use true as result
|
||||
}
|
||||
ffi::lua_pushvalue(state, -1); // make copy of entrypoint result
|
||||
ffi::lua_setfield(state, 2, name); /* _LOADED[name] = returned value */
|
||||
1
|
||||
}
|
||||
|
||||
/// Searches for the given `name` in the given `path`.
|
||||
///
|
||||
/// `path` is a string containing a sequence of templates separated by semicolons.
|
||||
fn package_searchpath(name: &str, search_path: &str, try_prefix: bool) -> Option<PathBuf> {
|
||||
let mut names = vec![name.replace('.', MAIN_SEPARATOR_STR)];
|
||||
if try_prefix && name.contains('.') {
|
||||
let prefix = name.split_once('.').map(|(prefix, _)| prefix).unwrap();
|
||||
names.push(prefix.to_string());
|
||||
}
|
||||
for path in search_path.split(';') {
|
||||
for name in &names {
|
||||
let file_path = PathBuf::from(path.replace('?', name));
|
||||
if let Ok(true) = fs::metadata(&file_path).map(|m| m.is_file()) {
|
||||
return Some(file_path);
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
//
|
||||
// Module loaders
|
||||
//
|
||||
|
||||
/// Tries to load a lua (text) file
|
||||
fn lua_loader(lua: &Lua, modname: StdString) -> Result<Value> {
|
||||
let package = {
|
||||
let key = lua.app_data_ref::<PackageKey>().unwrap();
|
||||
lua.registry_value::<Table>(&key.0)
|
||||
}?;
|
||||
let search_path = package.get::<_, StdString>("path").unwrap_or_default();
|
||||
|
||||
if let Some(file_path) = package_searchpath(&modname, &search_path, false) {
|
||||
match fs::read(&file_path) {
|
||||
Ok(buf) => {
|
||||
return lua
|
||||
.load(&buf)
|
||||
.set_name(&format!("={}", file_path.display()))
|
||||
.set_mode(ChunkMode::Text)
|
||||
.into_function()
|
||||
.map(Value::Function);
|
||||
}
|
||||
Err(err) => {
|
||||
return format!("cannot open '{}': {err}", file_path.display()).into_lua(lua);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Value::Nil)
|
||||
}
|
||||
|
||||
/// Tries to load a dynamic library
|
||||
#[cfg(unix)]
|
||||
fn dylib_loader(lua: &Lua, modname: StdString) -> Result<Value> {
|
||||
let package = {
|
||||
let key = lua.app_data_ref::<PackageKey>().unwrap();
|
||||
lua.registry_value::<Table>(&key.0)
|
||||
}?;
|
||||
let search_cpath = package.get::<_, StdString>("cpath").unwrap_or_default();
|
||||
|
||||
let find_symbol = |lib: &Library| unsafe {
|
||||
if let Ok(entry) = lib.get::<ffi::lua_CFunction>(format!("luaopen_{modname}\0").as_bytes())
|
||||
{
|
||||
return lua.create_c_function(*entry).map(Value::Function);
|
||||
}
|
||||
// Try all in one mode
|
||||
if let Ok(entry) = lib.get::<ffi::lua_CFunction>(
|
||||
format!("luaopen_{}\0", modname.replace('.', "_")).as_bytes(),
|
||||
) {
|
||||
return lua.create_c_function(*entry).map(Value::Function);
|
||||
}
|
||||
"cannot find module entrypoint".into_lua(lua)
|
||||
};
|
||||
|
||||
if let Some(file_path) = package_searchpath(&modname, &search_cpath, true) {
|
||||
let file_path = file_path.canonicalize()?;
|
||||
// Load the library and check for symbol
|
||||
unsafe {
|
||||
let mut loaded_dylibs = match lua.app_data_mut::<LoadedDylibs>() {
|
||||
Some(loaded_dylibs) => loaded_dylibs,
|
||||
None => return "dynamic libraries are disabled in safe mode".into_lua(lua),
|
||||
};
|
||||
// Check if it's already loaded
|
||||
if let Some(lib) = loaded_dylibs.get(&file_path) {
|
||||
return find_symbol(lib);
|
||||
}
|
||||
if let Ok(lib) = Library::new(&file_path) {
|
||||
// Check version
|
||||
let mod_version = lib.get::<*const u32>(b"MLUA_LUAU_ABI_VERSION");
|
||||
let mod_version = mod_version.map(|v| **v).unwrap_or_default();
|
||||
if mod_version != TARGET_MLUA_LUAU_ABI_VERSION {
|
||||
let err = format!("wrong module ABI version (expected {TARGET_MLUA_LUAU_ABI_VERSION}, got {mod_version})");
|
||||
return err.into_lua(lua);
|
||||
}
|
||||
let symbol = find_symbol(&lib);
|
||||
loaded_dylibs.insert(file_path, lib);
|
||||
return symbol;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Value::Nil)
|
||||
}
|
||||
@@ -0,0 +1,512 @@
|
||||
use std::cell::RefCell;
|
||||
use std::ffi::CStr;
|
||||
use std::io::Result as IoResult;
|
||||
use std::ops::{Deref, DerefMut};
|
||||
use std::os::raw::{c_char, c_int, c_void};
|
||||
use std::result::Result as StdResult;
|
||||
use std::{fmt, mem, ptr};
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::function::Function;
|
||||
use crate::state::{Lua, callback_error_ext};
|
||||
use crate::table::Table;
|
||||
use crate::types::MaybeSend;
|
||||
|
||||
pub use fs::FsRequirer;
|
||||
|
||||
/// An error that can occur during navigation in the Luau `require-by-string` system.
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum NavigateError {
|
||||
Ambiguous,
|
||||
NotFound,
|
||||
Other(Error),
|
||||
}
|
||||
|
||||
#[cfg(feature = "luau")]
|
||||
trait IntoNavigateResult {
|
||||
fn into_nav_result(self) -> Result<ffi::luarequire_NavigateResult>;
|
||||
}
|
||||
|
||||
#[cfg(feature = "luau")]
|
||||
impl IntoNavigateResult for StdResult<(), NavigateError> {
|
||||
fn into_nav_result(self) -> Result<ffi::luarequire_NavigateResult> {
|
||||
match self {
|
||||
Ok(()) => Ok(ffi::luarequire_NavigateResult::Success),
|
||||
Err(NavigateError::Ambiguous) => Ok(ffi::luarequire_NavigateResult::Ambiguous),
|
||||
Err(NavigateError::NotFound) => Ok(ffi::luarequire_NavigateResult::NotFound),
|
||||
Err(NavigateError::Other(err)) => Err(err),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Error> for NavigateError {
|
||||
fn from(err: Error) -> Self {
|
||||
NavigateError::Other(err)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "luau")]
|
||||
type WriteResult = ffi::luarequire_WriteResult;
|
||||
|
||||
#[cfg(feature = "luau")]
|
||||
type ConfigStatus = ffi::luarequire_ConfigStatus;
|
||||
|
||||
/// A trait for handling modules loading and navigation in the Luau `require-by-string` system.
|
||||
pub trait Require {
|
||||
/// Returns `true` if "require" is permitted for the given chunk name.
|
||||
fn is_require_allowed(&self, chunk_name: &str) -> bool;
|
||||
|
||||
/// Resets the internal state to point at the requirer module.
|
||||
fn reset(&mut self, chunk_name: &str) -> StdResult<(), NavigateError>;
|
||||
|
||||
/// Resets the internal state to point at an aliased module.
|
||||
///
|
||||
/// This function received an exact path from a configuration file.
|
||||
/// It's only called when an alias's path cannot be resolved relative to its
|
||||
/// configuration file.
|
||||
fn jump_to_alias(&mut self, path: &str) -> StdResult<(), NavigateError>;
|
||||
|
||||
/// Provides an initial alias override opportunity prior to searching for
|
||||
/// configuration files.
|
||||
///
|
||||
/// If `Ok(())` is returned, alias resolution stops here and the internal state
|
||||
/// must point at the aliased location.
|
||||
fn to_alias_override(&mut self, _alias: &str) -> StdResult<(), NavigateError> {
|
||||
Err(NavigateError::NotFound)
|
||||
}
|
||||
|
||||
/// Provides a final opportunity to resolve an alias if it cannot be found in
|
||||
/// configuration files.
|
||||
///
|
||||
/// If `Ok(())` is returned, alias resolution stops here and the internal state
|
||||
/// must point at the aliased location.
|
||||
fn to_alias_fallback(&mut self, _alias: &str) -> StdResult<(), NavigateError> {
|
||||
Err(NavigateError::NotFound)
|
||||
}
|
||||
|
||||
// Navigate to parent directory
|
||||
fn to_parent(&mut self) -> StdResult<(), NavigateError>;
|
||||
|
||||
/// Navigate to the given child directory.
|
||||
fn to_child(&mut self, name: &str) -> StdResult<(), NavigateError>;
|
||||
|
||||
/// Returns whether the context is currently pointing at a module.
|
||||
fn has_module(&self) -> bool;
|
||||
|
||||
/// Provides a cache key representing the current module.
|
||||
///
|
||||
/// This function is only called if `has_module` returns true.
|
||||
fn cache_key(&self) -> String;
|
||||
|
||||
/// Returns whether a configuration is present in the current context.
|
||||
fn has_config(&self) -> bool;
|
||||
|
||||
/// Returns the contents of the configuration file in the current context.
|
||||
///
|
||||
/// This function is only called if `has_config` returns true.
|
||||
fn config(&self) -> IoResult<Vec<u8>>;
|
||||
|
||||
/// Returns a loader function for the current module, that when called, loads the module
|
||||
/// and returns the result.
|
||||
///
|
||||
/// Loader can be sync or async.
|
||||
/// This function is only called if `has_module` returns true.
|
||||
fn loader(&self, lua: &Lua) -> Result<Function>;
|
||||
}
|
||||
|
||||
impl fmt::Debug for dyn Require {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "<dyn Require>")
|
||||
}
|
||||
}
|
||||
|
||||
struct Context {
|
||||
require: Box<dyn Require>,
|
||||
config_cache: Option<IoResult<Vec<u8>>>,
|
||||
}
|
||||
|
||||
impl Deref for Context {
|
||||
type Target = dyn Require;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&*self.require
|
||||
}
|
||||
}
|
||||
|
||||
impl DerefMut for Context {
|
||||
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||
&mut *self.require
|
||||
}
|
||||
}
|
||||
|
||||
impl Context {
|
||||
fn new(require: impl Require + MaybeSend + 'static) -> Self {
|
||||
Context {
|
||||
require: Box::new(require),
|
||||
config_cache: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! try_borrow {
|
||||
($state:expr, $ctx:expr) => {
|
||||
match (*($ctx as *const RefCell<Context>)).try_borrow() {
|
||||
Ok(ctx) => ctx,
|
||||
Err(_) => ffi::luaL_error($state, cstr!("require context is already borrowed")),
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! try_borrow_mut {
|
||||
($state:expr, $ctx:expr) => {
|
||||
match (*($ctx as *const RefCell<Context>)).try_borrow_mut() {
|
||||
Ok(ctx) => ctx,
|
||||
Err(_) => ffi::luaL_error($state, cstr!("require context is already borrowed")),
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
#[cfg(feature = "luau")]
|
||||
pub(super) unsafe extern "C-unwind" fn init_config(config: *mut ffi::luarequire_Configuration) {
|
||||
if config.is_null() {
|
||||
return;
|
||||
}
|
||||
|
||||
unsafe extern "C-unwind" fn is_require_allowed(
|
||||
state: *mut ffi::lua_State,
|
||||
ctx: *mut c_void,
|
||||
requirer_chunkname: *const c_char,
|
||||
) -> bool {
|
||||
if requirer_chunkname.is_null() {
|
||||
return false;
|
||||
}
|
||||
|
||||
let this = try_borrow!(state, ctx);
|
||||
let chunk_name = CStr::from_ptr(requirer_chunkname).to_string_lossy();
|
||||
this.is_require_allowed(&chunk_name)
|
||||
}
|
||||
|
||||
unsafe extern "C-unwind" fn reset(
|
||||
state: *mut ffi::lua_State,
|
||||
ctx: *mut c_void,
|
||||
requirer_chunkname: *const c_char,
|
||||
) -> ffi::luarequire_NavigateResult {
|
||||
let mut this = try_borrow_mut!(state, ctx);
|
||||
let chunk_name = CStr::from_ptr(requirer_chunkname).to_string_lossy();
|
||||
callback_error_ext(state, ptr::null_mut(), true, move |_, _| {
|
||||
this.reset(&chunk_name).into_nav_result()
|
||||
})
|
||||
}
|
||||
|
||||
unsafe extern "C-unwind" fn jump_to_alias(
|
||||
state: *mut ffi::lua_State,
|
||||
ctx: *mut c_void,
|
||||
path: *const c_char,
|
||||
) -> ffi::luarequire_NavigateResult {
|
||||
let mut this = try_borrow_mut!(state, ctx);
|
||||
let path = CStr::from_ptr(path).to_string_lossy();
|
||||
callback_error_ext(state, ptr::null_mut(), true, move |_, _| {
|
||||
this.jump_to_alias(&path).into_nav_result()
|
||||
})
|
||||
}
|
||||
|
||||
unsafe extern "C-unwind" fn to_alias_override(
|
||||
state: *mut ffi::lua_State,
|
||||
ctx: *mut c_void,
|
||||
alias_unprefixed: *const c_char,
|
||||
) -> ffi::luarequire_NavigateResult {
|
||||
let mut this = try_borrow_mut!(state, ctx);
|
||||
let alias = CStr::from_ptr(alias_unprefixed).to_string_lossy();
|
||||
callback_error_ext(state, ptr::null_mut(), true, move |_, _| {
|
||||
this.to_alias_override(&alias).into_nav_result()
|
||||
})
|
||||
}
|
||||
|
||||
unsafe extern "C-unwind" fn to_alias_fallback(
|
||||
state: *mut ffi::lua_State,
|
||||
ctx: *mut c_void,
|
||||
alias_unprefixed: *const c_char,
|
||||
) -> ffi::luarequire_NavigateResult {
|
||||
let mut this = try_borrow_mut!(state, ctx);
|
||||
let alias = CStr::from_ptr(alias_unprefixed).to_string_lossy();
|
||||
callback_error_ext(state, ptr::null_mut(), true, move |_, _| {
|
||||
this.to_alias_fallback(&alias).into_nav_result()
|
||||
})
|
||||
}
|
||||
|
||||
unsafe extern "C-unwind" fn to_parent(
|
||||
state: *mut ffi::lua_State,
|
||||
ctx: *mut c_void,
|
||||
) -> ffi::luarequire_NavigateResult {
|
||||
let mut this = try_borrow_mut!(state, ctx);
|
||||
callback_error_ext(state, ptr::null_mut(), true, move |_, _| {
|
||||
this.to_parent().into_nav_result()
|
||||
})
|
||||
}
|
||||
|
||||
unsafe extern "C-unwind" fn to_child(
|
||||
state: *mut ffi::lua_State,
|
||||
ctx: *mut c_void,
|
||||
name: *const c_char,
|
||||
) -> ffi::luarequire_NavigateResult {
|
||||
let mut this = try_borrow_mut!(state, ctx);
|
||||
let name = CStr::from_ptr(name).to_string_lossy();
|
||||
callback_error_ext(state, ptr::null_mut(), true, move |_, _| {
|
||||
this.to_child(&name).into_nav_result()
|
||||
})
|
||||
}
|
||||
|
||||
unsafe extern "C-unwind" fn is_module_present(state: *mut ffi::lua_State, ctx: *mut c_void) -> bool {
|
||||
let this = try_borrow!(state, ctx);
|
||||
this.has_module()
|
||||
}
|
||||
|
||||
unsafe extern "C-unwind" fn get_chunkname(
|
||||
_state: *mut ffi::lua_State,
|
||||
_ctx: *mut c_void,
|
||||
buffer: *mut c_char,
|
||||
buffer_size: usize,
|
||||
size_out: *mut usize,
|
||||
) -> WriteResult {
|
||||
write_to_buffer(buffer, buffer_size, size_out, &[])
|
||||
}
|
||||
|
||||
unsafe extern "C-unwind" fn get_loadname(
|
||||
_state: *mut ffi::lua_State,
|
||||
_ctx: *mut c_void,
|
||||
buffer: *mut c_char,
|
||||
buffer_size: usize,
|
||||
size_out: *mut usize,
|
||||
) -> WriteResult {
|
||||
write_to_buffer(buffer, buffer_size, size_out, &[])
|
||||
}
|
||||
|
||||
unsafe extern "C-unwind" fn get_cache_key(
|
||||
state: *mut ffi::lua_State,
|
||||
ctx: *mut c_void,
|
||||
buffer: *mut c_char,
|
||||
buffer_size: usize,
|
||||
size_out: *mut usize,
|
||||
) -> WriteResult {
|
||||
let this = try_borrow!(state, ctx);
|
||||
let cache_key = this.cache_key();
|
||||
write_to_buffer(buffer, buffer_size, size_out, cache_key.as_bytes())
|
||||
}
|
||||
|
||||
unsafe extern "C-unwind" fn get_config_status(
|
||||
state: *mut ffi::lua_State,
|
||||
ctx: *mut c_void,
|
||||
) -> ConfigStatus {
|
||||
let mut this = try_borrow_mut!(state, ctx);
|
||||
if this.has_config() {
|
||||
this.config_cache = Some(this.config());
|
||||
if let Some(Ok(data)) = &this.config_cache {
|
||||
return detect_config_format(data);
|
||||
}
|
||||
}
|
||||
ConfigStatus::Absent
|
||||
}
|
||||
|
||||
unsafe extern "C-unwind" fn get_config(
|
||||
state: *mut ffi::lua_State,
|
||||
ctx: *mut c_void,
|
||||
buffer: *mut c_char,
|
||||
buffer_size: usize,
|
||||
size_out: *mut usize,
|
||||
) -> WriteResult {
|
||||
let mut this = try_borrow_mut!(state, ctx);
|
||||
let config = callback_error_ext(state, ptr::null_mut(), true, move |_, _| {
|
||||
Ok(this.config_cache.take().unwrap_or_else(|| this.config())?)
|
||||
});
|
||||
write_to_buffer(buffer, buffer_size, size_out, &config)
|
||||
}
|
||||
|
||||
unsafe extern "C-unwind" fn load(
|
||||
state: *mut ffi::lua_State,
|
||||
ctx: *mut c_void,
|
||||
_path: *const c_char,
|
||||
_chunkname: *const c_char,
|
||||
_loadname: *const c_char,
|
||||
) -> c_int {
|
||||
let this = try_borrow!(state, ctx);
|
||||
callback_error_ext(state, ptr::null_mut(), true, move |extra, _| {
|
||||
let rawlua = (*extra).raw_lua();
|
||||
let loader = this.loader(rawlua.lua())?;
|
||||
rawlua.push(loader)?;
|
||||
Ok(1)
|
||||
})
|
||||
}
|
||||
|
||||
(*config).is_require_allowed = is_require_allowed;
|
||||
(*config).reset = reset;
|
||||
(*config).jump_to_alias = jump_to_alias;
|
||||
(*config).to_alias_override = Some(to_alias_override);
|
||||
(*config).to_alias_fallback = Some(to_alias_fallback);
|
||||
(*config).to_parent = to_parent;
|
||||
(*config).to_child = to_child;
|
||||
(*config).is_module_present = is_module_present;
|
||||
(*config).get_chunkname = get_chunkname;
|
||||
(*config).get_loadname = get_loadname;
|
||||
(*config).get_cache_key = get_cache_key;
|
||||
(*config).get_config_status = get_config_status;
|
||||
(*config).get_alias = None;
|
||||
(*config).get_config = Some(get_config);
|
||||
(*config).load = load;
|
||||
}
|
||||
|
||||
/// Detect configuration file format (JSON or Luau)
|
||||
#[cfg(feature = "luau")]
|
||||
fn detect_config_format(data: &[u8]) -> ConfigStatus {
|
||||
let data = data.trim_ascii();
|
||||
if data.starts_with(b"{") {
|
||||
let data = &data[1..].trim_ascii_start();
|
||||
if data.starts_with(b"\"") || data == b"}" {
|
||||
return ConfigStatus::PresentJson;
|
||||
}
|
||||
}
|
||||
ConfigStatus::PresentLuau
|
||||
}
|
||||
|
||||
/// Helper function to write data to a buffer
|
||||
#[cfg(feature = "luau")]
|
||||
unsafe fn write_to_buffer(
|
||||
buffer: *mut c_char,
|
||||
buffer_size: usize,
|
||||
size_out: *mut usize,
|
||||
data: &[u8],
|
||||
) -> WriteResult {
|
||||
// the buffer must be null terminated as it's a c++ `std::string` data() buffer
|
||||
let is_null_terminated = data.last() == Some(&0);
|
||||
*size_out = data.len() + if is_null_terminated { 0 } else { 1 };
|
||||
if *size_out > buffer_size {
|
||||
return WriteResult::BufferTooSmall;
|
||||
}
|
||||
ptr::copy_nonoverlapping(data.as_ptr(), buffer as *mut _, data.len());
|
||||
if !is_null_terminated {
|
||||
*buffer.add(data.len()) = 0;
|
||||
}
|
||||
WriteResult::Success
|
||||
}
|
||||
|
||||
#[cfg(feature = "luau")]
|
||||
pub(super) fn create_require_function<R: Require + MaybeSend + 'static>(
|
||||
lua: &Lua,
|
||||
require: R,
|
||||
) -> Result<Function> {
|
||||
unsafe extern "C-unwind" fn find_current_file(state: *mut ffi::lua_State) -> c_int {
|
||||
let mut ar: ffi::lua_Debug = mem::zeroed();
|
||||
for level in 2.. {
|
||||
if ffi::lua_getinfo(state, level, cstr!("s"), &mut ar) == 0 {
|
||||
ffi::luaL_error(state, cstr!("require is not supported in this context"));
|
||||
}
|
||||
if CStr::from_ptr(ar.what) != c"C" {
|
||||
break;
|
||||
}
|
||||
}
|
||||
ffi::lua_pushstring(state, ar.source);
|
||||
1
|
||||
}
|
||||
|
||||
unsafe extern "C-unwind" fn get_cache_key(state: *mut ffi::lua_State) -> c_int {
|
||||
let ctx = ffi::lua_touserdata(state, ffi::lua_upvalueindex(1));
|
||||
let ctx = try_borrow!(state, ctx);
|
||||
let cache_key = ctx.cache_key();
|
||||
ffi::lua_pushlstring(state, cache_key.as_ptr() as *const _, cache_key.len());
|
||||
1
|
||||
}
|
||||
|
||||
let (get_cache_key, find_current_file, proxyrequire, registered_modules, loader_cache) = unsafe {
|
||||
lua.exec_raw::<(Function, Function, Function, Table, Table)>((), move |state| {
|
||||
let context = Context::new(require);
|
||||
let context_ptr = ffi::lua_newuserdata_t(state, RefCell::new(context));
|
||||
ffi::lua_pushcclosured(state, get_cache_key, cstr!("get_cache_key"), 1);
|
||||
ffi::lua_pushcfunctiond(state, find_current_file, cstr!("find_current_file"));
|
||||
ffi::luarequire_pushproxyrequire(state, init_config, context_ptr as *mut _);
|
||||
ffi::luaL_getsubtable(state, ffi::LUA_REGISTRYINDEX, ffi::LUA_REGISTERED_MODULES_TABLE);
|
||||
ffi::luaL_getsubtable(state, ffi::LUA_REGISTRYINDEX, cstr!("__MLUA_LOADER_CACHE"));
|
||||
})
|
||||
}?;
|
||||
|
||||
unsafe extern "C-unwind" fn error(state: *mut ffi::lua_State) -> c_int {
|
||||
ffi::luaL_where(state, 1);
|
||||
ffi::lua_pushvalue(state, 1);
|
||||
ffi::lua_concat(state, 2);
|
||||
ffi::lua_error(state);
|
||||
}
|
||||
|
||||
unsafe extern "C-unwind" fn r#type(state: *mut ffi::lua_State) -> c_int {
|
||||
ffi::lua_pushstring(state, ffi::lua_typename(state, ffi::lua_type(state, 1)));
|
||||
1
|
||||
}
|
||||
|
||||
unsafe extern "C-unwind" fn to_lowercase(state: *mut ffi::lua_State) -> c_int {
|
||||
let s = ffi::luaL_checkstring(state, 1);
|
||||
let s = CStr::from_ptr(s);
|
||||
if !s.to_bytes().iter().any(|&c| c.is_ascii_uppercase()) {
|
||||
// If the string does not contain any uppercase ASCII letters, return it as is
|
||||
return 1;
|
||||
}
|
||||
callback_error_ext(state, ptr::null_mut(), true, |extra, _| {
|
||||
let s = (s.to_bytes().iter())
|
||||
.map(|&c| c.to_ascii_lowercase())
|
||||
.collect::<bstr::BString>();
|
||||
(*extra).raw_lua().push(s).map(|_| 1)
|
||||
})
|
||||
}
|
||||
|
||||
let (error, r#type, to_lowercase) = unsafe {
|
||||
lua.exec_raw::<(Function, Function, Function)>((), move |state| {
|
||||
ffi::lua_pushcfunctiond(state, error, cstr!("error"));
|
||||
ffi::lua_pushcfunctiond(state, r#type, cstr!("type"));
|
||||
ffi::lua_pushcfunctiond(state, to_lowercase, cstr!("to_lowercase"));
|
||||
})
|
||||
}?;
|
||||
|
||||
// Prepare environment for the "require" function
|
||||
let env = lua.create_table_with_capacity(0, 7)?;
|
||||
env.raw_set("get_cache_key", get_cache_key)?;
|
||||
env.raw_set("find_current_file", find_current_file)?;
|
||||
env.raw_set("proxyrequire", proxyrequire)?;
|
||||
env.raw_set("REGISTERED_MODULES", registered_modules)?;
|
||||
env.raw_set("LOADER_CACHE", loader_cache)?;
|
||||
env.raw_set("error", error)?;
|
||||
env.raw_set("type", r#type)?;
|
||||
env.raw_set("to_lowercase", to_lowercase)?;
|
||||
|
||||
lua.load(
|
||||
r#"
|
||||
local path = ...
|
||||
if type(path) ~= "string" then
|
||||
error("bad argument #1 to 'require' (string expected, got " .. type(path) .. ")")
|
||||
end
|
||||
|
||||
-- Check if the module (path) is explicitly registered
|
||||
local maybe_result = REGISTERED_MODULES[to_lowercase(path)]
|
||||
if maybe_result ~= nil then
|
||||
return maybe_result
|
||||
end
|
||||
|
||||
local loader = proxyrequire(path, find_current_file())
|
||||
local cache_key = get_cache_key()
|
||||
-- Check if the loader result is already cached
|
||||
local result = LOADER_CACHE[cache_key]
|
||||
if result ~= nil then
|
||||
return result
|
||||
end
|
||||
|
||||
-- Call the loader function and cache the result
|
||||
result = loader()
|
||||
if result == nil then
|
||||
result = true
|
||||
end
|
||||
LOADER_CACHE[cache_key] = result
|
||||
return result
|
||||
"#,
|
||||
)
|
||||
.try_cache()
|
||||
.set_name("=__mlua_require")
|
||||
.set_environment(env)
|
||||
.into_function()
|
||||
}
|
||||
|
||||
mod fs;
|
||||
@@ -0,0 +1,278 @@
|
||||
use std::collections::VecDeque;
|
||||
use std::io::Result as IoResult;
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
use std::result::Result as StdResult;
|
||||
use std::{env, fs};
|
||||
|
||||
use crate::error::Result;
|
||||
use crate::function::Function;
|
||||
use crate::state::Lua;
|
||||
|
||||
use super::{NavigateError, Require};
|
||||
|
||||
/// The standard implementation of Luau `require-by-string` navigation.
|
||||
#[derive(Default, Debug)]
|
||||
pub struct FsRequirer {
|
||||
/// An absolute path to the current Luau module (not mapped to a physical file)
|
||||
abs_path: PathBuf,
|
||||
/// A relative path to the current Luau module (not mapped to a physical file)
|
||||
rel_path: PathBuf,
|
||||
/// A physical path to the current Luau module, which is a file or a directory with an
|
||||
/// `init.lua(u)` file
|
||||
resolved_path: Option<PathBuf>,
|
||||
}
|
||||
|
||||
impl FsRequirer {
|
||||
/// The prefix used for chunk names in the require system.
|
||||
/// Only chunk names starting with this prefix are allowed to be used in `require`.
|
||||
const CHUNK_PREFIX: &str = "@";
|
||||
|
||||
/// The file extensions that are considered valid for Luau modules.
|
||||
const FILE_EXTENSIONS: &[&str] = &["luau", "lua"];
|
||||
|
||||
/// The filename for the JSON configuration file.
|
||||
const LUAURC_CONFIG_FILENAME: &str = ".luaurc";
|
||||
|
||||
/// The filename for the Luau configuration file.
|
||||
const LUAU_CONFIG_FILENAME: &str = ".config.luau";
|
||||
|
||||
/// Creates a new `FsRequirer` instance.
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
fn normalize_chunk_name(chunk_name: &str) -> &str {
|
||||
if let Some((path, line)) = chunk_name.rsplit_once(':')
|
||||
&& line.parse::<u32>().is_ok()
|
||||
{
|
||||
return path;
|
||||
}
|
||||
chunk_name
|
||||
}
|
||||
|
||||
// Normalizes the path by removing unnecessary components
|
||||
fn normalize_path(path: &Path) -> PathBuf {
|
||||
let mut components = VecDeque::new();
|
||||
|
||||
for comp in path.components() {
|
||||
match comp {
|
||||
Component::Prefix(..) | Component::RootDir => {
|
||||
components.push_back(comp);
|
||||
}
|
||||
Component::CurDir => {}
|
||||
Component::ParentDir => {
|
||||
if matches!(components.back(), None | Some(Component::ParentDir)) {
|
||||
components.push_back(Component::ParentDir);
|
||||
} else if matches!(components.back(), Some(Component::Normal(..))) {
|
||||
components.pop_back();
|
||||
}
|
||||
}
|
||||
Component::Normal(..) => components.push_back(comp),
|
||||
}
|
||||
}
|
||||
|
||||
if matches!(components.front(), None | Some(Component::Normal(..))) {
|
||||
components.push_front(Component::CurDir);
|
||||
}
|
||||
|
||||
// Join the components back together
|
||||
components.into_iter().collect()
|
||||
}
|
||||
|
||||
/// Resolve a Luau module path to a physical file or directory.
|
||||
///
|
||||
/// Empty directories without init files are considered valid as "intermediate" directories.
|
||||
fn resolve_module(path: &Path) -> StdResult<Option<PathBuf>, NavigateError> {
|
||||
let mut found_path = None;
|
||||
|
||||
if path.components().next_back() != Some(Component::Normal("init".as_ref())) {
|
||||
let current_ext = (path.extension().and_then(|s| s.to_str()))
|
||||
.map(|s| format!("{s}."))
|
||||
.unwrap_or_default();
|
||||
for ext in Self::FILE_EXTENSIONS {
|
||||
let candidate = path.with_extension(format!("{current_ext}{ext}"));
|
||||
if candidate.is_file() && found_path.replace(candidate).is_some() {
|
||||
return Err(NavigateError::Ambiguous);
|
||||
}
|
||||
}
|
||||
}
|
||||
if path.is_dir() {
|
||||
for component in Self::FILE_EXTENSIONS.iter().map(|ext| format!("init.{ext}")) {
|
||||
let candidate = path.join(component);
|
||||
if candidate.is_file() && found_path.replace(candidate).is_some() {
|
||||
return Err(NavigateError::Ambiguous);
|
||||
}
|
||||
}
|
||||
|
||||
if found_path.is_none() {
|
||||
// Directories without init files are considered valid "intermediate" path
|
||||
return Ok(None);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Some(found_path.ok_or(NavigateError::NotFound)?))
|
||||
}
|
||||
}
|
||||
|
||||
impl Require for FsRequirer {
|
||||
fn is_require_allowed(&self, chunk_name: &str) -> bool {
|
||||
chunk_name.starts_with(Self::CHUNK_PREFIX)
|
||||
}
|
||||
|
||||
fn reset(&mut self, chunk_name: &str) -> StdResult<(), NavigateError> {
|
||||
if !chunk_name.starts_with(Self::CHUNK_PREFIX) {
|
||||
return Err(NavigateError::NotFound);
|
||||
}
|
||||
let chunk_name = Self::normalize_chunk_name(&chunk_name[1..]);
|
||||
let chunk_path = Self::normalize_path(chunk_name.as_ref());
|
||||
|
||||
if chunk_path.extension() == Some("rs".as_ref()) {
|
||||
// Special case for Rust source files, reset to the current directory
|
||||
let chunk_filename = chunk_path.file_name().unwrap();
|
||||
let cwd = env::current_dir().map_err(|_| NavigateError::NotFound)?;
|
||||
self.abs_path = Self::normalize_path(&cwd.join(chunk_filename));
|
||||
self.rel_path = ([Component::CurDir, Component::Normal(chunk_filename)].into_iter()).collect();
|
||||
self.resolved_path = None;
|
||||
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if chunk_path.is_absolute() {
|
||||
let resolved_path = Self::resolve_module(&chunk_path)?;
|
||||
self.abs_path = chunk_path.clone();
|
||||
self.rel_path = chunk_path;
|
||||
self.resolved_path = resolved_path;
|
||||
} else {
|
||||
// Relative path
|
||||
let cwd = env::current_dir().map_err(|_| NavigateError::NotFound)?;
|
||||
let abs_path = Self::normalize_path(&cwd.join(&chunk_path));
|
||||
let resolved_path = Self::resolve_module(&abs_path)?;
|
||||
self.abs_path = abs_path;
|
||||
self.rel_path = chunk_path;
|
||||
self.resolved_path = resolved_path;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn jump_to_alias(&mut self, path: &str) -> StdResult<(), NavigateError> {
|
||||
let path = Self::normalize_path(path.as_ref());
|
||||
let resolved_path = Self::resolve_module(&path)?;
|
||||
|
||||
self.abs_path = path.clone();
|
||||
self.rel_path = path;
|
||||
self.resolved_path = resolved_path;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn to_parent(&mut self) -> StdResult<(), NavigateError> {
|
||||
let mut abs_path = self.abs_path.clone();
|
||||
if !abs_path.pop() {
|
||||
// It's important to return `NotFound` if we reached the root, as it's a "recoverable" error if we
|
||||
// cannot go beyond the root directory.
|
||||
// Luau "require-by-string` has a special logic to search for config file to resolve aliases.
|
||||
return Err(NavigateError::NotFound);
|
||||
}
|
||||
let mut rel_parent = self.rel_path.clone();
|
||||
rel_parent.pop();
|
||||
let resolved_path = Self::resolve_module(&abs_path)?;
|
||||
|
||||
self.abs_path = abs_path;
|
||||
self.rel_path = Self::normalize_path(&rel_parent);
|
||||
self.resolved_path = resolved_path;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn to_child(&mut self, name: &str) -> StdResult<(), NavigateError> {
|
||||
let abs_path = self.abs_path.join(name);
|
||||
let rel_path = self.rel_path.join(name);
|
||||
let resolved_path = Self::resolve_module(&abs_path)?;
|
||||
|
||||
self.abs_path = abs_path;
|
||||
self.rel_path = rel_path;
|
||||
self.resolved_path = resolved_path;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn has_module(&self) -> bool {
|
||||
(self.resolved_path.as_deref())
|
||||
.map(Path::is_file)
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
fn cache_key(&self) -> String {
|
||||
self.resolved_path.as_deref().unwrap().display().to_string()
|
||||
}
|
||||
|
||||
fn has_config(&self) -> bool {
|
||||
self.abs_path.is_dir() && self.abs_path.join(Self::LUAURC_CONFIG_FILENAME).is_file()
|
||||
|| self.abs_path.is_dir() && self.abs_path.join(Self::LUAU_CONFIG_FILENAME).is_file()
|
||||
}
|
||||
|
||||
fn config(&self) -> IoResult<Vec<u8>> {
|
||||
if self.abs_path.join(Self::LUAURC_CONFIG_FILENAME).is_file() {
|
||||
return fs::read(self.abs_path.join(Self::LUAURC_CONFIG_FILENAME));
|
||||
}
|
||||
fs::read(self.abs_path.join(Self::LUAU_CONFIG_FILENAME))
|
||||
}
|
||||
|
||||
fn loader(&self, lua: &Lua) -> Result<Function> {
|
||||
let name = format!("@{}", self.rel_path.display());
|
||||
lua.load(self.resolved_path.as_deref().unwrap())
|
||||
.set_name(name)
|
||||
.into_function()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::path::Path;
|
||||
|
||||
use super::FsRequirer;
|
||||
|
||||
#[test]
|
||||
fn test_path_normalize() {
|
||||
for (input, expected) in [
|
||||
// Basic formatting checks
|
||||
("", "./"),
|
||||
(".", "./"),
|
||||
("a/relative/path", "./a/relative/path"),
|
||||
// Paths containing extraneous '.' and '/' symbols
|
||||
("./remove/extraneous/symbols/", "./remove/extraneous/symbols"),
|
||||
("./remove/extraneous//symbols", "./remove/extraneous/symbols"),
|
||||
("./remove/extraneous/symbols/.", "./remove/extraneous/symbols"),
|
||||
("./remove/extraneous/./symbols", "./remove/extraneous/symbols"),
|
||||
("../remove/extraneous/symbols/", "../remove/extraneous/symbols"),
|
||||
("../remove/extraneous//symbols", "../remove/extraneous/symbols"),
|
||||
("../remove/extraneous/symbols/.", "../remove/extraneous/symbols"),
|
||||
("../remove/extraneous/./symbols", "../remove/extraneous/symbols"),
|
||||
("/remove/extraneous/symbols/", "/remove/extraneous/symbols"),
|
||||
("/remove/extraneous//symbols", "/remove/extraneous/symbols"),
|
||||
("/remove/extraneous/symbols/.", "/remove/extraneous/symbols"),
|
||||
("/remove/extraneous/./symbols", "/remove/extraneous/symbols"),
|
||||
// Paths containing '..'
|
||||
("./remove/me/..", "./remove"),
|
||||
("./remove/me/../", "./remove"),
|
||||
("../remove/me/..", "../remove"),
|
||||
("../remove/me/../", "../remove"),
|
||||
("/remove/me/..", "/remove"),
|
||||
("/remove/me/../", "/remove"),
|
||||
("./..", "../"),
|
||||
("./../", "../"),
|
||||
("../..", "../../"),
|
||||
("../../", "../../"),
|
||||
// '..' disappears if path is absolute and component is non-erasable
|
||||
("/../", "/"),
|
||||
] {
|
||||
let path = FsRequirer::normalize_path(input.as_ref());
|
||||
assert_eq!(
|
||||
&path,
|
||||
expected.as_ref() as &Path,
|
||||
"wrong normalization for {input}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-2
@@ -10,8 +10,7 @@ macro_rules! bug_msg {
|
||||
|
||||
macro_rules! cstr {
|
||||
($s:expr) => {
|
||||
concat!($s, "\0") as *const str as *const [::std::os::raw::c_char]
|
||||
as *const ::std::os::raw::c_char
|
||||
concat!($s, "\0") as *const str as *const [::std::os::raw::c_char] as *const ::std::os::raw::c_char
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
+13
-9
@@ -18,16 +18,20 @@ pub(crate) struct MemoryState {
|
||||
}
|
||||
|
||||
impl MemoryState {
|
||||
#[cfg(feature = "luau")]
|
||||
#[inline]
|
||||
pub(crate) unsafe fn get(state: *mut ffi::lua_State) -> *mut Self {
|
||||
let mut mem_state = ptr::null_mut();
|
||||
#[cfg(feature = "luau")]
|
||||
{
|
||||
ffi::lua_getallocf(state, &mut mem_state);
|
||||
mlua_assert!(!mem_state.is_null(), "Luau state has no allocator userdata");
|
||||
}
|
||||
#[cfg(not(feature = "luau"))]
|
||||
if ffi::lua_getallocf(state, &mut mem_state) != ALLOCATOR {
|
||||
ffi::lua_getallocf(state, &mut mem_state);
|
||||
mlua_assert!(!mem_state.is_null(), "Luau state has no allocator userdata");
|
||||
mem_state as *mut MemoryState
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "luau"))]
|
||||
#[inline]
|
||||
pub(crate) unsafe fn get(state: *mut ffi::lua_State) -> *mut Self {
|
||||
let mut mem_state = ptr::null_mut();
|
||||
if !ptr::fn_addr_eq(ffi::lua_getallocf(state, &mut mem_state), ALLOCATOR) {
|
||||
mem_state = ptr::null_mut();
|
||||
}
|
||||
mem_state as *mut MemoryState
|
||||
@@ -66,7 +70,7 @@ impl MemoryState {
|
||||
}
|
||||
|
||||
// Does nothing apart from calling `f()`, we don't need to bypass any limits
|
||||
#[cfg(any(feature = "lua52", feature = "lua53", feature = "lua54"))]
|
||||
#[cfg(any(feature = "lua55", feature = "lua54", feature = "lua53", feature = "lua52"))]
|
||||
#[inline]
|
||||
pub(crate) unsafe fn relax_limit_with(_state: *mut ffi::lua_State, f: impl FnOnce()) {
|
||||
f();
|
||||
@@ -80,7 +84,7 @@ impl MemoryState {
|
||||
}
|
||||
}
|
||||
|
||||
unsafe extern "C-unwind" fn allocator(
|
||||
unsafe extern "C" fn allocator(
|
||||
extra: *mut c_void,
|
||||
ptr: *mut c_void,
|
||||
osize: usize,
|
||||
|
||||
+236
-118
@@ -1,135 +1,229 @@
|
||||
use std::collections::{VecDeque, vec_deque};
|
||||
use std::iter::FromIterator;
|
||||
use std::mem;
|
||||
use std::ops::{Deref, DerefMut};
|
||||
use std::os::raw::c_int;
|
||||
use std::result::Result as StdResult;
|
||||
|
||||
use crate::error::Result;
|
||||
use crate::lua::Lua;
|
||||
use crate::state::{Lua, RawLua};
|
||||
use crate::traits::{FromLua, FromLuaMulti, IntoLua, IntoLuaMulti};
|
||||
use crate::util::check_stack;
|
||||
use crate::value::{FromLua, FromLuaMulti, IntoLua, IntoLuaMulti, MultiValue, Nil};
|
||||
use crate::value::{Nil, Value};
|
||||
|
||||
/// Result is convertible to `MultiValue` following the common Lua idiom of returning the result
|
||||
/// Result is convertible to [`MultiValue`] following the common Lua idiom of returning the result
|
||||
/// on success, or in the case of an error, returning `nil` and an error message.
|
||||
impl<'lua, T: IntoLua<'lua>, E: IntoLua<'lua>> IntoLuaMulti<'lua> for StdResult<T, E> {
|
||||
impl<T: IntoLua, E: IntoLua> IntoLuaMulti for StdResult<T, E> {
|
||||
#[inline]
|
||||
fn into_lua_multi(self, lua: &'lua Lua) -> Result<MultiValue<'lua>> {
|
||||
let mut result = MultiValue::with_lua_and_capacity(lua, 2);
|
||||
fn into_lua_multi(self, lua: &Lua) -> Result<MultiValue> {
|
||||
match self {
|
||||
Ok(v) => result.push_front(v.into_lua(lua)?),
|
||||
Err(e) => {
|
||||
result.push_front(e.into_lua(lua)?);
|
||||
result.push_front(Nil);
|
||||
}
|
||||
Ok(val) => (val,).into_lua_multi(lua),
|
||||
Err(err) => (Nil, err).into_lua_multi(lua),
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
unsafe fn push_into_stack_multi(self, lua: &'lua Lua) -> Result<c_int> {
|
||||
unsafe fn push_into_stack_multi(self, lua: &RawLua) -> Result<c_int> {
|
||||
match self {
|
||||
Ok(v) => v.push_into_stack(lua).map(|_| 1),
|
||||
Err(e) => {
|
||||
let state = lua.state();
|
||||
check_stack(state, 3)?;
|
||||
ffi::lua_pushnil(state);
|
||||
e.push_into_stack(lua)?;
|
||||
Ok(2)
|
||||
}
|
||||
Ok(val) => (val,).push_into_stack_multi(lua),
|
||||
Err(err) => (Nil, err).push_into_stack_multi(lua),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'lua, E: IntoLua<'lua>> IntoLuaMulti<'lua> for StdResult<(), E> {
|
||||
impl<E: IntoLua> IntoLuaMulti for StdResult<(), E> {
|
||||
#[inline]
|
||||
fn into_lua_multi(self, lua: &'lua Lua) -> Result<MultiValue<'lua>> {
|
||||
fn into_lua_multi(self, lua: &Lua) -> Result<MultiValue> {
|
||||
match self {
|
||||
Ok(_) => return Ok(MultiValue::new()),
|
||||
Err(e) => {
|
||||
let mut result = MultiValue::with_lua_and_capacity(lua, 2);
|
||||
result.push_front(e.into_lua(lua)?);
|
||||
result.push_front(Nil);
|
||||
Ok(result)
|
||||
}
|
||||
Ok(_) => const { Ok(MultiValue::new()) },
|
||||
Err(err) => (Nil, err).into_lua_multi(lua),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
unsafe fn push_into_stack_multi(self, lua: &'lua Lua) -> Result<c_int> {
|
||||
unsafe fn push_into_stack_multi(self, lua: &RawLua) -> Result<c_int> {
|
||||
match self {
|
||||
Ok(_) => Ok(0),
|
||||
Err(e) => {
|
||||
let state = lua.state();
|
||||
check_stack(state, 3)?;
|
||||
ffi::lua_pushnil(state);
|
||||
e.push_into_stack(lua)?;
|
||||
Ok(2)
|
||||
}
|
||||
Err(err) => (Nil, err).push_into_stack_multi(lua),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'lua, T: IntoLua<'lua>> IntoLuaMulti<'lua> for T {
|
||||
impl<T: IntoLua> IntoLuaMulti for T {
|
||||
#[inline]
|
||||
fn into_lua_multi(self, lua: &'lua Lua) -> Result<MultiValue<'lua>> {
|
||||
let mut v = MultiValue::with_lua_and_capacity(lua, 1);
|
||||
v.push_front(self.into_lua(lua)?);
|
||||
fn into_lua_multi(self, lua: &Lua) -> Result<MultiValue> {
|
||||
let mut v = MultiValue::with_capacity(1);
|
||||
v.push_back(self.into_lua(lua)?);
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
unsafe fn push_into_stack_multi(self, lua: &'lua Lua) -> Result<c_int> {
|
||||
unsafe fn push_into_stack_multi(self, lua: &RawLua) -> Result<c_int> {
|
||||
self.push_into_stack(lua)?;
|
||||
Ok(1)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'lua, T: FromLua<'lua>> FromLuaMulti<'lua> for T {
|
||||
impl<T: FromLua> FromLuaMulti for T {
|
||||
#[inline]
|
||||
fn from_lua_multi(mut values: MultiValue<'lua>, lua: &'lua Lua) -> Result<Self> {
|
||||
fn from_lua_multi(mut values: MultiValue, lua: &Lua) -> Result<Self> {
|
||||
T::from_lua(values.pop_front().unwrap_or(Nil), lua)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn from_lua_args(
|
||||
mut args: MultiValue<'lua>,
|
||||
i: usize,
|
||||
to: Option<&str>,
|
||||
lua: &'lua Lua,
|
||||
) -> Result<Self> {
|
||||
fn from_lua_args(mut args: MultiValue, i: usize, to: Option<&str>, lua: &Lua) -> Result<Self> {
|
||||
T::from_lua_arg(args.pop_front().unwrap_or(Nil), i, to, lua)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
unsafe fn from_stack_multi(nvals: c_int, lua: &'lua Lua) -> Result<Self> {
|
||||
unsafe fn from_stack_multi(nvals: c_int, lua: &RawLua) -> Result<Self> {
|
||||
if nvals == 0 {
|
||||
return T::from_lua(Nil, lua);
|
||||
return T::from_lua(Nil, lua.lua());
|
||||
}
|
||||
T::from_stack(-nvals, lua)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
unsafe fn from_stack_args(
|
||||
nargs: c_int,
|
||||
i: usize,
|
||||
to: Option<&str>,
|
||||
lua: &'lua Lua,
|
||||
) -> Result<Self> {
|
||||
unsafe fn from_stack_args(nargs: c_int, i: usize, to: Option<&str>, lua: &RawLua) -> Result<Self> {
|
||||
if nargs == 0 {
|
||||
return T::from_lua_arg(Nil, i, to, lua);
|
||||
return T::from_lua_arg(Nil, i, to, lua.lua());
|
||||
}
|
||||
T::from_stack_arg(-nargs, i, to, lua)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'lua> IntoLuaMulti<'lua> for MultiValue<'lua> {
|
||||
/// Multiple Lua values used for both argument passing and also for multiple return values.
|
||||
#[derive(Default, Debug, Clone)]
|
||||
pub struct MultiValue(VecDeque<Value>);
|
||||
|
||||
impl Deref for MultiValue {
|
||||
type Target = VecDeque<Value>;
|
||||
|
||||
#[inline]
|
||||
fn into_lua_multi(self, _: &'lua Lua) -> Result<MultiValue<'lua>> {
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl DerefMut for MultiValue {
|
||||
#[inline]
|
||||
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||
&mut self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl MultiValue {
|
||||
/// Creates an empty `MultiValue` containing no values.
|
||||
#[inline]
|
||||
pub const fn new() -> MultiValue {
|
||||
MultiValue(VecDeque::new())
|
||||
}
|
||||
|
||||
/// Creates an empty `MultiValue` container with space for at least `capacity` elements.
|
||||
pub fn with_capacity(capacity: usize) -> MultiValue {
|
||||
MultiValue(VecDeque::with_capacity(capacity))
|
||||
}
|
||||
|
||||
/// Creates a `MultiValue` container from vector of values.
|
||||
///
|
||||
/// This method works in *O*(1) time and does not allocate any additional memory.
|
||||
#[inline]
|
||||
pub fn from_vec(vec: Vec<Value>) -> MultiValue {
|
||||
vec.into()
|
||||
}
|
||||
|
||||
/// Consumes the `MultiValue` and returns a vector of values.
|
||||
///
|
||||
/// This method needs *O*(*n*) data movement if the circular buffer doesn't happen to be at the
|
||||
/// beginning of the allocation.
|
||||
#[inline]
|
||||
pub fn into_vec(self) -> Vec<Value> {
|
||||
self.into()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn from_lua_iter<T: IntoLua>(lua: &Lua, iter: impl IntoIterator<Item = T>) -> Result<Self> {
|
||||
let iter = iter.into_iter();
|
||||
let mut multi_value = MultiValue::with_capacity(iter.size_hint().0);
|
||||
for value in iter {
|
||||
multi_value.push_back(value.into_lua(lua)?);
|
||||
}
|
||||
Ok(multi_value)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Vec<Value>> for MultiValue {
|
||||
#[inline]
|
||||
fn from(value: Vec<Value>) -> Self {
|
||||
MultiValue(value.into())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<MultiValue> for Vec<Value> {
|
||||
#[inline]
|
||||
fn from(value: MultiValue) -> Self {
|
||||
value.0.into()
|
||||
}
|
||||
}
|
||||
|
||||
impl FromIterator<Value> for MultiValue {
|
||||
#[inline]
|
||||
fn from_iter<I: IntoIterator<Item = Value>>(iter: I) -> Self {
|
||||
let mut multi_value = MultiValue::new();
|
||||
multi_value.extend(iter);
|
||||
multi_value
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoIterator for MultiValue {
|
||||
type Item = Value;
|
||||
type IntoIter = vec_deque::IntoIter<Value>;
|
||||
|
||||
#[inline]
|
||||
fn into_iter(mut self) -> Self::IntoIter {
|
||||
let deque = mem::take(&mut self.0);
|
||||
mem::forget(self);
|
||||
deque.into_iter()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> IntoIterator for &'a MultiValue {
|
||||
type Item = &'a Value;
|
||||
type IntoIter = vec_deque::Iter<'a, Value>;
|
||||
|
||||
#[inline]
|
||||
fn into_iter(self) -> Self::IntoIter {
|
||||
self.0.iter()
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoLuaMulti for MultiValue {
|
||||
#[inline]
|
||||
fn into_lua_multi(self, _: &Lua) -> Result<MultiValue> {
|
||||
Ok(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'lua> FromLuaMulti<'lua> for MultiValue<'lua> {
|
||||
impl IntoLuaMulti for &MultiValue {
|
||||
#[inline]
|
||||
fn from_lua_multi(values: MultiValue<'lua>, _: &'lua Lua) -> Result<Self> {
|
||||
fn into_lua_multi(self, _: &Lua) -> Result<MultiValue> {
|
||||
Ok(self.clone())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
unsafe fn push_into_stack_multi(self, lua: &RawLua) -> Result<c_int> {
|
||||
let nresults = self.len() as i32;
|
||||
check_stack(lua.state(), nresults + 1)?;
|
||||
for value in &self.0 {
|
||||
lua.push_value(value)?;
|
||||
}
|
||||
Ok(nresults)
|
||||
}
|
||||
}
|
||||
|
||||
impl FromLuaMulti for MultiValue {
|
||||
#[inline]
|
||||
fn from_lua_multi(values: MultiValue, _: &Lua) -> Result<Self> {
|
||||
Ok(values)
|
||||
}
|
||||
}
|
||||
@@ -157,10 +251,7 @@ impl<'lua> FromLuaMulti<'lua> for MultiValue<'lua> {
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
///
|
||||
/// [`FromLua`]: crate::FromLua
|
||||
/// [`MultiValue`]: crate::MultiValue
|
||||
#[derive(Debug, Clone)]
|
||||
#[derive(Default, Debug, Clone)]
|
||||
pub struct Variadic<T>(Vec<T>);
|
||||
|
||||
impl<T> Variadic<T> {
|
||||
@@ -168,11 +259,38 @@ impl<T> Variadic<T> {
|
||||
pub const fn new() -> Variadic<T> {
|
||||
Variadic(Vec::new())
|
||||
}
|
||||
|
||||
/// Creates an empty `Variadic` container with space for at least `capacity` elements.
|
||||
pub fn with_capacity(capacity: usize) -> Variadic<T> {
|
||||
Variadic(Vec::with_capacity(capacity))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Default for Variadic<T> {
|
||||
fn default() -> Variadic<T> {
|
||||
Variadic::new()
|
||||
impl<T> Deref for Variadic<T> {
|
||||
type Target = Vec<T>;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> DerefMut for Variadic<T> {
|
||||
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||
&mut self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> From<Vec<T>> for Variadic<T> {
|
||||
#[inline]
|
||||
fn from(vec: Vec<T>) -> Self {
|
||||
Variadic(vec)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> From<Variadic<T>> for Vec<T> {
|
||||
#[inline]
|
||||
fn from(value: Variadic<T>) -> Self {
|
||||
value.0
|
||||
}
|
||||
}
|
||||
|
||||
@@ -191,35 +309,28 @@ impl<T> IntoIterator for Variadic<T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Deref for Variadic<T> {
|
||||
type Target = Vec<T>;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> DerefMut for Variadic<T> {
|
||||
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||
&mut self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl<'lua, T: IntoLua<'lua>> IntoLuaMulti<'lua> for Variadic<T> {
|
||||
impl<T: IntoLua> IntoLuaMulti for Variadic<T> {
|
||||
#[inline]
|
||||
fn into_lua_multi(self, lua: &'lua Lua) -> Result<MultiValue<'lua>> {
|
||||
let mut values = MultiValue::with_lua_and_capacity(lua, self.0.len());
|
||||
values.refill(self.0.into_iter().map(|e| e.into_lua(lua)))?;
|
||||
Ok(values)
|
||||
fn into_lua_multi(self, lua: &Lua) -> Result<MultiValue> {
|
||||
MultiValue::from_lua_iter(lua, self)
|
||||
}
|
||||
|
||||
unsafe fn push_into_stack_multi(self, lua: &RawLua) -> Result<c_int> {
|
||||
let nresults = self.len() as i32;
|
||||
check_stack(lua.state(), nresults + 1)?;
|
||||
for value in self.0 {
|
||||
value.push_into_stack(lua)?;
|
||||
}
|
||||
Ok(nresults)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'lua, T: FromLua<'lua>> FromLuaMulti<'lua> for Variadic<T> {
|
||||
impl<T: FromLua> FromLuaMulti for Variadic<T> {
|
||||
#[inline]
|
||||
fn from_lua_multi(mut values: MultiValue<'lua>, lua: &'lua Lua) -> Result<Self> {
|
||||
fn from_lua_multi(mut values: MultiValue, lua: &Lua) -> Result<Self> {
|
||||
values
|
||||
.drain_all()
|
||||
.map(|e| T::from_lua(e, lua))
|
||||
.drain(..)
|
||||
.map(|val| T::from_lua(val, lua))
|
||||
.collect::<Result<Vec<T>>>()
|
||||
.map(Variadic)
|
||||
}
|
||||
@@ -227,42 +338,39 @@ impl<'lua, T: FromLua<'lua>> FromLuaMulti<'lua> for Variadic<T> {
|
||||
|
||||
macro_rules! impl_tuple {
|
||||
() => (
|
||||
impl<'lua> IntoLuaMulti<'lua> for () {
|
||||
impl IntoLuaMulti for () {
|
||||
#[inline]
|
||||
fn into_lua_multi(self, lua: &'lua Lua) -> Result<MultiValue<'lua>> {
|
||||
Ok(MultiValue::with_lua_and_capacity(lua, 0))
|
||||
fn into_lua_multi(self, _: &Lua) -> Result<MultiValue> {
|
||||
const { Ok(MultiValue::new()) }
|
||||
}
|
||||
|
||||
#[inline]
|
||||
unsafe fn push_into_stack_multi(self, _lua: &'lua Lua) -> Result<c_int> {
|
||||
unsafe fn push_into_stack_multi(self, _lua: &RawLua) -> Result<c_int> {
|
||||
Ok(0)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'lua> FromLuaMulti<'lua> for () {
|
||||
impl FromLuaMulti for () {
|
||||
#[inline]
|
||||
fn from_lua_multi(_values: MultiValue<'lua>, _lua: &'lua Lua) -> Result<Self> {
|
||||
fn from_lua_multi(_values: MultiValue, _lua: &Lua) -> Result<Self> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
unsafe fn from_stack_multi(nvals: c_int, lua: &'lua Lua) -> Result<Self> {
|
||||
if nvals > 0 {
|
||||
ffi::lua_pop(lua.state(), nvals);
|
||||
}
|
||||
unsafe fn from_stack_multi(_nvals: c_int, _lua: &RawLua) -> Result<Self> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
($last:ident $($name:ident)*) => (
|
||||
impl<'lua, $($name,)* $last> IntoLuaMulti<'lua> for ($($name,)* $last,)
|
||||
where $($name: IntoLua<'lua>,)*
|
||||
$last: IntoLuaMulti<'lua>
|
||||
impl<$($name,)* $last> IntoLuaMulti for ($($name,)* $last,)
|
||||
where $($name: IntoLua,)*
|
||||
$last: IntoLuaMulti
|
||||
{
|
||||
#[allow(unused_mut, non_snake_case)]
|
||||
#[inline]
|
||||
fn into_lua_multi(self, lua: &'lua Lua) -> Result<MultiValue<'lua>> {
|
||||
fn into_lua_multi(self, lua: &Lua) -> Result<MultiValue> {
|
||||
let ($($name,)* $last,) = self;
|
||||
|
||||
let mut results = $last.into_lua_multi(lua)?;
|
||||
@@ -272,7 +380,7 @@ macro_rules! impl_tuple {
|
||||
|
||||
#[allow(non_snake_case)]
|
||||
#[inline]
|
||||
unsafe fn push_into_stack_multi(self, lua: &'lua Lua) -> Result<c_int> {
|
||||
unsafe fn push_into_stack_multi(self, lua: &RawLua) -> Result<c_int> {
|
||||
let ($($name,)* $last,) = self;
|
||||
let mut nresults = 0;
|
||||
$(
|
||||
@@ -288,13 +396,13 @@ macro_rules! impl_tuple {
|
||||
}
|
||||
}
|
||||
|
||||
impl<'lua, $($name,)* $last> FromLuaMulti<'lua> for ($($name,)* $last,)
|
||||
where $($name: FromLua<'lua>,)*
|
||||
$last: FromLuaMulti<'lua>
|
||||
impl<$($name,)* $last> FromLuaMulti for ($($name,)* $last,)
|
||||
where $($name: FromLua,)*
|
||||
$last: FromLuaMulti
|
||||
{
|
||||
#[allow(unused_mut, non_snake_case)]
|
||||
#[inline]
|
||||
fn from_lua_multi(mut values: MultiValue<'lua>, lua: &'lua Lua) -> Result<Self> {
|
||||
fn from_lua_multi(mut values: MultiValue, lua: &Lua) -> Result<Self> {
|
||||
$(let $name = FromLua::from_lua(values.pop_front().unwrap_or(Nil), lua)?;)*
|
||||
let $last = FromLuaMulti::from_lua_multi(values, lua)?;
|
||||
Ok(($($name,)* $last,))
|
||||
@@ -302,7 +410,7 @@ macro_rules! impl_tuple {
|
||||
|
||||
#[allow(unused_mut, non_snake_case)]
|
||||
#[inline]
|
||||
fn from_lua_args(mut args: MultiValue<'lua>, mut i: usize, to: Option<&str>, lua: &'lua Lua) -> Result<Self> {
|
||||
fn from_lua_args(mut args: MultiValue, mut i: usize, to: Option<&str>, lua: &Lua) -> Result<Self> {
|
||||
$(
|
||||
let $name = FromLua::from_lua_arg(args.pop_front().unwrap_or(Nil), i, to, lua)?;
|
||||
i += 1;
|
||||
@@ -313,13 +421,13 @@ macro_rules! impl_tuple {
|
||||
|
||||
#[allow(unused_mut, non_snake_case)]
|
||||
#[inline]
|
||||
unsafe fn from_stack_multi(mut nvals: c_int, lua: &'lua Lua) -> Result<Self> {
|
||||
unsafe fn from_stack_multi(mut nvals: c_int, lua: &RawLua) -> Result<Self> {
|
||||
$(
|
||||
let $name = if nvals > 0 {
|
||||
nvals -= 1;
|
||||
FromLua::from_stack(-(nvals + 1), lua)
|
||||
} else {
|
||||
FromLua::from_lua(Nil, lua)
|
||||
FromLua::from_lua(Nil, lua.lua())
|
||||
}?;
|
||||
)*
|
||||
let $last = FromLuaMulti::from_stack_multi(nvals, lua)?;
|
||||
@@ -328,13 +436,13 @@ macro_rules! impl_tuple {
|
||||
|
||||
#[allow(unused_mut, non_snake_case)]
|
||||
#[inline]
|
||||
unsafe fn from_stack_args(mut nargs: c_int, mut i: usize, to: Option<&str>, lua: &'lua Lua) -> Result<Self> {
|
||||
unsafe fn from_stack_args(mut nargs: c_int, mut i: usize, to: Option<&str>, lua: &RawLua) -> Result<Self> {
|
||||
$(
|
||||
let $name = if nargs > 0 {
|
||||
nargs -= 1;
|
||||
FromLua::from_stack_arg(-(nargs + 1), i, to, lua)
|
||||
} else {
|
||||
FromLua::from_lua_arg(Nil, i, to, lua)
|
||||
FromLua::from_lua_arg(Nil, i, to, lua.lua())
|
||||
}?;
|
||||
i += 1;
|
||||
)*
|
||||
@@ -375,3 +483,13 @@ impl_tuple!(A B C D E F G H I J K L M);
|
||||
impl_tuple!(A B C D E F G H I J K L M N);
|
||||
impl_tuple!(A B C D E F G H I J K L M N O);
|
||||
impl_tuple!(A B C D E F G H I J K L M N O P);
|
||||
|
||||
#[cfg(test)]
|
||||
mod assertions {
|
||||
use super::*;
|
||||
|
||||
#[cfg(not(feature = "send"))]
|
||||
static_assertions::assert_not_impl_any!(MultiValue: Send);
|
||||
#[cfg(feature = "send")]
|
||||
static_assertions::assert_impl_all!(MultiValue: Send, Sync);
|
||||
}
|
||||
|
||||
+30
-24
@@ -2,43 +2,49 @@
|
||||
|
||||
#[doc(no_inline)]
|
||||
pub use crate::{
|
||||
AnyUserData as LuaAnyUserData, AnyUserDataExt as LuaAnyUserDataExt, Chunk as LuaChunk,
|
||||
Error as LuaError, ErrorContext as LuaErrorContext, ExternalError as LuaExternalError,
|
||||
ExternalResult as LuaExternalResult, FromLua, FromLuaMulti, Function as LuaFunction,
|
||||
FunctionInfo as LuaFunctionInfo, GCMode as LuaGCMode, Integer as LuaInteger, IntoLua,
|
||||
IntoLuaMulti, LightUserData as LuaLightUserData, Lua, LuaOptions, MetaMethod as LuaMetaMethod,
|
||||
MultiValue as LuaMultiValue, Nil as LuaNil, Number as LuaNumber, RegistryKey as LuaRegistryKey,
|
||||
Result as LuaResult, StdLib as LuaStdLib, String as LuaString, Table as LuaTable,
|
||||
TableExt as LuaTableExt, TablePairs as LuaTablePairs, TableSequence as LuaTableSequence,
|
||||
Thread as LuaThread, ThreadStatus as LuaThreadStatus, UserData as LuaUserData,
|
||||
UserDataFields as LuaUserDataFields, UserDataMetatable as LuaUserDataMetatable,
|
||||
UserDataMethods as LuaUserDataMethods, UserDataRef as LuaUserDataRef,
|
||||
UserDataRefMut as LuaUserDataRefMut, UserDataRegistry as LuaUserDataRegistry,
|
||||
Value as LuaValue,
|
||||
AnyUserData as LuaAnyUserData, BorrowedBytes as LuaBorrowedBytes, BorrowedStr as LuaBorrowedStr,
|
||||
Either as LuaEither, Error as LuaError, FromLua, FromLuaMulti, Function as LuaFunction,
|
||||
Integer as LuaInteger, IntoLua, IntoLuaMulti, LightUserData as LuaLightUserData, Lua, LuaOptions,
|
||||
LuaString, MetaMethod as LuaMetaMethod, MultiValue as LuaMultiValue, Nil as LuaNil, Number as LuaNumber,
|
||||
ObjectLike as LuaObjectLike, RegistryKey as LuaRegistryKey, Result as LuaResult, StdLib as LuaStdLib,
|
||||
Table as LuaTable, Thread as LuaThread, UserData as LuaUserData, UserDataFields as LuaUserDataFields,
|
||||
UserDataMetatable as LuaUserDataMetatable, UserDataMethods as LuaUserDataMethods,
|
||||
UserDataOwned as LuaUserDataOwned, UserDataRef as LuaUserDataRef, UserDataRefMut as LuaUserDataRefMut,
|
||||
UserDataRegistry as LuaUserDataRegistry, Value as LuaValue, Variadic as LuaVariadic,
|
||||
VmState as LuaVmState, WeakLua, chunk::AsChunk as AsLuaChunk, chunk::Chunk as LuaChunk,
|
||||
chunk::ChunkMode as LuaChunkMode, error::ErrorContext as LuaErrorContext,
|
||||
error::ExternalError as LuaExternalError, error::ExternalResult as LuaExternalResult,
|
||||
function::FunctionInfo as LuaFunctionInfo, function::LuaNativeFn, function::LuaNativeFnMut,
|
||||
state::GcIncParams as LuaGcIncParams, state::GcMode as LuaGcMode, table::TablePairs as LuaTablePairs,
|
||||
table::TableSequence as LuaTableSequence, thread::ThreadStatus as LuaThreadStatus,
|
||||
};
|
||||
|
||||
#[cfg(not(feature = "luau"))]
|
||||
#[doc(no_inline)]
|
||||
pub use crate::HookTriggers as LuaHookTriggers;
|
||||
|
||||
#[cfg(any(feature = "lua54", feature = "lua55"))]
|
||||
#[doc(no_inline)]
|
||||
pub use crate::state::GcGenParams as LuaGcGenParams;
|
||||
|
||||
#[cfg(feature = "luau")]
|
||||
#[doc(no_inline)]
|
||||
pub use crate::{CoverageInfo as LuaCoverageInfo, Vector as LuaVector, VmState as LuaVmState};
|
||||
pub use crate::{
|
||||
Vector as LuaVector,
|
||||
chunk::{CompileConstant as LuaCompileConstant, Compiler as LuaCompiler},
|
||||
luau::{
|
||||
FsRequirer as LuaFsRequirer, HeapDump as LuaHeapDump, NavigateError as LuaNavigateError,
|
||||
Require as LuaRequire,
|
||||
},
|
||||
};
|
||||
|
||||
#[cfg(feature = "async")]
|
||||
#[doc(no_inline)]
|
||||
pub use crate::AsyncThread as LuaAsyncThread;
|
||||
pub use crate::{function::LuaNativeAsyncFn, thread::AsyncThread as LuaAsyncThread};
|
||||
|
||||
#[cfg(feature = "serialize")]
|
||||
#[cfg(feature = "serde")]
|
||||
#[doc(no_inline)]
|
||||
pub use crate::{
|
||||
DeserializeOptions as LuaDeserializeOptions, LuaSerdeExt,
|
||||
DeserializeOptions as LuaDeserializeOptions, LuaSerdeExt, SerializableValue as LuaSerializableValue,
|
||||
SerializeOptions as LuaSerializeOptions,
|
||||
};
|
||||
|
||||
#[cfg(feature = "unstable")]
|
||||
#[doc(no_inline)]
|
||||
pub use crate::{
|
||||
OwnedAnyUserData as LuaOwnedAnyUserData, OwnedFunction as LuaOwnedFunction,
|
||||
OwnedString as LuaOwnedString, OwnedTable as LuaOwnedTable, OwnedThread as LuaOwnedThread,
|
||||
};
|
||||
|
||||
+202
-823
File diff suppressed because it is too large
Load Diff
+146
-90
@@ -1,8 +1,9 @@
|
||||
//! Deserialize Lua values to a Rust data structure.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::os::raw::c_void;
|
||||
use std::rc::Rc;
|
||||
use std::result::Result as StdResult;
|
||||
use std::string::String as StdString;
|
||||
|
||||
use rustc_hash::FxHashSet;
|
||||
use serde::de::{self, IntoDeserializer};
|
||||
@@ -13,11 +14,12 @@ use crate::userdata::AnyUserData;
|
||||
use crate::value::Value;
|
||||
|
||||
/// A struct for deserializing Lua values into Rust values.
|
||||
#[derive(Debug)]
|
||||
pub struct Deserializer<'lua> {
|
||||
value: Value<'lua>,
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Deserializer {
|
||||
value: Value,
|
||||
options: Options,
|
||||
visited: Rc<RefCell<FxHashSet<*const c_void>>>,
|
||||
len: Option<usize>, // A length hint for sequences
|
||||
}
|
||||
|
||||
/// A struct with options to change default deserializer behavior.
|
||||
@@ -47,11 +49,29 @@ pub struct Options {
|
||||
///
|
||||
/// Default: **false**
|
||||
pub sort_keys: bool,
|
||||
|
||||
/// If true, empty Lua tables will be encoded as array, instead of map.
|
||||
///
|
||||
/// Default: **false**
|
||||
pub encode_empty_tables_as_array: bool,
|
||||
|
||||
/// If true, enable detection of mixed tables.
|
||||
///
|
||||
/// A mixed table is a table that has both array-like and map-like entries or several borders.
|
||||
/// See [`The Length Operator`] documentation for details about borders.
|
||||
///
|
||||
/// When this option is disabled, a table with a non-zero length (with one or more borders) will
|
||||
/// be always encoded as an array.
|
||||
///
|
||||
/// Default: **false**
|
||||
///
|
||||
/// [`The Length Operator`]: https://www.lua.org/manual/5.4/manual.html#3.4.7
|
||||
pub detect_mixed_tables: bool,
|
||||
}
|
||||
|
||||
impl Default for Options {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
const { Self::new() }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -62,6 +82,8 @@ impl Options {
|
||||
deny_unsupported_types: true,
|
||||
deny_recursive_tables: true,
|
||||
sort_keys: false,
|
||||
encode_empty_tables_as_array: false,
|
||||
detect_mixed_tables: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -91,37 +113,57 @@ impl Options {
|
||||
self.sort_keys = enabled;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets [`encode_empty_tables_as_array`] option.
|
||||
///
|
||||
/// [`encode_empty_tables_as_array`]: #structfield.encode_empty_tables_as_array
|
||||
#[must_use]
|
||||
pub const fn encode_empty_tables_as_array(mut self, enabled: bool) -> Self {
|
||||
self.encode_empty_tables_as_array = enabled;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets [`detect_mixed_tables`] option.
|
||||
///
|
||||
/// [`detect_mixed_tables`]: #structfield.detect_mixed_tables
|
||||
#[must_use]
|
||||
pub const fn detect_mixed_tables(mut self, enable: bool) -> Self {
|
||||
self.detect_mixed_tables = enable;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl<'lua> Deserializer<'lua> {
|
||||
/// Creates a new Lua Deserializer for the `Value`.
|
||||
pub fn new(value: Value<'lua>) -> Self {
|
||||
impl Deserializer {
|
||||
/// Creates a new Lua Deserializer for the [`Value`].
|
||||
pub fn new(value: Value) -> Self {
|
||||
Self::new_with_options(value, Options::default())
|
||||
}
|
||||
|
||||
/// Creates a new Lua Deserializer for the `Value` with custom options.
|
||||
pub fn new_with_options(value: Value<'lua>, options: Options) -> Self {
|
||||
/// Creates a new Lua Deserializer for the [`Value`] with custom options.
|
||||
pub fn new_with_options(value: Value, options: Options) -> Self {
|
||||
Deserializer {
|
||||
value,
|
||||
options,
|
||||
visited: Rc::new(RefCell::new(FxHashSet::default())),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn from_parts(
|
||||
value: Value<'lua>,
|
||||
options: Options,
|
||||
visited: Rc<RefCell<FxHashSet<*const c_void>>>,
|
||||
) -> Self {
|
||||
fn from_parts(value: Value, options: Options, visited: Rc<RefCell<FxHashSet<*const c_void>>>) -> Self {
|
||||
Deserializer {
|
||||
value,
|
||||
options,
|
||||
visited,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn with_len(mut self, len: usize) -> Self {
|
||||
self.len = Some(len);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl<'lua, 'de> serde::Deserializer<'de> for Deserializer<'lua> {
|
||||
impl<'de> serde::Deserializer<'de> for Deserializer {
|
||||
type Error = Error;
|
||||
|
||||
#[inline]
|
||||
@@ -139,28 +181,31 @@ impl<'lua, 'de> serde::Deserializer<'de> for Deserializer<'lua> {
|
||||
#[cfg(feature = "luau")]
|
||||
Value::Vector(_) => self.deserialize_seq(visitor),
|
||||
Value::String(s) => match s.to_str() {
|
||||
Ok(s) => visitor.visit_str(s),
|
||||
Err(_) => visitor.visit_bytes(s.as_bytes()),
|
||||
Ok(s) => visitor.visit_str(&s),
|
||||
Err(_) => visitor.visit_bytes(&s.as_bytes()),
|
||||
},
|
||||
Value::Table(ref t) if t.raw_len() > 0 || t.is_array() => self.deserialize_seq(visitor),
|
||||
Value::Table(_) => self.deserialize_map(visitor),
|
||||
Value::Table(ref t) => {
|
||||
if let Some(len) = t.encode_as_array(self.options) {
|
||||
self.with_len(len).deserialize_seq(visitor)
|
||||
} else {
|
||||
self.deserialize_map(visitor)
|
||||
}
|
||||
}
|
||||
Value::LightUserData(ud) if ud.0.is_null() => visitor.visit_none(),
|
||||
Value::UserData(ud) if ud.is_serializable() => {
|
||||
serde_userdata(ud, |value| value.deserialize_any(visitor))
|
||||
}
|
||||
#[cfg(feature = "luau")]
|
||||
Value::UserData(ud) if ud.1 == crate::types::SubtypeId::Buffer => unsafe {
|
||||
let mut size = 0usize;
|
||||
let buf = ffi::lua_tobuffer(ud.0.lua.ref_thread(), ud.0.index, &mut size);
|
||||
mlua_assert!(!buf.is_null(), "invalid Luau buffer");
|
||||
let buf = std::slice::from_raw_parts(buf as *const u8, size);
|
||||
visitor.visit_bytes(buf)
|
||||
},
|
||||
Value::Buffer(buf) => {
|
||||
let lua = buf.0.lua.lock();
|
||||
visitor.visit_bytes(buf.as_slice(&lua))
|
||||
}
|
||||
Value::Function(_)
|
||||
| Value::Thread(_)
|
||||
| Value::UserData(_)
|
||||
| Value::LightUserData(_)
|
||||
| Value::Error(_) => {
|
||||
| Value::Error(_)
|
||||
| Value::Other(_) => {
|
||||
if self.options.deny_unsupported_types {
|
||||
let msg = format!("unsupported value type `{}`", self.value.type_name());
|
||||
Err(de::Error::custom(msg))
|
||||
@@ -197,14 +242,14 @@ impl<'lua, 'de> serde::Deserializer<'de> for Deserializer<'lua> {
|
||||
Value::Table(table) => {
|
||||
let _guard = RecursionGuard::new(&table, &self.visited);
|
||||
|
||||
let mut iter = table.pairs::<StdString, Value>();
|
||||
let mut iter = table.pairs::<String, Value>();
|
||||
let (variant, value) = match iter.next() {
|
||||
Some(v) => v?,
|
||||
None => {
|
||||
return Err(de::Error::invalid_value(
|
||||
de::Unexpected::Map,
|
||||
&"map with a single key",
|
||||
))
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
@@ -256,20 +301,17 @@ impl<'lua, 'de> serde::Deserializer<'de> for Deserializer<'lua> {
|
||||
Value::Table(t) => {
|
||||
let _guard = RecursionGuard::new(&t, &self.visited);
|
||||
|
||||
let len = t.raw_len();
|
||||
let len = self.len.unwrap_or_else(|| t.raw_len());
|
||||
let mut deserializer = SeqDeserializer {
|
||||
seq: t.sequence_values(),
|
||||
seq: t.sequence_values().with_len(len),
|
||||
options: self.options,
|
||||
visited: self.visited,
|
||||
};
|
||||
let seq = visitor.visit_seq(&mut deserializer)?;
|
||||
if deserializer.seq.count() == 0 {
|
||||
if deserializer.seq.next().is_none() {
|
||||
Ok(seq)
|
||||
} else {
|
||||
Err(de::Error::invalid_length(
|
||||
len,
|
||||
&"fewer elements in the table",
|
||||
))
|
||||
Err(de::Error::invalid_length(len, &"fewer elements in the table"))
|
||||
}
|
||||
}
|
||||
Value::UserData(ud) if ud.is_serializable() => {
|
||||
@@ -291,12 +333,7 @@ impl<'lua, 'de> serde::Deserializer<'de> for Deserializer<'lua> {
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn deserialize_tuple_struct<V>(
|
||||
self,
|
||||
_name: &'static str,
|
||||
_len: usize,
|
||||
visitor: V,
|
||||
) -> Result<V::Value>
|
||||
fn deserialize_tuple_struct<V>(self, _name: &'static str, _len: usize, visitor: V) -> Result<V::Value>
|
||||
where
|
||||
V: de::Visitor<'de>,
|
||||
{
|
||||
@@ -313,7 +350,7 @@ impl<'lua, 'de> serde::Deserializer<'de> for Deserializer<'lua> {
|
||||
let _guard = RecursionGuard::new(&t, &self.visited);
|
||||
|
||||
let mut deserializer = MapDeserializer {
|
||||
pairs: MapPairs::new(t, self.options.sort_keys)?,
|
||||
pairs: MapPairs::new(&t, self.options.sort_keys)?,
|
||||
value: None,
|
||||
options: self.options,
|
||||
visited: self.visited,
|
||||
@@ -394,13 +431,13 @@ impl<'lua, 'de> serde::Deserializer<'de> for Deserializer<'lua> {
|
||||
}
|
||||
}
|
||||
|
||||
struct SeqDeserializer<'lua> {
|
||||
seq: TableSequence<'lua, Value<'lua>>,
|
||||
struct SeqDeserializer<'a> {
|
||||
seq: TableSequence<'a, Value>,
|
||||
options: Options,
|
||||
visited: Rc<RefCell<FxHashSet<*const c_void>>>,
|
||||
}
|
||||
|
||||
impl<'lua, 'de> de::SeqAccess<'de> for SeqDeserializer<'lua> {
|
||||
impl<'de> de::SeqAccess<'de> for SeqDeserializer<'_> {
|
||||
type Error = Error;
|
||||
|
||||
fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>>
|
||||
@@ -435,7 +472,7 @@ impl<'lua, 'de> de::SeqAccess<'de> for SeqDeserializer<'lua> {
|
||||
|
||||
#[cfg(feature = "luau")]
|
||||
struct VecDeserializer {
|
||||
vec: crate::types::Vector,
|
||||
vec: crate::Vector,
|
||||
next: usize,
|
||||
options: Options,
|
||||
visited: Rc<RefCell<FxHashSet<*const c_void>>>,
|
||||
@@ -453,8 +490,7 @@ impl<'de> de::SeqAccess<'de> for VecDeserializer {
|
||||
Some(&n) => {
|
||||
self.next += 1;
|
||||
let visited = Rc::clone(&self.visited);
|
||||
let deserializer =
|
||||
Deserializer::from_parts(Value::Number(n as _), self.options, visited);
|
||||
let deserializer = Deserializer::from_parts(Value::Number(n as _), self.options, visited);
|
||||
seed.deserialize(deserializer).map(Some)
|
||||
}
|
||||
None => Ok(None),
|
||||
@@ -462,20 +498,20 @@ impl<'de> de::SeqAccess<'de> for VecDeserializer {
|
||||
}
|
||||
|
||||
fn size_hint(&self) -> Option<usize> {
|
||||
Some(crate::types::Vector::SIZE)
|
||||
Some(crate::Vector::SIZE)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) enum MapPairs<'lua> {
|
||||
Iter(TablePairs<'lua, Value<'lua>, Value<'lua>>),
|
||||
Vec(Vec<(Value<'lua>, Value<'lua>)>),
|
||||
pub(crate) enum MapPairs<'a> {
|
||||
Iter(TablePairs<'a, Value, Value>),
|
||||
Vec(Vec<(Value, Value)>),
|
||||
}
|
||||
|
||||
impl<'lua> MapPairs<'lua> {
|
||||
pub(crate) fn new(t: Table<'lua>, sort_keys: bool) -> Result<Self> {
|
||||
impl<'a> MapPairs<'a> {
|
||||
pub(crate) fn new(t: &'a Table, sort_keys: bool) -> Result<Self> {
|
||||
if sort_keys {
|
||||
let mut pairs = t.pairs::<Value, Value>().collect::<Result<Vec<_>>>()?;
|
||||
pairs.sort_by(|(a, _), (b, _)| b.cmp(a)); // reverse order as we pop values from the end
|
||||
pairs.sort_by(|(a, _), (b, _)| b.sort_cmp(a)); // reverse order as we pop values from the end
|
||||
Ok(MapPairs::Vec(pairs))
|
||||
} else {
|
||||
Ok(MapPairs::Iter(t.pairs::<Value, Value>()))
|
||||
@@ -497,8 +533,8 @@ impl<'lua> MapPairs<'lua> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<'lua> Iterator for MapPairs<'lua> {
|
||||
type Item = Result<(Value<'lua>, Value<'lua>)>;
|
||||
impl Iterator for MapPairs<'_> {
|
||||
type Item = Result<(Value, Value)>;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
match self {
|
||||
@@ -508,21 +544,16 @@ impl<'lua> Iterator for MapPairs<'lua> {
|
||||
}
|
||||
}
|
||||
|
||||
struct MapDeserializer<'lua> {
|
||||
pairs: MapPairs<'lua>,
|
||||
value: Option<Value<'lua>>,
|
||||
struct MapDeserializer<'a> {
|
||||
pairs: MapPairs<'a>,
|
||||
value: Option<Value>,
|
||||
options: Options,
|
||||
visited: Rc<RefCell<FxHashSet<*const c_void>>>,
|
||||
processed: usize,
|
||||
}
|
||||
|
||||
impl<'lua, 'de> de::MapAccess<'de> for MapDeserializer<'lua> {
|
||||
type Error = Error;
|
||||
|
||||
fn next_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>>
|
||||
where
|
||||
T: de::DeserializeSeed<'de>,
|
||||
{
|
||||
impl MapDeserializer<'_> {
|
||||
fn next_key_deserializer(&mut self) -> Result<Option<Deserializer>> {
|
||||
loop {
|
||||
match self.pairs.next() {
|
||||
Some(item) => {
|
||||
@@ -538,23 +569,45 @@ impl<'lua, 'de> de::MapAccess<'de> for MapDeserializer<'lua> {
|
||||
self.value = Some(value);
|
||||
let visited = Rc::clone(&self.visited);
|
||||
let key_de = Deserializer::from_parts(key, self.options, visited);
|
||||
return seed.deserialize(key_de).map(Some);
|
||||
return Ok(Some(key_de));
|
||||
}
|
||||
None => return Ok(None),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn next_value_deserializer(&mut self) -> Result<Deserializer> {
|
||||
match self.value.take() {
|
||||
Some(value) => {
|
||||
let visited = Rc::clone(&self.visited);
|
||||
Ok(Deserializer::from_parts(value, self.options, visited))
|
||||
}
|
||||
None => Err(de::Error::custom("value is missing")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> de::MapAccess<'de> for MapDeserializer<'_> {
|
||||
type Error = Error;
|
||||
|
||||
fn next_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>>
|
||||
where
|
||||
T: de::DeserializeSeed<'de>,
|
||||
{
|
||||
match self.next_key_deserializer() {
|
||||
Ok(Some(key_de)) => seed.deserialize(key_de).map(Some),
|
||||
Ok(None) => Ok(None),
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
}
|
||||
|
||||
fn next_value_seed<T>(&mut self, seed: T) -> Result<T::Value>
|
||||
where
|
||||
T: de::DeserializeSeed<'de>,
|
||||
{
|
||||
match self.value.take() {
|
||||
Some(value) => {
|
||||
let visited = Rc::clone(&self.visited);
|
||||
seed.deserialize(Deserializer::from_parts(value, self.options, visited))
|
||||
}
|
||||
None => Err(de::Error::custom("value is missing")),
|
||||
match self.next_value_deserializer() {
|
||||
Ok(value_de) => seed.deserialize(value_de),
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -566,16 +619,16 @@ impl<'lua, 'de> de::MapAccess<'de> for MapDeserializer<'lua> {
|
||||
}
|
||||
}
|
||||
|
||||
struct EnumDeserializer<'lua> {
|
||||
variant: StdString,
|
||||
value: Option<Value<'lua>>,
|
||||
struct EnumDeserializer {
|
||||
variant: String,
|
||||
value: Option<Value>,
|
||||
options: Options,
|
||||
visited: Rc<RefCell<FxHashSet<*const c_void>>>,
|
||||
}
|
||||
|
||||
impl<'lua, 'de> de::EnumAccess<'de> for EnumDeserializer<'lua> {
|
||||
impl<'de> de::EnumAccess<'de> for EnumDeserializer {
|
||||
type Error = Error;
|
||||
type Variant = VariantDeserializer<'lua>;
|
||||
type Variant = VariantDeserializer;
|
||||
|
||||
fn variant_seed<T>(self, seed: T) -> Result<(T::Value, Self::Variant)>
|
||||
where
|
||||
@@ -591,13 +644,13 @@ impl<'lua, 'de> de::EnumAccess<'de> for EnumDeserializer<'lua> {
|
||||
}
|
||||
}
|
||||
|
||||
struct VariantDeserializer<'lua> {
|
||||
value: Option<Value<'lua>>,
|
||||
struct VariantDeserializer {
|
||||
value: Option<Value>,
|
||||
options: Options,
|
||||
visited: Rc<RefCell<FxHashSet<*const c_void>>>,
|
||||
}
|
||||
|
||||
impl<'lua, 'de> de::VariantAccess<'de> for VariantDeserializer<'lua> {
|
||||
impl<'de> de::VariantAccess<'de> for VariantDeserializer {
|
||||
type Error = Error;
|
||||
|
||||
fn unit_variant(self) -> Result<()> {
|
||||
@@ -615,9 +668,7 @@ impl<'lua, 'de> de::VariantAccess<'de> for VariantDeserializer<'lua> {
|
||||
T: de::DeserializeSeed<'de>,
|
||||
{
|
||||
match self.value {
|
||||
Some(value) => {
|
||||
seed.deserialize(Deserializer::from_parts(value, self.options, self.visited))
|
||||
}
|
||||
Some(value) => seed.deserialize(Deserializer::from_parts(value, self.options, self.visited)),
|
||||
None => Err(de::Error::invalid_type(
|
||||
de::Unexpected::UnitVariant,
|
||||
&"newtype variant",
|
||||
@@ -716,6 +767,11 @@ fn serde_userdata<V>(
|
||||
ud: AnyUserData,
|
||||
f: impl FnOnce(serde_value::Value) -> std::result::Result<V, serde_value::DeserializerError>,
|
||||
) -> Result<V> {
|
||||
let value = serde_value::to_value(ud).map_err(|err| Error::SerializeError(err.to_string()))?;
|
||||
f(value).map_err(|err| Error::DeserializeError(err.to_string()))
|
||||
match serde_value::to_value(ud) {
|
||||
Ok(value) => match f(value) {
|
||||
Ok(r) => Ok(r),
|
||||
Err(error) => Err(Error::DeserializeError(error.to_string())),
|
||||
},
|
||||
Err(error) => Err(Error::SerializeError(error.to_string())),
|
||||
}
|
||||
}
|
||||
|
||||
+16
-35
@@ -2,22 +2,21 @@
|
||||
|
||||
use std::os::raw::c_void;
|
||||
|
||||
use serde::{de::DeserializeOwned, ser::Serialize};
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde::ser::Serialize;
|
||||
|
||||
use crate::error::Result;
|
||||
use crate::lua::Lua;
|
||||
use crate::private::Sealed;
|
||||
use crate::state::Lua;
|
||||
use crate::table::Table;
|
||||
use crate::util::check_stack;
|
||||
use crate::value::Value;
|
||||
|
||||
/// Trait for serializing/deserializing Lua values using Serde.
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "serialize")))]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
|
||||
pub trait LuaSerdeExt: Sealed {
|
||||
/// A special value (lightuserdata) to encode/decode optional (none) values.
|
||||
///
|
||||
/// Requires `feature = "serialize"`
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
@@ -38,10 +37,8 @@ pub trait LuaSerdeExt: Sealed {
|
||||
fn null(&self) -> Value;
|
||||
|
||||
/// A metatable attachable to a Lua table to systematically encode it as Array (instead of Map).
|
||||
/// As result, encoded Array will contain only sequence part of the table, with the same length
|
||||
/// as the `#` operator on that table.
|
||||
///
|
||||
/// Requires `feature = "serialize"`
|
||||
/// As a result, encoded Array will contain only sequence part of the table, with the same
|
||||
/// length as the `#` operator on that table.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
@@ -70,8 +67,6 @@ pub trait LuaSerdeExt: Sealed {
|
||||
|
||||
/// Converts `T` into a [`Value`] instance.
|
||||
///
|
||||
/// Requires `feature = "serialize"`
|
||||
///
|
||||
/// [`Value`]: crate::Value
|
||||
///
|
||||
/// # Example
|
||||
@@ -99,14 +94,10 @@ pub trait LuaSerdeExt: Sealed {
|
||||
/// "#).exec()
|
||||
/// }
|
||||
/// ```
|
||||
fn to_value<'lua, T: Serialize + ?Sized>(&'lua self, t: &T) -> Result<Value<'lua>>;
|
||||
fn to_value<T: Serialize + ?Sized>(&self, t: &T) -> Result<Value>;
|
||||
|
||||
/// Converts `T` into a [`Value`] instance with options.
|
||||
///
|
||||
/// Requires `feature = "serialize"`
|
||||
///
|
||||
/// [`Value`]: crate::Value
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
@@ -124,16 +115,12 @@ pub trait LuaSerdeExt: Sealed {
|
||||
/// "#).exec()
|
||||
/// }
|
||||
/// ```
|
||||
fn to_value_with<'lua, T>(&'lua self, t: &T, options: ser::Options) -> Result<Value<'lua>>
|
||||
fn to_value_with<T>(&self, t: &T, options: ser::Options) -> Result<Value>
|
||||
where
|
||||
T: Serialize + ?Sized;
|
||||
|
||||
/// Deserializes a [`Value`] into any serde deserializable object.
|
||||
///
|
||||
/// Requires `feature = "serialize"`
|
||||
///
|
||||
/// [`Value`]: crate::Value
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
@@ -161,10 +148,6 @@ pub trait LuaSerdeExt: Sealed {
|
||||
|
||||
/// Deserializes a [`Value`] into any serde deserializable object with options.
|
||||
///
|
||||
/// Requires `feature = "serialize"`
|
||||
///
|
||||
/// [`Value`]: crate::Value
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
@@ -189,8 +172,7 @@ pub trait LuaSerdeExt: Sealed {
|
||||
/// }
|
||||
/// ```
|
||||
#[allow(clippy::wrong_self_convention)]
|
||||
fn from_value_with<T: DeserializeOwned>(&self, value: Value, options: de::Options)
|
||||
-> Result<T>;
|
||||
fn from_value_with<T: DeserializeOwned>(&self, value: Value, options: de::Options) -> Result<T>;
|
||||
}
|
||||
|
||||
impl LuaSerdeExt for Lua {
|
||||
@@ -199,20 +181,21 @@ impl LuaSerdeExt for Lua {
|
||||
}
|
||||
|
||||
fn array_metatable(&self) -> Table {
|
||||
let lua = self.lock();
|
||||
unsafe {
|
||||
push_array_metatable(self.ref_thread());
|
||||
Table(self.pop_ref_thread())
|
||||
push_array_metatable(lua.ref_thread());
|
||||
Table(lua.pop_ref_thread())
|
||||
}
|
||||
}
|
||||
|
||||
fn to_value<'lua, T>(&'lua self, t: &T) -> Result<Value<'lua>>
|
||||
fn to_value<T>(&self, t: &T) -> Result<Value>
|
||||
where
|
||||
T: Serialize + ?Sized,
|
||||
{
|
||||
t.serialize(ser::Serializer::new(self))
|
||||
}
|
||||
|
||||
fn to_value_with<'lua, T>(&'lua self, t: &T, options: ser::Options) -> Result<Value<'lua>>
|
||||
fn to_value_with<T>(&self, t: &T, options: ser::Options) -> Result<Value>
|
||||
where
|
||||
T: Serialize + ?Sized,
|
||||
{
|
||||
@@ -259,7 +242,5 @@ static ARRAY_METATABLE_REGISTRY_KEY: u8 = 0;
|
||||
pub mod de;
|
||||
pub mod ser;
|
||||
|
||||
#[doc(inline)]
|
||||
pub use de::Deserializer;
|
||||
#[doc(inline)]
|
||||
pub use ser::Serializer;
|
||||
pub use de::{Deserializer, Options as DeserializeOptions};
|
||||
pub use ser::{Options as SerializeOptions, Serializer};
|
||||
|
||||
+98
-102
@@ -1,15 +1,18 @@
|
||||
use serde::{ser, Serialize};
|
||||
//! Serialize a Rust data structure into Lua value.
|
||||
|
||||
use serde::{Serialize, ser};
|
||||
|
||||
use super::LuaSerdeExt;
|
||||
use crate::error::{Error, Result};
|
||||
use crate::lua::Lua;
|
||||
use crate::state::Lua;
|
||||
use crate::table::Table;
|
||||
use crate::value::{IntoLua, Value};
|
||||
use crate::traits::IntoLua;
|
||||
use crate::value::Value;
|
||||
|
||||
/// A struct for serializing Rust values into Lua values.
|
||||
#[derive(Debug)]
|
||||
pub struct Serializer<'lua> {
|
||||
lua: &'lua Lua,
|
||||
pub struct Serializer<'a> {
|
||||
lua: &'a Lua,
|
||||
options: Options,
|
||||
}
|
||||
|
||||
@@ -52,7 +55,7 @@ pub struct Options {
|
||||
|
||||
impl Default for Options {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
const { Self::new() }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -96,8 +99,8 @@ impl Options {
|
||||
|
||||
/// Sets [`detect_serde_json_arbitrary_precision`] option.
|
||||
///
|
||||
/// This option is used to serialize `serde_json::Number` with arbitrary precision to a Lua number.
|
||||
/// Otherwise it will be serialized as an object (what serde does).
|
||||
/// This option is used to serialize `serde_json::Number` with arbitrary precision to a Lua
|
||||
/// number. Otherwise it will be serialized as an object (what serde does).
|
||||
///
|
||||
/// This option is disabled by default.
|
||||
///
|
||||
@@ -109,14 +112,14 @@ impl Options {
|
||||
}
|
||||
}
|
||||
|
||||
impl<'lua> Serializer<'lua> {
|
||||
impl<'a> Serializer<'a> {
|
||||
/// Creates a new Lua Serializer with default options.
|
||||
pub fn new(lua: &'lua Lua) -> Self {
|
||||
pub fn new(lua: &'a Lua) -> Self {
|
||||
Self::new_with_options(lua, Options::default())
|
||||
}
|
||||
|
||||
/// Creates a new Lua Serializer with custom options.
|
||||
pub fn new_with_options(lua: &'lua Lua, options: Options) -> Self {
|
||||
pub fn new_with_options(lua: &'a Lua, options: Options) -> Self {
|
||||
Serializer { lua, options }
|
||||
}
|
||||
}
|
||||
@@ -124,28 +127,28 @@ impl<'lua> Serializer<'lua> {
|
||||
macro_rules! lua_serialize_number {
|
||||
($name:ident, $t:ty) => {
|
||||
#[inline]
|
||||
fn $name(self, value: $t) -> Result<Value<'lua>> {
|
||||
fn $name(self, value: $t) -> Result<Value> {
|
||||
value.into_lua(self.lua)
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
impl<'lua> ser::Serializer for Serializer<'lua> {
|
||||
type Ok = Value<'lua>;
|
||||
impl<'a> ser::Serializer for Serializer<'a> {
|
||||
type Ok = Value;
|
||||
type Error = Error;
|
||||
|
||||
// Associated types for keeping track of additional state while serializing
|
||||
// compound data structures like sequences and maps.
|
||||
type SerializeSeq = SerializeSeq<'lua>;
|
||||
type SerializeTuple = SerializeSeq<'lua>;
|
||||
type SerializeTupleStruct = SerializeSeq<'lua>;
|
||||
type SerializeTupleVariant = SerializeTupleVariant<'lua>;
|
||||
type SerializeMap = SerializeMap<'lua>;
|
||||
type SerializeStruct = SerializeStruct<'lua>;
|
||||
type SerializeStructVariant = SerializeStructVariant<'lua>;
|
||||
type SerializeSeq = SerializeSeq<'a>;
|
||||
type SerializeTuple = SerializeSeq<'a>;
|
||||
type SerializeTupleStruct = SerializeSeq<'a>;
|
||||
type SerializeTupleVariant = SerializeTupleVariant<'a>;
|
||||
type SerializeMap = SerializeMap<'a>;
|
||||
type SerializeStruct = SerializeStruct<'a>;
|
||||
type SerializeStructVariant = SerializeStructVariant<'a>;
|
||||
|
||||
#[inline]
|
||||
fn serialize_bool(self, value: bool) -> Result<Value<'lua>> {
|
||||
fn serialize_bool(self, value: bool) -> Result<Value> {
|
||||
Ok(Value::Boolean(value))
|
||||
}
|
||||
|
||||
@@ -164,22 +167,22 @@ impl<'lua> ser::Serializer for Serializer<'lua> {
|
||||
lua_serialize_number!(serialize_f64, f64);
|
||||
|
||||
#[inline]
|
||||
fn serialize_char(self, value: char) -> Result<Value<'lua>> {
|
||||
fn serialize_char(self, value: char) -> Result<Value> {
|
||||
self.serialize_str(&value.to_string())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn serialize_str(self, value: &str) -> Result<Value<'lua>> {
|
||||
fn serialize_str(self, value: &str) -> Result<Value> {
|
||||
self.lua.create_string(value).map(Value::String)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn serialize_bytes(self, value: &[u8]) -> Result<Value<'lua>> {
|
||||
fn serialize_bytes(self, value: &[u8]) -> Result<Value> {
|
||||
self.lua.create_string(value).map(Value::String)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn serialize_none(self) -> Result<Value<'lua>> {
|
||||
fn serialize_none(self) -> Result<Value> {
|
||||
if self.options.serialize_none_to_null {
|
||||
Ok(self.lua.null())
|
||||
} else {
|
||||
@@ -188,7 +191,7 @@ impl<'lua> ser::Serializer for Serializer<'lua> {
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn serialize_some<T>(self, value: &T) -> Result<Value<'lua>>
|
||||
fn serialize_some<T>(self, value: &T) -> Result<Value>
|
||||
where
|
||||
T: Serialize + ?Sized,
|
||||
{
|
||||
@@ -196,7 +199,7 @@ impl<'lua> ser::Serializer for Serializer<'lua> {
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn serialize_unit(self) -> Result<Value<'lua>> {
|
||||
fn serialize_unit(self) -> Result<Value> {
|
||||
if self.options.serialize_unit_to_null {
|
||||
Ok(self.lua.null())
|
||||
} else {
|
||||
@@ -205,7 +208,7 @@ impl<'lua> ser::Serializer for Serializer<'lua> {
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn serialize_unit_struct(self, _name: &'static str) -> Result<Value<'lua>> {
|
||||
fn serialize_unit_struct(self, _name: &'static str) -> Result<Value> {
|
||||
if self.options.serialize_unit_to_null {
|
||||
Ok(self.lua.null())
|
||||
} else {
|
||||
@@ -219,12 +222,12 @@ impl<'lua> ser::Serializer for Serializer<'lua> {
|
||||
_name: &'static str,
|
||||
_variant_index: u32,
|
||||
variant: &'static str,
|
||||
) -> Result<Value<'lua>> {
|
||||
) -> Result<Value> {
|
||||
self.serialize_str(variant)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn serialize_newtype_struct<T>(self, _name: &'static str, value: &T) -> Result<Value<'lua>>
|
||||
fn serialize_newtype_struct<T>(self, _name: &'static str, value: &T) -> Result<Value>
|
||||
where
|
||||
T: Serialize + ?Sized,
|
||||
{
|
||||
@@ -238,7 +241,7 @@ impl<'lua> ser::Serializer for Serializer<'lua> {
|
||||
_variant_index: u32,
|
||||
variant: &'static str,
|
||||
value: &T,
|
||||
) -> Result<Value<'lua>>
|
||||
) -> Result<Value>
|
||||
where
|
||||
T: Serialize + ?Sized,
|
||||
{
|
||||
@@ -253,9 +256,9 @@ impl<'lua> ser::Serializer for Serializer<'lua> {
|
||||
fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq> {
|
||||
let table = self.lua.create_table_with_capacity(len.unwrap_or(0), 0)?;
|
||||
if self.options.set_array_metatable {
|
||||
table.set_metatable(Some(self.lua.array_metatable()));
|
||||
table.set_metatable(Some(self.lua.array_metatable()))?;
|
||||
}
|
||||
Ok(SerializeSeq::new(table, self.options))
|
||||
Ok(SerializeSeq::new(self.lua, table, self.options))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
@@ -264,13 +267,9 @@ impl<'lua> ser::Serializer for Serializer<'lua> {
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn serialize_tuple_struct(
|
||||
self,
|
||||
name: &'static str,
|
||||
len: usize,
|
||||
) -> Result<Self::SerializeTupleStruct> {
|
||||
fn serialize_tuple_struct(self, name: &'static str, len: usize) -> Result<Self::SerializeTupleStruct> {
|
||||
#[cfg(feature = "luau")]
|
||||
if name == "Vector" && len == crate::types::Vector::SIZE {
|
||||
if name == "Vector" && len == crate::Vector::SIZE {
|
||||
return Ok(SerializeSeq::new_vector(self.lua, self.options));
|
||||
}
|
||||
_ = name;
|
||||
@@ -286,6 +285,7 @@ impl<'lua> ser::Serializer for Serializer<'lua> {
|
||||
_len: usize,
|
||||
) -> Result<Self::SerializeTupleVariant> {
|
||||
Ok(SerializeTupleVariant {
|
||||
lua: self.lua,
|
||||
variant,
|
||||
table: self.lua.create_table()?,
|
||||
options: self.options,
|
||||
@@ -295,6 +295,7 @@ impl<'lua> ser::Serializer for Serializer<'lua> {
|
||||
#[inline]
|
||||
fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap> {
|
||||
Ok(SerializeMap {
|
||||
lua: self.lua,
|
||||
key: None,
|
||||
table: self.lua.create_table_with_capacity(0, len.unwrap_or(0))?,
|
||||
options: self.options,
|
||||
@@ -330,6 +331,7 @@ impl<'lua> ser::Serializer for Serializer<'lua> {
|
||||
len: usize,
|
||||
) -> Result<Self::SerializeStructVariant> {
|
||||
Ok(SerializeStructVariant {
|
||||
lua: self.lua,
|
||||
variant,
|
||||
table: self.lua.create_table_with_capacity(0, len)?,
|
||||
options: self.options,
|
||||
@@ -338,19 +340,19 @@ impl<'lua> ser::Serializer for Serializer<'lua> {
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub struct SerializeSeq<'lua> {
|
||||
lua: &'lua Lua,
|
||||
pub struct SerializeSeq<'a> {
|
||||
lua: &'a Lua,
|
||||
#[cfg(feature = "luau")]
|
||||
vector: Option<crate::types::Vector>,
|
||||
table: Option<Table<'lua>>,
|
||||
vector: Option<crate::Vector>,
|
||||
table: Option<Table>,
|
||||
next: usize,
|
||||
options: Options,
|
||||
}
|
||||
|
||||
impl<'lua> SerializeSeq<'lua> {
|
||||
const fn new(table: Table<'lua>, options: Options) -> Self {
|
||||
impl<'a> SerializeSeq<'a> {
|
||||
fn new(lua: &'a Lua, table: Table, options: Options) -> Self {
|
||||
Self {
|
||||
lua: table.0.lua,
|
||||
lua,
|
||||
#[cfg(feature = "luau")]
|
||||
vector: None,
|
||||
table: Some(table),
|
||||
@@ -360,10 +362,10 @@ impl<'lua> SerializeSeq<'lua> {
|
||||
}
|
||||
|
||||
#[cfg(feature = "luau")]
|
||||
const fn new_vector(lua: &'lua Lua, options: Options) -> Self {
|
||||
const fn new_vector(lua: &'a Lua, options: Options) -> Self {
|
||||
Self {
|
||||
lua,
|
||||
vector: Some(crate::types::Vector::zero()),
|
||||
vector: Some(crate::Vector::zero()),
|
||||
table: None,
|
||||
next: 0,
|
||||
options,
|
||||
@@ -371,8 +373,8 @@ impl<'lua> SerializeSeq<'lua> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<'lua> ser::SerializeSeq for SerializeSeq<'lua> {
|
||||
type Ok = Value<'lua>;
|
||||
impl ser::SerializeSeq for SerializeSeq<'_> {
|
||||
type Ok = Value;
|
||||
type Error = Error;
|
||||
|
||||
fn serialize_element<T>(&mut self, value: &T) -> Result<()>
|
||||
@@ -386,13 +388,13 @@ impl<'lua> ser::SerializeSeq for SerializeSeq<'lua> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn end(self) -> Result<Value<'lua>> {
|
||||
fn end(self) -> Result<Value> {
|
||||
Ok(Value::Table(self.table.unwrap()))
|
||||
}
|
||||
}
|
||||
|
||||
impl<'lua> ser::SerializeTuple for SerializeSeq<'lua> {
|
||||
type Ok = Value<'lua>;
|
||||
impl ser::SerializeTuple for SerializeSeq<'_> {
|
||||
type Ok = Value;
|
||||
type Error = Error;
|
||||
|
||||
fn serialize_element<T>(&mut self, value: &T) -> Result<()>
|
||||
@@ -402,13 +404,13 @@ impl<'lua> ser::SerializeTuple for SerializeSeq<'lua> {
|
||||
ser::SerializeSeq::serialize_element(self, value)
|
||||
}
|
||||
|
||||
fn end(self) -> Result<Value<'lua>> {
|
||||
fn end(self) -> Result<Value> {
|
||||
ser::SerializeSeq::end(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'lua> ser::SerializeTupleStruct for SerializeSeq<'lua> {
|
||||
type Ok = Value<'lua>;
|
||||
impl ser::SerializeTupleStruct for SerializeSeq<'_> {
|
||||
type Ok = Value;
|
||||
type Error = Error;
|
||||
|
||||
fn serialize_field<T>(&mut self, value: &T) -> Result<()>
|
||||
@@ -426,7 +428,7 @@ impl<'lua> ser::SerializeTupleStruct for SerializeSeq<'lua> {
|
||||
ser::SerializeSeq::serialize_element(self, value)
|
||||
}
|
||||
|
||||
fn end(self) -> Result<Value<'lua>> {
|
||||
fn end(self) -> Result<Value> {
|
||||
#[cfg(feature = "luau")]
|
||||
if let Some(vector) = self.vector {
|
||||
return Ok(Value::Vector(vector));
|
||||
@@ -436,49 +438,48 @@ impl<'lua> ser::SerializeTupleStruct for SerializeSeq<'lua> {
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub struct SerializeTupleVariant<'lua> {
|
||||
pub struct SerializeTupleVariant<'a> {
|
||||
lua: &'a Lua,
|
||||
variant: &'static str,
|
||||
table: Table<'lua>,
|
||||
table: Table,
|
||||
options: Options,
|
||||
}
|
||||
|
||||
impl<'lua> ser::SerializeTupleVariant for SerializeTupleVariant<'lua> {
|
||||
type Ok = Value<'lua>;
|
||||
impl ser::SerializeTupleVariant for SerializeTupleVariant<'_> {
|
||||
type Ok = Value;
|
||||
type Error = Error;
|
||||
|
||||
fn serialize_field<T>(&mut self, value: &T) -> Result<()>
|
||||
where
|
||||
T: Serialize + ?Sized,
|
||||
{
|
||||
let lua = self.table.0.lua;
|
||||
self.table.raw_push(lua.to_value_with(value, self.options)?)
|
||||
self.table.raw_push(self.lua.to_value_with(value, self.options)?)
|
||||
}
|
||||
|
||||
fn end(self) -> Result<Value<'lua>> {
|
||||
let lua = self.table.0.lua;
|
||||
let table = lua.create_table()?;
|
||||
fn end(self) -> Result<Value> {
|
||||
let table = self.lua.create_table()?;
|
||||
table.raw_set(self.variant, self.table)?;
|
||||
Ok(Value::Table(table))
|
||||
}
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub struct SerializeMap<'lua> {
|
||||
table: Table<'lua>,
|
||||
key: Option<Value<'lua>>,
|
||||
pub struct SerializeMap<'a> {
|
||||
lua: &'a Lua,
|
||||
table: Table,
|
||||
key: Option<Value>,
|
||||
options: Options,
|
||||
}
|
||||
|
||||
impl<'lua> ser::SerializeMap for SerializeMap<'lua> {
|
||||
type Ok = Value<'lua>;
|
||||
impl ser::SerializeMap for SerializeMap<'_> {
|
||||
type Ok = Value;
|
||||
type Error = Error;
|
||||
|
||||
fn serialize_key<T>(&mut self, key: &T) -> Result<()>
|
||||
where
|
||||
T: Serialize + ?Sized,
|
||||
{
|
||||
let lua = self.table.0.lua;
|
||||
self.key = Some(lua.to_value_with(key, self.options)?);
|
||||
self.key = Some(self.lua.to_value_with(key, self.options)?);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -486,29 +487,25 @@ impl<'lua> ser::SerializeMap for SerializeMap<'lua> {
|
||||
where
|
||||
T: Serialize + ?Sized,
|
||||
{
|
||||
let lua = self.table.0.lua;
|
||||
let key = mlua_expect!(
|
||||
self.key.take(),
|
||||
"serialize_value called before serialize_key"
|
||||
);
|
||||
let value = lua.to_value_with(value, self.options)?;
|
||||
let key = mlua_expect!(self.key.take(), "serialize_value called before serialize_key");
|
||||
let value = self.lua.to_value_with(value, self.options)?;
|
||||
self.table.raw_set(key, value)
|
||||
}
|
||||
|
||||
fn end(self) -> Result<Value<'lua>> {
|
||||
fn end(self) -> Result<Value> {
|
||||
Ok(Value::Table(self.table))
|
||||
}
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub struct SerializeStruct<'lua> {
|
||||
lua: &'lua Lua,
|
||||
inner: Option<Value<'lua>>,
|
||||
pub struct SerializeStruct<'a> {
|
||||
lua: &'a Lua,
|
||||
inner: Option<Value>,
|
||||
options: Options,
|
||||
}
|
||||
|
||||
impl<'lua> ser::SerializeStruct for SerializeStruct<'lua> {
|
||||
type Ok = Value<'lua>;
|
||||
impl ser::SerializeStruct for SerializeStruct<'_> {
|
||||
type Ok = Value;
|
||||
type Error = Error;
|
||||
|
||||
fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()>
|
||||
@@ -529,15 +526,15 @@ impl<'lua> ser::SerializeStruct for SerializeStruct<'lua> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn end(self) -> Result<Value<'lua>> {
|
||||
fn end(self) -> Result<Value> {
|
||||
match self.inner {
|
||||
Some(table @ Value::Table(_)) => Ok(table),
|
||||
Some(value) if self.options.detect_serde_json_arbitrary_precision => {
|
||||
let number_s = value.as_str().expect("not an arbitrary precision number");
|
||||
if number_s.contains(['.', 'e', 'E']) {
|
||||
if let Ok(number) = number_s.parse().map(Value::Number) {
|
||||
return Ok(number);
|
||||
}
|
||||
Some(value @ Value::String(_)) if self.options.detect_serde_json_arbitrary_precision => {
|
||||
let number_s = value.to_string()?;
|
||||
if number_s.contains(['.', 'e', 'E'])
|
||||
&& let Ok(number) = number_s.parse().map(Value::Number)
|
||||
{
|
||||
return Ok(number);
|
||||
}
|
||||
Ok(number_s
|
||||
.parse()
|
||||
@@ -551,29 +548,28 @@ impl<'lua> ser::SerializeStruct for SerializeStruct<'lua> {
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub struct SerializeStructVariant<'lua> {
|
||||
pub struct SerializeStructVariant<'a> {
|
||||
lua: &'a Lua,
|
||||
variant: &'static str,
|
||||
table: Table<'lua>,
|
||||
table: Table,
|
||||
options: Options,
|
||||
}
|
||||
|
||||
impl<'lua> ser::SerializeStructVariant for SerializeStructVariant<'lua> {
|
||||
type Ok = Value<'lua>;
|
||||
impl ser::SerializeStructVariant for SerializeStructVariant<'_> {
|
||||
type Ok = Value;
|
||||
type Error = Error;
|
||||
|
||||
fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()>
|
||||
where
|
||||
T: Serialize + ?Sized,
|
||||
{
|
||||
let lua = self.table.0.lua;
|
||||
self.table
|
||||
.raw_set(key, lua.to_value_with(value, self.options)?)?;
|
||||
.raw_set(key, self.lua.to_value_with(value, self.options)?)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn end(self) -> Result<Value<'lua>> {
|
||||
let lua = self.table.0.lua;
|
||||
let table = lua.create_table_with_capacity(0, 1)?;
|
||||
fn end(self) -> Result<Value> {
|
||||
let table = self.lua.create_table_with_capacity(0, 1)?;
|
||||
table.raw_set(self.variant, self.table)?;
|
||||
Ok(Value::Table(table))
|
||||
}
|
||||
|
||||
+2470
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,291 @@
|
||||
use std::any::TypeId;
|
||||
use std::cell::UnsafeCell;
|
||||
use std::mem::MaybeUninit;
|
||||
use std::os::raw::{c_int, c_void};
|
||||
use std::ptr;
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
|
||||
use parking_lot::Mutex;
|
||||
use rustc_hash::FxHashMap;
|
||||
|
||||
use crate::error::Result;
|
||||
use crate::state::RawLua;
|
||||
use crate::stdlib::StdLib;
|
||||
use crate::thread::ThreadTriggers;
|
||||
use crate::types::{AppData, ReentrantMutex, ThreadEventCallback, XRc};
|
||||
use crate::userdata::RawUserDataRegistry;
|
||||
use crate::util::{TypeKey, WrappedFailure, get_internal_metatable, push_internal_userdata};
|
||||
|
||||
#[cfg(any(feature = "luau", doc))]
|
||||
use crate::chunk::Compiler;
|
||||
|
||||
#[cfg(feature = "async")]
|
||||
use {futures_util::task::noop_waker_ref, std::ptr::NonNull, std::task::Waker};
|
||||
|
||||
use super::{Lua, WeakLua};
|
||||
|
||||
// Unique key to store `ExtraData` in the registry
|
||||
static EXTRA_REGISTRY_KEY: u8 = 0;
|
||||
|
||||
const WRAPPED_FAILURE_POOL_DEFAULT_CAPACITY: usize = 64;
|
||||
const REF_STACK_RESERVE: c_int = 3;
|
||||
|
||||
/// Data associated with the Lua state.
|
||||
pub(crate) struct ExtraData {
|
||||
pub(super) lua: MaybeUninit<Lua>,
|
||||
pub(super) weak: MaybeUninit<WeakLua>,
|
||||
pub(super) owned: bool,
|
||||
|
||||
pub(super) pending_userdata_reg: FxHashMap<TypeId, RawUserDataRegistry>,
|
||||
pub(super) registered_userdata_t: FxHashMap<TypeId, c_int>,
|
||||
pub(super) registered_userdata_mt: FxHashMap<*const c_void, Option<TypeId>>,
|
||||
pub(super) last_checked_userdata_mt: (*const c_void, Option<TypeId>),
|
||||
|
||||
// When Lua instance dropped, setting `None` would prevent collecting `RegistryKey`s
|
||||
pub(super) registry_unref_list: Arc<Mutex<Option<Vec<c_int>>>>,
|
||||
|
||||
// Containers to store arbitrary data (extensions)
|
||||
pub(super) app_data: AppData,
|
||||
pub(super) app_data_priv: AppData,
|
||||
|
||||
pub(super) safe: bool,
|
||||
pub(super) libs: StdLib,
|
||||
// Used in module mode
|
||||
pub(super) skip_memory_check: bool,
|
||||
|
||||
// Auxiliary thread to store references
|
||||
pub(super) ref_thread: *mut ffi::lua_State,
|
||||
pub(super) ref_stack_size: c_int,
|
||||
pub(super) ref_stack_top: c_int,
|
||||
pub(super) ref_free: Vec<c_int>,
|
||||
|
||||
// Pool of `WrappedFailure` enums in the ref thread (as userdata)
|
||||
pub(super) wrapped_failure_pool: Vec<c_int>,
|
||||
pub(super) wrapped_failure_top: usize,
|
||||
// Pool of `Thread`s (coroutines) for async execution
|
||||
#[cfg(feature = "async")]
|
||||
pub(super) thread_pool: Vec<crate::types::ValueRefIndex>,
|
||||
|
||||
// Address of `WrappedFailure` metatable
|
||||
pub(super) wrapped_failure_mt_ptr: *const c_void,
|
||||
|
||||
// Waker for polling futures
|
||||
#[cfg(feature = "async")]
|
||||
pub(super) waker: NonNull<Waker>,
|
||||
|
||||
#[cfg(not(feature = "luau"))]
|
||||
pub(super) hook_callback: Option<crate::types::HookCallback>,
|
||||
#[cfg(not(feature = "luau"))]
|
||||
pub(super) hook_triggers: crate::debug::HookTriggers,
|
||||
#[cfg(any(feature = "lua55", feature = "lua54"))]
|
||||
pub(super) warn_callback: Option<crate::types::WarnCallback>,
|
||||
#[cfg(feature = "luau")]
|
||||
pub(super) interrupt_callback: Option<crate::types::InterruptCallback>,
|
||||
pub(super) thread_triggers: ThreadTriggers,
|
||||
pub(super) thread_event_callback: Option<ThreadEventCallback>,
|
||||
|
||||
#[cfg(feature = "luau")]
|
||||
pub(crate) running_gc: bool,
|
||||
#[cfg(feature = "luau")]
|
||||
pub(crate) sandboxed: bool,
|
||||
#[cfg(feature = "luau")]
|
||||
pub(super) compiler: Option<Compiler>,
|
||||
#[cfg(feature = "luau-jit")]
|
||||
pub(super) enable_jit: bool,
|
||||
#[cfg(feature = "luau")]
|
||||
pub(crate) mem_categories: Vec<std::ffi::CString>,
|
||||
}
|
||||
|
||||
impl Drop for ExtraData {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
if !self.owned {
|
||||
self.lua.assume_init_drop();
|
||||
}
|
||||
|
||||
self.weak.assume_init_drop();
|
||||
}
|
||||
*self.registry_unref_list.lock() = None;
|
||||
}
|
||||
}
|
||||
|
||||
static EXTRA_TYPE_KEY: u8 = 0;
|
||||
|
||||
impl TypeKey for XRc<UnsafeCell<ExtraData>> {
|
||||
#[inline(always)]
|
||||
fn type_key() -> *const c_void {
|
||||
&EXTRA_TYPE_KEY as *const u8 as *const c_void
|
||||
}
|
||||
}
|
||||
|
||||
impl ExtraData {
|
||||
// Index of `error_traceback` function in auxiliary thread stack
|
||||
#[cfg(any(feature = "lua51", feature = "luajit", feature = "luau"))]
|
||||
pub(super) const ERROR_TRACEBACK_IDX: c_int = 1;
|
||||
|
||||
pub(super) unsafe fn init(state: *mut ffi::lua_State, owned: bool) -> XRc<UnsafeCell<Self>> {
|
||||
// Create ref stack thread and place it in the registry to prevent it
|
||||
// from being garbage collected.
|
||||
let ref_thread = mlua_expect!(
|
||||
protect_lua!(state, 0, 0, |state| {
|
||||
let thread = ffi::lua_newthread(state);
|
||||
ffi::luaL_ref(state, ffi::LUA_REGISTRYINDEX);
|
||||
thread
|
||||
}),
|
||||
"Error while creating ref thread",
|
||||
);
|
||||
|
||||
let wrapped_failure_mt_ptr = {
|
||||
get_internal_metatable::<WrappedFailure>(state);
|
||||
let ptr = ffi::lua_topointer(state, -1);
|
||||
ffi::lua_pop(state, 1);
|
||||
ptr
|
||||
};
|
||||
|
||||
// Store `error_traceback` function on the ref stack
|
||||
#[cfg(any(feature = "lua51", feature = "luajit", feature = "luau"))]
|
||||
{
|
||||
ffi::lua_pushcfunction(ref_thread, crate::util::error_traceback);
|
||||
assert_eq!(ffi::lua_gettop(ref_thread), Self::ERROR_TRACEBACK_IDX);
|
||||
}
|
||||
|
||||
#[allow(clippy::arc_with_non_send_sync)]
|
||||
let extra = XRc::new(UnsafeCell::new(ExtraData {
|
||||
lua: MaybeUninit::uninit(),
|
||||
weak: MaybeUninit::uninit(),
|
||||
owned,
|
||||
pending_userdata_reg: FxHashMap::default(),
|
||||
registered_userdata_t: FxHashMap::default(),
|
||||
registered_userdata_mt: FxHashMap::default(),
|
||||
last_checked_userdata_mt: (ptr::null(), None),
|
||||
registry_unref_list: Arc::new(Mutex::new(Some(Vec::new()))),
|
||||
app_data: AppData::default(),
|
||||
app_data_priv: AppData::default(),
|
||||
safe: false,
|
||||
libs: StdLib::NONE,
|
||||
skip_memory_check: false,
|
||||
ref_thread,
|
||||
// We need some reserved stack space to move values in and out of the ref stack.
|
||||
ref_stack_size: ffi::LUA_MINSTACK - REF_STACK_RESERVE,
|
||||
ref_stack_top: ffi::lua_gettop(ref_thread),
|
||||
ref_free: Vec::new(),
|
||||
wrapped_failure_pool: Vec::with_capacity(WRAPPED_FAILURE_POOL_DEFAULT_CAPACITY),
|
||||
wrapped_failure_top: 0,
|
||||
#[cfg(feature = "async")]
|
||||
thread_pool: Vec::new(),
|
||||
wrapped_failure_mt_ptr,
|
||||
#[cfg(feature = "async")]
|
||||
waker: NonNull::from(noop_waker_ref()),
|
||||
#[cfg(not(feature = "luau"))]
|
||||
hook_callback: None,
|
||||
#[cfg(not(feature = "luau"))]
|
||||
hook_triggers: Default::default(),
|
||||
#[cfg(any(feature = "lua55", feature = "lua54"))]
|
||||
warn_callback: None,
|
||||
#[cfg(feature = "luau")]
|
||||
interrupt_callback: None,
|
||||
thread_triggers: ThreadTriggers::default(),
|
||||
thread_event_callback: None,
|
||||
#[cfg(feature = "luau")]
|
||||
sandboxed: false,
|
||||
#[cfg(feature = "luau")]
|
||||
compiler: None,
|
||||
#[cfg(feature = "luau-jit")]
|
||||
enable_jit: true,
|
||||
#[cfg(feature = "luau")]
|
||||
running_gc: false,
|
||||
#[cfg(feature = "luau")]
|
||||
mem_categories: vec![std::ffi::CString::new("main").unwrap()],
|
||||
}));
|
||||
|
||||
// Store it in the registry
|
||||
mlua_expect!(Self::store(&extra, state), "Error while storing extra data");
|
||||
|
||||
extra
|
||||
}
|
||||
|
||||
pub(super) unsafe fn set_lua(&mut self, raw: &XRc<ReentrantMutex<RawLua>>) {
|
||||
self.lua.write(Lua {
|
||||
raw: XRc::clone(raw),
|
||||
collect_garbage: false,
|
||||
});
|
||||
self.weak.write(WeakLua(XRc::downgrade(raw)));
|
||||
}
|
||||
|
||||
pub(crate) unsafe fn get(state: *mut ffi::lua_State) -> *mut Self {
|
||||
#[cfg(feature = "luau")]
|
||||
if cfg!(not(feature = "module")) {
|
||||
// In the main app we can use `lua_callbacks` to access ExtraData
|
||||
return (*ffi::lua_callbacks(state)).userdata as *mut _;
|
||||
}
|
||||
|
||||
let extra_key = &EXTRA_REGISTRY_KEY as *const u8 as *const c_void;
|
||||
if ffi::lua_rawgetp(state, ffi::LUA_REGISTRYINDEX, extra_key) != ffi::LUA_TUSERDATA {
|
||||
// `ExtraData` can be null only when Lua state is foreign.
|
||||
// This case in used in `Lua::try_from_ptr()`.
|
||||
ffi::lua_pop(state, 1);
|
||||
return ptr::null_mut();
|
||||
}
|
||||
let extra_ptr = ffi::lua_touserdata(state, -1) as *mut Rc<UnsafeCell<ExtraData>>;
|
||||
ffi::lua_pop(state, 1);
|
||||
(*extra_ptr).get()
|
||||
}
|
||||
|
||||
unsafe fn store(extra: &XRc<UnsafeCell<Self>>, state: *mut ffi::lua_State) -> Result<()> {
|
||||
#[cfg(feature = "luau")]
|
||||
if cfg!(not(feature = "module")) {
|
||||
(*ffi::lua_callbacks(state)).userdata = extra.get() as *mut _;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
push_internal_userdata(state, XRc::clone(extra), true)?;
|
||||
protect_lua!(state, 1, 0, fn(state) {
|
||||
let extra_key = &EXTRA_REGISTRY_KEY as *const u8 as *const c_void;
|
||||
ffi::lua_rawsetp(state, ffi::LUA_REGISTRYINDEX, extra_key);
|
||||
})
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(super) unsafe fn lua(&self) -> &Lua {
|
||||
self.lua.assume_init_ref()
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) unsafe fn raw_lua(&self) -> &RawLua {
|
||||
&*self.lua.assume_init_ref().raw.data_ptr()
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(super) unsafe fn weak(&self) -> &WeakLua {
|
||||
self.weak.assume_init_ref()
|
||||
}
|
||||
|
||||
/// Pops a reference from top of the auxiliary stack and move it to a first free slot.
|
||||
pub(super) unsafe fn ref_stack_pop(&mut self) -> c_int {
|
||||
if let Some(free) = self.ref_free.pop() {
|
||||
ffi::lua_replace(self.ref_thread, free);
|
||||
return free;
|
||||
}
|
||||
|
||||
// Try to grow max stack size
|
||||
if self.ref_stack_top >= self.ref_stack_size {
|
||||
let mut inc = self.ref_stack_size; // Try to double stack size
|
||||
while inc > 0 && ffi::lua_checkstack(self.ref_thread, inc + REF_STACK_RESERVE) == 0 {
|
||||
inc /= 2;
|
||||
}
|
||||
if inc == 0 {
|
||||
// Pop item on top of the stack to avoid stack leaking and successfully run destructors
|
||||
// during unwinding.
|
||||
ffi::lua_pop(self.ref_thread, 1);
|
||||
let top = self.ref_stack_top;
|
||||
// It is a user error to create too many references to exhaust the Lua max stack size
|
||||
// for the ref thread.
|
||||
panic!("cannot create a Lua reference, out of auxiliary stack space (used {top} slots)");
|
||||
}
|
||||
self.ref_stack_size += inc;
|
||||
}
|
||||
self.ref_stack_top += 1;
|
||||
self.ref_stack_top
|
||||
}
|
||||
}
|
||||
+1663
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,152 @@
|
||||
use std::os::raw::c_int;
|
||||
use std::panic::{AssertUnwindSafe, catch_unwind};
|
||||
use std::ptr;
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::state::{ExtraData, RawLua};
|
||||
use crate::util::{self, WrappedFailure, get_internal_metatable};
|
||||
|
||||
struct StateGuard<'a>(&'a RawLua, *mut ffi::lua_State);
|
||||
|
||||
impl<'a> StateGuard<'a> {
|
||||
fn new(inner: &'a RawLua, mut state: *mut ffi::lua_State) -> Self {
|
||||
state = inner.state.replace(state);
|
||||
Self(inner, state)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for StateGuard<'_> {
|
||||
fn drop(&mut self) {
|
||||
self.0.state.set(self.1);
|
||||
}
|
||||
}
|
||||
|
||||
// An optimized version of `callback_error` that does not allocate `WrappedFailure` userdata
|
||||
// and instead reuses unused values from previous calls (or allocates new).
|
||||
pub(crate) unsafe fn callback_error_ext<F, R>(
|
||||
state: *mut ffi::lua_State,
|
||||
mut extra: *mut ExtraData,
|
||||
wrap_error: bool,
|
||||
f: F,
|
||||
) -> R
|
||||
where
|
||||
F: FnOnce(*mut ExtraData, c_int) -> Result<R>,
|
||||
{
|
||||
if extra.is_null() {
|
||||
extra = ExtraData::get(state);
|
||||
}
|
||||
|
||||
let nargs = ffi::lua_gettop(state);
|
||||
|
||||
enum PreallocatedFailure {
|
||||
New(*mut WrappedFailure),
|
||||
Reserved,
|
||||
}
|
||||
|
||||
impl PreallocatedFailure {
|
||||
unsafe fn reserve(state: *mut ffi::lua_State, extra: *mut ExtraData) -> Self {
|
||||
if (*extra).wrapped_failure_top > 0 {
|
||||
(*extra).wrapped_failure_top -= 1;
|
||||
return PreallocatedFailure::Reserved;
|
||||
}
|
||||
|
||||
// We need to check stack for Luau in case when callback is called from interrupt
|
||||
// See https://github.com/luau-lang/luau/issues/446 and mlua #142 and #153
|
||||
#[cfg(feature = "luau")]
|
||||
ffi::lua_rawcheckstack(state, 2);
|
||||
// Place it to the beginning of the stack
|
||||
let ud = WrappedFailure::new_userdata(state);
|
||||
ffi::lua_insert(state, 1);
|
||||
PreallocatedFailure::New(ud)
|
||||
}
|
||||
|
||||
#[cold]
|
||||
unsafe fn r#use(&self, state: *mut ffi::lua_State, extra: *mut ExtraData) -> *mut WrappedFailure {
|
||||
let ref_thread = (*extra).ref_thread;
|
||||
match *self {
|
||||
PreallocatedFailure::New(ud) => {
|
||||
ffi::lua_settop(state, 1);
|
||||
ud
|
||||
}
|
||||
PreallocatedFailure::Reserved => {
|
||||
let index = (*extra).wrapped_failure_pool.pop().unwrap();
|
||||
ffi::lua_settop(state, 0);
|
||||
#[cfg(feature = "luau")]
|
||||
ffi::lua_rawcheckstack(state, 2);
|
||||
ffi::lua_xpush(ref_thread, state, index);
|
||||
ffi::lua_pushnil(ref_thread);
|
||||
ffi::lua_replace(ref_thread, index);
|
||||
(*extra).ref_free.push(index);
|
||||
ffi::lua_touserdata(state, -1) as *mut WrappedFailure
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn release(self, state: *mut ffi::lua_State, extra: *mut ExtraData) {
|
||||
let ref_thread = (*extra).ref_thread;
|
||||
match self {
|
||||
PreallocatedFailure::New(_) => {
|
||||
ffi::lua_rotate(state, 1, -1);
|
||||
ffi::lua_xmove(state, ref_thread, 1);
|
||||
let index = (*extra).ref_stack_pop();
|
||||
(*extra).wrapped_failure_pool.push(index);
|
||||
(*extra).wrapped_failure_top += 1;
|
||||
}
|
||||
PreallocatedFailure::Reserved => (*extra).wrapped_failure_top += 1,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// We cannot shadow Rust errors with Lua ones, so we need to reserve pre-allocated memory
|
||||
// to store a wrapped failure (error or panic) *before* we proceed.
|
||||
let prealloc_failure = PreallocatedFailure::reserve(state, extra);
|
||||
|
||||
match catch_unwind(AssertUnwindSafe(|| {
|
||||
let rawlua = (*extra).raw_lua();
|
||||
let _guard = StateGuard::new(rawlua, state);
|
||||
f(extra, nargs)
|
||||
})) {
|
||||
Ok(Ok(r)) => {
|
||||
// Return unused `WrappedFailure` to the pool
|
||||
prealloc_failure.release(state, extra);
|
||||
r
|
||||
}
|
||||
Ok(Err(err)) => {
|
||||
let wrapped_error = prealloc_failure.r#use(state, extra);
|
||||
|
||||
if !wrap_error {
|
||||
ptr::write(wrapped_error, WrappedFailure::Error(err));
|
||||
get_internal_metatable::<WrappedFailure>(state);
|
||||
ffi::lua_setmetatable(state, -2);
|
||||
ffi::lua_error(state)
|
||||
}
|
||||
|
||||
// Build `CallbackError` with traceback
|
||||
let traceback = if ffi::lua_checkstack(state, ffi::LUA_TRACEBACK_STACK) != 0 {
|
||||
ffi::luaL_traceback(state, state, ptr::null(), 0);
|
||||
let traceback = util::to_string(state, -1);
|
||||
ffi::lua_pop(state, 1);
|
||||
traceback
|
||||
} else {
|
||||
"<not enough stack space for traceback>".to_string()
|
||||
};
|
||||
let cause = Arc::new(err);
|
||||
ptr::write(
|
||||
wrapped_error,
|
||||
WrappedFailure::Error(Error::CallbackError { traceback, cause }),
|
||||
);
|
||||
get_internal_metatable::<WrappedFailure>(state);
|
||||
ffi::lua_setmetatable(state, -2);
|
||||
|
||||
ffi::lua_error(state)
|
||||
}
|
||||
Err(p) => {
|
||||
let wrapped_panic = prealloc_failure.r#use(state, extra);
|
||||
ptr::write(wrapped_panic, WrappedFailure::Panic(Some(p)));
|
||||
get_internal_metatable::<WrappedFailure>(state);
|
||||
ffi::lua_setmetatable(state, -2);
|
||||
ffi::lua_error(state)
|
||||
}
|
||||
}
|
||||
}
|
||||
+42
-14
@@ -1,4 +1,4 @@
|
||||
use std::ops::{BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign};
|
||||
use std::ops::{BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Not};
|
||||
|
||||
/// Flags describing the set of lua standard libraries to load.
|
||||
#[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
|
||||
@@ -6,14 +6,23 @@ pub struct StdLib(u32);
|
||||
|
||||
impl StdLib {
|
||||
/// [`coroutine`](https://www.lua.org/manual/5.4/manual.html#6.2) library
|
||||
///
|
||||
/// Requires `feature = "lua54/lua53/lua52/luau"`
|
||||
#[cfg(any(
|
||||
feature = "lua55",
|
||||
feature = "lua54",
|
||||
feature = "lua53",
|
||||
feature = "lua52",
|
||||
feature = "luau"
|
||||
))]
|
||||
#[cfg_attr(
|
||||
docsrs,
|
||||
doc(cfg(any(
|
||||
feature = "lua55",
|
||||
feature = "lua54",
|
||||
feature = "lua53",
|
||||
feature = "lua52",
|
||||
feature = "luau"
|
||||
)))
|
||||
)]
|
||||
pub const COROUTINE: StdLib = StdLib(1);
|
||||
|
||||
/// [`table`](https://www.lua.org/manual/5.4/manual.html#6.6) library
|
||||
@@ -31,38 +40,50 @@ impl StdLib {
|
||||
pub const STRING: StdLib = StdLib(1 << 4);
|
||||
|
||||
/// [`utf8`](https://www.lua.org/manual/5.4/manual.html#6.5) library
|
||||
///
|
||||
/// Requires `feature = "lua54/lua53/luau"`
|
||||
#[cfg(any(feature = "lua54", feature = "lua53", feature = "luau"))]
|
||||
#[cfg(any(feature = "lua55", feature = "lua54", feature = "lua53", feature = "luau"))]
|
||||
#[cfg_attr(
|
||||
docsrs,
|
||||
doc(cfg(any(feature = "lua55", feature = "lua54", feature = "lua53", feature = "luau")))
|
||||
)]
|
||||
pub const UTF8: StdLib = StdLib(1 << 5);
|
||||
|
||||
/// [`bit`](https://www.lua.org/manual/5.2/manual.html#6.7) library
|
||||
///
|
||||
/// Requires `feature = "lua52/luajit/luau"`
|
||||
#[cfg(any(feature = "lua52", feature = "luajit", feature = "luau", doc))]
|
||||
#[cfg_attr(
|
||||
docsrs,
|
||||
doc(cfg(any(feature = "lua52", feature = "luajit", feature = "luau")))
|
||||
)]
|
||||
pub const BIT: StdLib = StdLib(1 << 6);
|
||||
|
||||
/// [`math`](https://www.lua.org/manual/5.4/manual.html#6.7) library
|
||||
pub const MATH: StdLib = StdLib(1 << 7);
|
||||
|
||||
/// [`package`](https://www.lua.org/manual/5.4/manual.html#6.3) library
|
||||
#[cfg(not(feature = "luau"))]
|
||||
#[cfg_attr(docsrs, doc(cfg(not(feature = "luau"))))]
|
||||
pub const PACKAGE: StdLib = StdLib(1 << 8);
|
||||
|
||||
/// [`buffer`](https://luau-lang.org/library#buffer-library) library
|
||||
/// [`buffer`](https://luau.org/library#buffer-library) library
|
||||
#[cfg(any(feature = "luau", doc))]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "luau")))]
|
||||
pub const BUFFER: StdLib = StdLib(1 << 9);
|
||||
|
||||
/// [`vector`](https://luau.org/library#vector-library) library
|
||||
#[cfg(any(feature = "luau", doc))]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "luau")))]
|
||||
pub const VECTOR: StdLib = StdLib(1 << 10);
|
||||
|
||||
/// [`integer`](https://luau.org/library#integer-library) library
|
||||
#[cfg(any(feature = "luau", doc))]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "luau")))]
|
||||
pub const INTEGER: StdLib = StdLib(1 << 11);
|
||||
|
||||
/// [`jit`](http://luajit.org/ext_jit.html) library
|
||||
///
|
||||
/// Requires `feature = "luajit"`
|
||||
#[cfg(any(feature = "luajit", doc))]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "luajit")))]
|
||||
pub const JIT: StdLib = StdLib(1 << 9);
|
||||
pub const JIT: StdLib = StdLib(1 << 12);
|
||||
|
||||
/// (**unsafe**) [`ffi`](http://luajit.org/ext_ffi.html) library
|
||||
///
|
||||
/// Requires `feature = "luajit"`
|
||||
#[cfg(any(feature = "luajit", doc))]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "luajit")))]
|
||||
pub const FFI: StdLib = StdLib(1 << 30);
|
||||
@@ -123,3 +144,10 @@ impl BitXorAssign for StdLib {
|
||||
*self = StdLib(self.0 ^ rhs.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl Not for StdLib {
|
||||
type Output = Self;
|
||||
fn not(self) -> Self::Output {
|
||||
StdLib(!self.0)
|
||||
}
|
||||
}
|
||||
|
||||
+305
-137
@@ -1,78 +1,67 @@
|
||||
use std::borrow::{Borrow, Cow};
|
||||
use std::hash::{Hash, Hasher};
|
||||
use std::os::raw::c_void;
|
||||
use std::string::String as StdString;
|
||||
use std::{fmt, slice, str};
|
||||
//! Lua string handling.
|
||||
//!
|
||||
//! This module provides types for working with Lua strings from Rust.
|
||||
|
||||
#[cfg(feature = "serialize")]
|
||||
use std::borrow::Borrow;
|
||||
use std::hash::{Hash, Hasher};
|
||||
use std::ops::Deref;
|
||||
use std::os::raw::{c_int, c_void};
|
||||
use std::{cmp, fmt, mem, slice, str};
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::state::Lua;
|
||||
use crate::traits::IntoLua;
|
||||
use crate::types::{LuaType, ValueRef};
|
||||
use crate::value::Value;
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
use {
|
||||
serde::ser::{Serialize, Serializer},
|
||||
std::result::Result as StdResult,
|
||||
};
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::types::LuaRef;
|
||||
|
||||
/// Handle to an internal Lua string.
|
||||
///
|
||||
/// Unlike Rust strings, Lua strings may not be valid UTF-8.
|
||||
#[derive(Clone)]
|
||||
pub struct String<'lua>(pub(crate) LuaRef<'lua>);
|
||||
#[derive(Clone, PartialEq)]
|
||||
pub struct LuaString(pub(crate) ValueRef);
|
||||
|
||||
/// Owned handle to an internal Lua string.
|
||||
///
|
||||
/// The owned handle holds a *strong* reference to the current Lua instance.
|
||||
/// Be warned, if you place it into a Lua type (eg. [`UserData`] or a Rust callback), it is *very easy*
|
||||
/// to accidentally cause reference cycles that would prevent destroying Lua instance.
|
||||
///
|
||||
/// [`UserData`]: crate::UserData
|
||||
#[cfg(feature = "unstable")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "unstable")))]
|
||||
#[derive(Clone)]
|
||||
pub struct OwnedString(pub(crate) crate::types::LuaOwnedRef);
|
||||
|
||||
#[cfg(feature = "unstable")]
|
||||
impl OwnedString {
|
||||
/// Get borrowed handle to the underlying Lua string.
|
||||
#[cfg_attr(feature = "send", allow(unused))]
|
||||
pub const fn to_ref(&self) -> String {
|
||||
String(self.0.to_ref())
|
||||
}
|
||||
}
|
||||
|
||||
impl<'lua> String<'lua> {
|
||||
/// Get a `&str` slice if the Lua string is valid UTF-8.
|
||||
impl LuaString {
|
||||
/// Get a [`BorrowedStr`] if the Lua string is valid UTF-8.
|
||||
///
|
||||
/// The returned `BorrowedStr` holds a strong reference to the Lua state to guarantee the
|
||||
/// validity of the underlying data.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// # use mlua::{Lua, Result, String};
|
||||
/// # use mlua::{Lua, LuaString, Result};
|
||||
/// # fn main() -> Result<()> {
|
||||
/// # let lua = Lua::new();
|
||||
/// let globals = lua.globals();
|
||||
///
|
||||
/// let version: String = globals.get("_VERSION")?;
|
||||
/// let version: LuaString = globals.get("_VERSION")?;
|
||||
/// assert!(version.to_str()?.contains("Lua"));
|
||||
///
|
||||
/// let non_utf8: String = lua.load(r#" "test\255" "#).eval()?;
|
||||
/// let non_utf8: LuaString = lua.load(r#" "test\255" "#).eval()?;
|
||||
/// assert!(non_utf8.to_str().is_err());
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
#[inline]
|
||||
pub fn to_str(&self) -> Result<&str> {
|
||||
str::from_utf8(self.as_bytes()).map_err(|e| Error::FromLuaConversionError {
|
||||
from: "string",
|
||||
to: "&str",
|
||||
message: Some(e.to_string()),
|
||||
})
|
||||
pub fn to_str(&self) -> Result<BorrowedStr> {
|
||||
BorrowedStr::try_from(self)
|
||||
}
|
||||
|
||||
/// Converts this string to a [`Cow<str>`].
|
||||
/// Converts this Lua string to a [`String`].
|
||||
///
|
||||
/// Any non-Unicode sequences are replaced with [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD].
|
||||
///
|
||||
/// This method returns [`String`] instead of [`Cow<'_, str>`] because lifetime cannot be
|
||||
/// bound to a weak Lua object.
|
||||
///
|
||||
/// [U+FFFD]: std::char::REPLACEMENT_CHARACTER
|
||||
/// [`Cow<'_, str>`]: std::borrow::Cow
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
@@ -87,120 +76,108 @@ impl<'lua> String<'lua> {
|
||||
/// # }
|
||||
/// ```
|
||||
#[inline]
|
||||
pub fn to_string_lossy(&self) -> Cow<'_, str> {
|
||||
StdString::from_utf8_lossy(self.as_bytes())
|
||||
pub fn to_string_lossy(&self) -> String {
|
||||
String::from_utf8_lossy(&self.as_bytes()).into_owned()
|
||||
}
|
||||
|
||||
/// Returns an object that implements [`Display`] for safely printing a [`LuaString`] that may
|
||||
/// contain non-Unicode data.
|
||||
///
|
||||
/// This may perform lossy conversion.
|
||||
///
|
||||
/// [`Display`]: fmt::Display
|
||||
pub fn display(&self) -> impl fmt::Display + '_ {
|
||||
Display(self)
|
||||
}
|
||||
|
||||
/// Get the bytes that make up this string.
|
||||
///
|
||||
/// The returned slice will not contain the terminating nul byte, but will contain any nul
|
||||
/// bytes embedded into the Lua string.
|
||||
/// The returned `BorrowedStr` holds a strong reference to the Lua state to guarantee the
|
||||
/// validity of the underlying data. The data will not contain the terminating null byte, but
|
||||
/// will contain any null bytes embedded into the Lua string.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// # use mlua::{Lua, Result, String};
|
||||
/// # use mlua::{Lua, LuaString, Result};
|
||||
/// # fn main() -> Result<()> {
|
||||
/// # let lua = Lua::new();
|
||||
/// let non_utf8: String = lua.load(r#" "test\255" "#).eval()?;
|
||||
/// let non_utf8: LuaString = lua.load(r#" "test\255" "#).eval()?;
|
||||
/// assert!(non_utf8.to_str().is_err()); // oh no :(
|
||||
/// assert_eq!(non_utf8.as_bytes(), &b"test\xff"[..]);
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
#[inline]
|
||||
pub fn as_bytes(&self) -> &[u8] {
|
||||
let nulled = self.as_bytes_with_nul();
|
||||
&nulled[..nulled.len() - 1]
|
||||
pub fn as_bytes(&self) -> BorrowedBytes {
|
||||
BorrowedBytes::from(self)
|
||||
}
|
||||
|
||||
/// Get the bytes that make up this string, including the trailing nul byte.
|
||||
pub fn as_bytes_with_nul(&self) -> &[u8] {
|
||||
let ref_thread = self.0.lua.ref_thread();
|
||||
unsafe {
|
||||
/// Get the bytes that make up this string, including the trailing null byte.
|
||||
pub fn as_bytes_with_nul(&self) -> BorrowedBytes {
|
||||
let BorrowedBytes { buf, vref, _lua } = BorrowedBytes::from(self);
|
||||
// Include the trailing null byte (it's always present but excluded by default)
|
||||
let buf = unsafe { slice::from_raw_parts((*buf).as_ptr(), (*buf).len() + 1) };
|
||||
BorrowedBytes { buf, vref, _lua }
|
||||
}
|
||||
|
||||
// Does not return the terminating null byte
|
||||
unsafe fn to_slice(&self) -> (&[u8], Lua) {
|
||||
let lua = self.0.lua.upgrade();
|
||||
let slice = {
|
||||
let rawlua = lua.lock();
|
||||
let ref_thread = rawlua.ref_thread();
|
||||
|
||||
mlua_debug_assert!(
|
||||
ffi::lua_type(ref_thread, self.0.index) == ffi::LUA_TSTRING,
|
||||
"string ref is not string type"
|
||||
);
|
||||
|
||||
let mut size = 0;
|
||||
// This will not trigger a 'm' error, because the reference is guaranteed to be of
|
||||
// string type
|
||||
let mut size = 0;
|
||||
let data = ffi::lua_tolstring(ref_thread, self.0.index, &mut size);
|
||||
|
||||
slice::from_raw_parts(data as *const u8, size + 1)
|
||||
}
|
||||
slice::from_raw_parts(data as *const u8, size)
|
||||
};
|
||||
(slice, lua)
|
||||
}
|
||||
|
||||
/// Converts this string to a generic C pointer.
|
||||
/// Converts this Lua string to a generic C pointer.
|
||||
///
|
||||
/// There is no way to convert the pointer back to its original value.
|
||||
///
|
||||
/// Typically this function is used only for hashing and debug information.
|
||||
#[inline]
|
||||
pub fn to_pointer(&self) -> *const c_void {
|
||||
self.0.to_pointer()
|
||||
}
|
||||
|
||||
/// Convert this handle to owned version.
|
||||
#[cfg(all(feature = "unstable", any(not(feature = "send"), doc)))]
|
||||
#[cfg_attr(docsrs, doc(cfg(all(feature = "unstable", not(feature = "send")))))]
|
||||
#[inline]
|
||||
pub fn into_owned(self) -> OwnedString {
|
||||
OwnedString(self.0.into_owned())
|
||||
// In Lua < 5.4 (excluding Luau), string pointers are NULL
|
||||
// Use alternative approach
|
||||
let lua = self.0.lua.lock();
|
||||
unsafe { ffi::lua_tostring(lua.ref_thread(), self.0.index) as *const c_void }
|
||||
}
|
||||
}
|
||||
|
||||
impl<'lua> fmt::Debug for String<'lua> {
|
||||
impl fmt::Debug for LuaString {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
let bytes = self.as_bytes();
|
||||
// Check if the string is valid utf8
|
||||
if let Ok(s) = str::from_utf8(bytes) {
|
||||
if let Ok(s) = str::from_utf8(&bytes) {
|
||||
return s.fmt(f);
|
||||
}
|
||||
|
||||
// Format as bytes
|
||||
write!(f, "b\"")?;
|
||||
for &b in bytes {
|
||||
// https://doc.rust-lang.org/reference/tokens.html#byte-escapes
|
||||
match b {
|
||||
b'\n' => write!(f, "\\n")?,
|
||||
b'\r' => write!(f, "\\r")?,
|
||||
b'\t' => write!(f, "\\t")?,
|
||||
b'\\' | b'"' => write!(f, "\\{}", b as char)?,
|
||||
b'\0' => write!(f, "\\0")?,
|
||||
// ASCII printable
|
||||
0x20..=0x7e => write!(f, "{}", b as char)?,
|
||||
_ => write!(f, "\\x{b:02x}")?,
|
||||
}
|
||||
}
|
||||
write!(f, "\"")?;
|
||||
|
||||
Ok(())
|
||||
write!(f, "b")?;
|
||||
<bstr::BStr as fmt::Debug>::fmt(bstr::BStr::new(&bytes), f)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'lua> AsRef<[u8]> for String<'lua> {
|
||||
fn as_ref(&self) -> &[u8] {
|
||||
self.as_bytes()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'lua> Borrow<[u8]> for String<'lua> {
|
||||
fn borrow(&self) -> &[u8] {
|
||||
self.as_bytes()
|
||||
}
|
||||
}
|
||||
|
||||
// Lua strings are basically &[u8] slices, so implement PartialEq for anything resembling that.
|
||||
// Lua strings are basically `&[u8]` slices, so implement `PartialEq` for anything resembling that.
|
||||
//
|
||||
// This makes our `String` comparable with `Vec<u8>`, `[u8]`, `&str`, `String` and `mlua::String`
|
||||
// itself.
|
||||
// This makes our `LuaString` comparable with `Vec<u8>`, `[u8]`, `&str` and `String`.
|
||||
//
|
||||
// The only downside is that this disallows a comparison with `Cow<str>`, as that only implements
|
||||
// `AsRef<str>`, which collides with this impl. Requiring `AsRef<str>` would fix that, but limit us
|
||||
// in other ways.
|
||||
impl<'lua, T> PartialEq<T> for String<'lua>
|
||||
impl<T> PartialEq<T> for LuaString
|
||||
where
|
||||
T: AsRef<[u8]> + ?Sized,
|
||||
{
|
||||
@@ -209,61 +186,252 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<'lua> Eq for String<'lua> {}
|
||||
impl Eq for LuaString {}
|
||||
|
||||
impl<'lua> Hash for String<'lua> {
|
||||
impl<T> PartialOrd<T> for LuaString
|
||||
where
|
||||
T: AsRef<[u8]> + ?Sized,
|
||||
{
|
||||
fn partial_cmp(&self, other: &T) -> Option<cmp::Ordering> {
|
||||
<[u8]>::partial_cmp(&self.as_bytes(), other.as_ref())
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialOrd for LuaString {
|
||||
fn partial_cmp(&self, other: &LuaString) -> Option<cmp::Ordering> {
|
||||
Some(self.cmp(other))
|
||||
}
|
||||
}
|
||||
|
||||
impl Ord for LuaString {
|
||||
fn cmp(&self, other: &LuaString) -> cmp::Ordering {
|
||||
self.as_bytes().cmp(&other.as_bytes())
|
||||
}
|
||||
}
|
||||
|
||||
impl Hash for LuaString {
|
||||
fn hash<H: Hasher>(&self, state: &mut H) {
|
||||
self.as_bytes().hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "serialize")]
|
||||
impl<'lua> Serialize for String<'lua> {
|
||||
#[cfg(feature = "serde")]
|
||||
impl Serialize for LuaString {
|
||||
fn serialize<S>(&self, serializer: S) -> StdResult<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
match self.to_str() {
|
||||
Ok(s) => serializer.serialize_str(s),
|
||||
Err(_) => serializer.serialize_bytes(self.as_bytes()),
|
||||
Ok(s) => serializer.serialize_str(&s),
|
||||
Err(_) => serializer.serialize_bytes(&self.as_bytes()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Additional shortcuts
|
||||
#[cfg(feature = "unstable")]
|
||||
impl OwnedString {
|
||||
/// Get a `&str` slice if the Lua string is valid UTF-8.
|
||||
///
|
||||
/// This is a shortcut for [`String::to_str()`].
|
||||
#[inline]
|
||||
pub fn to_str(&self) -> Result<&str> {
|
||||
let s = self.to_ref();
|
||||
// Reattach lifetime to &self
|
||||
unsafe { std::mem::transmute(s.to_str()) }
|
||||
}
|
||||
struct Display<'a>(&'a LuaString);
|
||||
|
||||
/// Get the bytes that make up this string.
|
||||
///
|
||||
/// This is a shortcut for [`String::as_bytes()`].
|
||||
#[inline]
|
||||
pub fn as_bytes(&self) -> &[u8] {
|
||||
let s = self.to_ref();
|
||||
// Reattach lifetime to &self
|
||||
unsafe { std::mem::transmute(s.as_bytes()) }
|
||||
impl fmt::Display for Display<'_> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
let bytes = self.0.as_bytes();
|
||||
<bstr::BStr as fmt::Display>::fmt(bstr::BStr::new(&bytes), f)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "unstable")]
|
||||
impl fmt::Debug for OwnedString {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
self.to_ref().fmt(f)
|
||||
/// A borrowed string (`&str`) that holds a strong reference to the Lua state.
|
||||
pub struct BorrowedStr {
|
||||
// `buf` points to a readonly memory managed by Lua
|
||||
pub(crate) buf: &'static str,
|
||||
pub(crate) vref: ValueRef,
|
||||
pub(crate) _lua: Lua,
|
||||
}
|
||||
|
||||
impl Deref for BorrowedStr {
|
||||
type Target = str;
|
||||
|
||||
#[inline(always)]
|
||||
fn deref(&self) -> &str {
|
||||
self.buf
|
||||
}
|
||||
}
|
||||
|
||||
impl Borrow<str> for BorrowedStr {
|
||||
#[inline(always)]
|
||||
fn borrow(&self) -> &str {
|
||||
self.buf
|
||||
}
|
||||
}
|
||||
|
||||
impl AsRef<str> for BorrowedStr {
|
||||
#[inline(always)]
|
||||
fn as_ref(&self) -> &str {
|
||||
self.buf
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for BorrowedStr {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
self.buf.fmt(f)
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for BorrowedStr {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
self.buf.fmt(f)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> PartialEq<T> for BorrowedStr
|
||||
where
|
||||
T: AsRef<str>,
|
||||
{
|
||||
fn eq(&self, other: &T) -> bool {
|
||||
self.buf == other.as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for BorrowedStr {}
|
||||
|
||||
impl<T> PartialOrd<T> for BorrowedStr
|
||||
where
|
||||
T: AsRef<str>,
|
||||
{
|
||||
fn partial_cmp(&self, other: &T) -> Option<cmp::Ordering> {
|
||||
self.buf.partial_cmp(other.as_ref())
|
||||
}
|
||||
}
|
||||
|
||||
impl Ord for BorrowedStr {
|
||||
fn cmp(&self, other: &Self) -> cmp::Ordering {
|
||||
self.buf.cmp(other.buf)
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<&LuaString> for BorrowedStr {
|
||||
type Error = Error;
|
||||
|
||||
#[inline]
|
||||
fn try_from(value: &LuaString) -> Result<Self> {
|
||||
let BorrowedBytes { buf, vref, _lua } = BorrowedBytes::from(value);
|
||||
let buf =
|
||||
str::from_utf8(buf).map_err(|e| Error::from_lua_conversion("string", "&str", e.to_string()))?;
|
||||
Ok(Self { buf, vref, _lua })
|
||||
}
|
||||
}
|
||||
|
||||
/// A borrowed byte slice (`&[u8]`) that holds a strong reference to the Lua state.
|
||||
pub struct BorrowedBytes {
|
||||
// `buf` points to a readonly memory managed by Lua
|
||||
pub(crate) buf: &'static [u8],
|
||||
pub(crate) vref: ValueRef,
|
||||
pub(crate) _lua: Lua,
|
||||
}
|
||||
|
||||
impl Deref for BorrowedBytes {
|
||||
type Target = [u8];
|
||||
|
||||
#[inline(always)]
|
||||
fn deref(&self) -> &[u8] {
|
||||
self.buf
|
||||
}
|
||||
}
|
||||
|
||||
impl Borrow<[u8]> for BorrowedBytes {
|
||||
#[inline(always)]
|
||||
fn borrow(&self) -> &[u8] {
|
||||
self.buf
|
||||
}
|
||||
}
|
||||
|
||||
impl AsRef<[u8]> for BorrowedBytes {
|
||||
#[inline(always)]
|
||||
fn as_ref(&self) -> &[u8] {
|
||||
self.buf
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for BorrowedBytes {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
self.buf.fmt(f)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> PartialEq<T> for BorrowedBytes
|
||||
where
|
||||
T: AsRef<[u8]>,
|
||||
{
|
||||
fn eq(&self, other: &T) -> bool {
|
||||
self.buf == other.as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for BorrowedBytes {}
|
||||
|
||||
impl<T> PartialOrd<T> for BorrowedBytes
|
||||
where
|
||||
T: AsRef<[u8]>,
|
||||
{
|
||||
fn partial_cmp(&self, other: &T) -> Option<cmp::Ordering> {
|
||||
self.buf.partial_cmp(other.as_ref())
|
||||
}
|
||||
}
|
||||
|
||||
impl Ord for BorrowedBytes {
|
||||
fn cmp(&self, other: &Self) -> cmp::Ordering {
|
||||
self.buf.cmp(other.buf)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> IntoIterator for &'a BorrowedBytes {
|
||||
type Item = &'a u8;
|
||||
type IntoIter = slice::Iter<'a, u8>;
|
||||
|
||||
fn into_iter(self) -> Self::IntoIter {
|
||||
self.iter()
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&LuaString> for BorrowedBytes {
|
||||
#[inline]
|
||||
fn from(value: &LuaString) -> Self {
|
||||
let (buf, _lua) = unsafe { value.to_slice() };
|
||||
let vref = value.0.clone();
|
||||
// SAFETY: The `buf` is valid for the lifetime of the Lua state and occupied slot index
|
||||
let buf = unsafe { mem::transmute::<&[u8], &'static [u8]>(buf) };
|
||||
Self { buf, vref, _lua }
|
||||
}
|
||||
}
|
||||
|
||||
struct WrappedString<T: AsRef<[u8]>>(T);
|
||||
|
||||
impl LuaString {
|
||||
/// Wraps bytes, returning an opaque type that implements [`IntoLua`] trait.
|
||||
///
|
||||
/// This function uses [`Lua::create_string`] under the hood.
|
||||
pub fn wrap(data: impl AsRef<[u8]>) -> impl IntoLua {
|
||||
WrappedString(data)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: AsRef<[u8]>> IntoLua for WrappedString<T> {
|
||||
fn into_lua(self, lua: &Lua) -> Result<Value> {
|
||||
lua.create_string(self.0).map(Value::String)
|
||||
}
|
||||
}
|
||||
|
||||
impl LuaType for LuaString {
|
||||
const TYPE_ID: c_int = ffi::LUA_TSTRING;
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod assertions {
|
||||
use super::*;
|
||||
|
||||
static_assertions::assert_not_impl_any!(String: Send);
|
||||
#[cfg(not(feature = "send"))]
|
||||
static_assertions::assert_not_impl_any!(LuaString: Send);
|
||||
#[cfg(feature = "send")]
|
||||
static_assertions::assert_impl_all!(LuaString: Send, Sync);
|
||||
#[cfg(feature = "send")]
|
||||
static_assertions::assert_impl_all!(BorrowedBytes: Send, Sync);
|
||||
#[cfg(feature = "send")]
|
||||
static_assertions::assert_impl_all!(BorrowedStr: Send, Sync);
|
||||
}
|
||||
|
||||
+562
-434
File diff suppressed because it is too large
Load Diff
+538
-253
File diff suppressed because it is too large
Load Diff
+259
@@ -0,0 +1,259 @@
|
||||
//! Core conversion and extension traits.
|
||||
//!
|
||||
//! This module provides the fundamental traits for converting values between Rust and Lua,
|
||||
//! and for defining native Lua callable functions.
|
||||
|
||||
use std::os::raw::c_int;
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::multi::MultiValue;
|
||||
use crate::private::Sealed;
|
||||
use crate::state::{Lua, RawLua, WeakLua};
|
||||
use crate::util::{check_stack, parse_lookup_path, short_type_name};
|
||||
use crate::value::Value;
|
||||
|
||||
#[cfg(feature = "async")]
|
||||
use crate::function::AsyncCallFuture;
|
||||
|
||||
/// Trait for types convertible to [`Value`].
|
||||
pub trait IntoLua: Sized {
|
||||
/// Performs the conversion.
|
||||
fn into_lua(self, lua: &Lua) -> Result<Value>;
|
||||
|
||||
/// Pushes the value into the Lua stack.
|
||||
///
|
||||
/// # Safety
|
||||
/// This method does not check Lua stack space.
|
||||
#[doc(hidden)]
|
||||
#[inline]
|
||||
unsafe fn push_into_stack(self, lua: &RawLua) -> Result<()> {
|
||||
lua.push_value(&self.into_lua(lua.lua())?)
|
||||
}
|
||||
}
|
||||
|
||||
/// Trait for types convertible from [`Value`].
|
||||
pub trait FromLua: Sized {
|
||||
/// Performs the conversion.
|
||||
fn from_lua(value: Value, lua: &Lua) -> Result<Self>;
|
||||
|
||||
/// Performs the conversion for an argument (eg. function argument).
|
||||
///
|
||||
/// `i` is the argument index (position),
|
||||
/// `to` is a function name that received the argument.
|
||||
#[doc(hidden)]
|
||||
#[inline]
|
||||
fn from_lua_arg(arg: Value, i: usize, to: Option<&str>, lua: &Lua) -> Result<Self> {
|
||||
Self::from_lua(arg, lua).map_err(|err| Error::BadArgument {
|
||||
to: to.map(|s| s.to_string()),
|
||||
pos: i,
|
||||
name: None,
|
||||
cause: Arc::new(err),
|
||||
})
|
||||
}
|
||||
|
||||
/// Performs the conversion for a value in the Lua stack at index `idx`.
|
||||
#[doc(hidden)]
|
||||
#[inline]
|
||||
unsafe fn from_stack(idx: c_int, lua: &RawLua) -> Result<Self> {
|
||||
Self::from_lua(lua.stack_value(idx, None), lua.lua())
|
||||
}
|
||||
|
||||
/// Same as `from_lua_arg` but for a value in the Lua stack at index `idx`.
|
||||
#[doc(hidden)]
|
||||
#[inline]
|
||||
unsafe fn from_stack_arg(idx: c_int, i: usize, to: Option<&str>, lua: &RawLua) -> Result<Self> {
|
||||
Self::from_stack(idx, lua).map_err(|err| Error::BadArgument {
|
||||
to: to.map(|s| s.to_string()),
|
||||
pos: i,
|
||||
name: None,
|
||||
cause: Arc::new(err),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Trait for types convertible to any number of Lua values.
|
||||
///
|
||||
/// This is a generalization of [`IntoLua`], allowing any number of resulting Lua values instead of
|
||||
/// just one. Any type that implements [`IntoLua`] will automatically implement this trait.
|
||||
pub trait IntoLuaMulti: Sized {
|
||||
/// Performs the conversion.
|
||||
fn into_lua_multi(self, lua: &Lua) -> Result<MultiValue>;
|
||||
|
||||
/// Pushes the values into the Lua stack.
|
||||
///
|
||||
/// Returns number of pushed values.
|
||||
#[doc(hidden)]
|
||||
#[inline]
|
||||
unsafe fn push_into_stack_multi(self, lua: &RawLua) -> Result<c_int> {
|
||||
let values = self.into_lua_multi(lua.lua())?;
|
||||
let len: c_int = values.len().try_into().unwrap();
|
||||
unsafe {
|
||||
check_stack(lua.state(), len + 1)?;
|
||||
for val in &values {
|
||||
lua.push_value(val)?;
|
||||
}
|
||||
}
|
||||
Ok(len)
|
||||
}
|
||||
}
|
||||
|
||||
/// Trait for types that can be created from an arbitrary number of Lua values.
|
||||
///
|
||||
/// This is a generalization of [`FromLua`], allowing an arbitrary number of Lua values to
|
||||
/// participate in the conversion. Any type that implements [`FromLua`] will automatically
|
||||
/// implement this trait.
|
||||
pub trait FromLuaMulti: Sized {
|
||||
/// Performs the conversion.
|
||||
///
|
||||
/// In case `values` contains more values than needed to perform the conversion, the excess
|
||||
/// values should be ignored. This reflects the semantics of Lua when calling a function or
|
||||
/// assigning values. Similarly, if not enough values are given, conversions should assume that
|
||||
/// any missing values are nil.
|
||||
fn from_lua_multi(values: MultiValue, lua: &Lua) -> Result<Self>;
|
||||
|
||||
/// Performs the conversion for a list of arguments.
|
||||
///
|
||||
/// `i` is an index (position) of the first argument,
|
||||
/// `to` is a function name that received the arguments.
|
||||
#[doc(hidden)]
|
||||
#[inline]
|
||||
fn from_lua_args(args: MultiValue, i: usize, to: Option<&str>, lua: &Lua) -> Result<Self> {
|
||||
let _ = (i, to);
|
||||
Self::from_lua_multi(args, lua)
|
||||
}
|
||||
|
||||
/// Performs the conversion for a number of values in the Lua stack.
|
||||
#[doc(hidden)]
|
||||
#[inline]
|
||||
unsafe fn from_stack_multi(nvals: c_int, lua: &RawLua) -> Result<Self> {
|
||||
let mut values = MultiValue::with_capacity(nvals as usize);
|
||||
for idx in 0..nvals {
|
||||
values.push_back(lua.stack_value(-nvals + idx, None));
|
||||
}
|
||||
Self::from_lua_multi(values, lua.lua())
|
||||
}
|
||||
|
||||
/// Same as `from_lua_args` but for a number of values in the Lua stack.
|
||||
#[doc(hidden)]
|
||||
#[inline]
|
||||
unsafe fn from_stack_args(nargs: c_int, i: usize, to: Option<&str>, lua: &RawLua) -> Result<Self> {
|
||||
let _ = (i, to);
|
||||
Self::from_stack_multi(nargs, lua)
|
||||
}
|
||||
}
|
||||
|
||||
/// A trait for types that can be used as Lua objects (usually table and userdata).
|
||||
pub trait ObjectLike: Sealed {
|
||||
/// Gets the value associated to `key` from the object, assuming it has `__index` metamethod.
|
||||
fn get<V: FromLua>(&self, key: impl IntoLua) -> Result<V>;
|
||||
|
||||
/// Sets the value associated to `key` in the object, assuming it has `__newindex` metamethod.
|
||||
fn set(&self, key: impl IntoLua, value: impl IntoLua) -> Result<()>;
|
||||
|
||||
/// Calls the object as a function assuming it has `__call` metamethod.
|
||||
///
|
||||
/// The metamethod is called with the object as its first argument, followed by the passed
|
||||
/// arguments.
|
||||
fn call<R>(&self, args: impl IntoLuaMulti) -> Result<R>
|
||||
where
|
||||
R: FromLuaMulti;
|
||||
|
||||
/// Asynchronously calls the object as a function assuming it has `__call` metamethod.
|
||||
///
|
||||
/// The metamethod is called with the object as its first argument, followed by the passed
|
||||
/// arguments.
|
||||
#[cfg(feature = "async")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
|
||||
fn call_async<R>(&self, args: impl IntoLuaMulti) -> AsyncCallFuture<R>
|
||||
where
|
||||
R: FromLuaMulti;
|
||||
|
||||
/// Gets the function associated to key `name` from the object and calls it,
|
||||
/// passing the object itself along with `args` as function arguments.
|
||||
fn call_method<R>(&self, name: &str, args: impl IntoLuaMulti) -> Result<R>
|
||||
where
|
||||
R: FromLuaMulti;
|
||||
|
||||
/// Gets the function associated to key `name` from the object and asynchronously calls it,
|
||||
/// passing the object itself along with `args` as function arguments.
|
||||
///
|
||||
/// This might invoke the `__index` metamethod.
|
||||
#[cfg(feature = "async")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
|
||||
fn call_async_method<R>(&self, name: &str, args: impl IntoLuaMulti) -> AsyncCallFuture<R>
|
||||
where
|
||||
R: FromLuaMulti;
|
||||
|
||||
/// Gets the function associated to key `name` from the object and calls it,
|
||||
/// passing `args` as function arguments.
|
||||
///
|
||||
/// This might invoke the `__index` metamethod.
|
||||
fn call_function<R>(&self, name: &str, args: impl IntoLuaMulti) -> Result<R>
|
||||
where
|
||||
R: FromLuaMulti;
|
||||
|
||||
/// Gets the function associated to key `name` from the object and asynchronously calls it,
|
||||
/// passing `args` as function arguments.
|
||||
///
|
||||
/// This might invoke the `__index` metamethod.
|
||||
#[cfg(feature = "async")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
|
||||
fn call_async_function<R>(&self, name: &str, args: impl IntoLuaMulti) -> AsyncCallFuture<R>
|
||||
where
|
||||
R: FromLuaMulti;
|
||||
|
||||
/// Look up a value by a path of keys.
|
||||
///
|
||||
/// The syntax is similar to accessing nested tables in Lua, with additional support for
|
||||
/// `?` operator to perform safe navigation.
|
||||
///
|
||||
/// For example, the path `a[1].c` is equivalent to `table.a[1].c` in Lua.
|
||||
/// With `?` operator, `a[1]?.c` is equivalent to `table.a[1] and table.a[1].c or nil` in Lua.
|
||||
///
|
||||
/// Bracket notation rules:
|
||||
/// - `[123]` - integer keys
|
||||
/// - `["string key"]` or `['string key']` - string keys (must be quoted)
|
||||
/// - String keys support escape sequences: `\"`, `\'`, `\\`
|
||||
fn get_path<V: FromLua>(&self, path: &str) -> Result<V> {
|
||||
let mut current = self.to_value();
|
||||
for (key, safe_nil) in parse_lookup_path(path)? {
|
||||
current = match current {
|
||||
Value::Table(table) => table.get::<Value>(key),
|
||||
Value::UserData(ud) => ud.get::<Value>(key),
|
||||
_ => {
|
||||
let type_name = current.type_name();
|
||||
let err = format!("attempt to index a {type_name} value with key '{key}'");
|
||||
Err(Error::runtime(err))
|
||||
}
|
||||
}?;
|
||||
if safe_nil && (current == Value::Nil || current == Value::NULL) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
let lua = self.weak_lua().lock();
|
||||
V::from_lua(current, lua.lua())
|
||||
}
|
||||
|
||||
/// Converts the object to a string in a human-readable format.
|
||||
///
|
||||
/// This might invoke the `__tostring` metamethod.
|
||||
fn to_string(&self) -> Result<String>;
|
||||
|
||||
/// Converts the object to a Lua value.
|
||||
fn to_value(&self) -> Value;
|
||||
|
||||
/// Gets a reference to the associated Lua state.
|
||||
#[doc(hidden)]
|
||||
fn weak_lua(&self) -> &WeakLua;
|
||||
}
|
||||
|
||||
pub(crate) trait ShortTypeName {
|
||||
#[inline(always)]
|
||||
fn type_name() -> String {
|
||||
short_type_name::<Self>()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> ShortTypeName for T {}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user