Compare commits

..

No commits in common. "57f391a9502c494cee9db4754a362d781cf24d1b" and "5c257b0f7478b95f36a23b472399e80569993495" have entirely different histories.

8 changed files with 137 additions and 160 deletions

View File

@ -67,7 +67,7 @@ impl lb_fslib {
///
/// # Errors
///
/// This function may throw if the file does not exist or could not be read.
/// This function may throw if the file does not exist or cannot be read.
pub async extern "Lua-C" fn read(path: &str) -> Result<Vec<u8>> {
Ok(tokio::fs::read(path).await?)
}
@ -78,7 +78,7 @@ impl lb_fslib {
///
/// # Errors
///
/// This function may throw if the file does not exist or could not be read.
/// This function may throw if the file does not exist or cannot be read.
pub extern "Lua-C" fn read_sync(path: &str) -> Result<Vec<u8>> {
Ok(std::fs::read(path)?)
}
@ -87,7 +87,7 @@ impl lb_fslib {
///
/// # Errors
///
/// This function may throw if the file could not be written.
/// This function may throw if the file cannot be written.
pub async extern "Lua-C" fn write(path: &str, contents: &[u8]) -> Result<()> {
Ok(tokio::fs::write(path, contents).await?)
}
@ -98,7 +98,7 @@ impl lb_fslib {
///
/// # Errors
///
/// This function may throw if the file could not be written.
/// This function may throw if the file cannot be written.
pub extern "Lua-C" fn write_sync(path: &str, contents: &[u8]) -> Result<()> {
Ok(std::fs::write(path, contents)?)
}
@ -107,7 +107,7 @@ impl lb_fslib {
///
/// # Errors
///
/// This function may throw if the directory could not be read.
/// This function may throw if the directory cannot be read.
pub async extern "Lua-C" fn read_dir(path: &str) -> Result<lb_read_dir> {
Ok(lb_read_dir::new(tokio::fs::read_dir(path).await?))
}
@ -118,7 +118,7 @@ impl lb_fslib {
///
/// # Errors
///
/// This function may throw if the directory could not be read.
/// This function may throw if the directory cannot be read.
pub extern "Lua-C" fn read_dir_sync(path: &str) -> Result<lb_read_dir_sync> {
Ok(lb_read_dir_sync::new(std::fs::read_dir(path)?))
}
@ -156,7 +156,7 @@ impl lb_fslib {
///
/// # Errors
///
/// This function may throw if the temporary directory could not be created.
/// This function may throw if the temporary directory cannot be created.
pub extern "Lua-C" fn temp_dir() -> Result<lb_temp_dir> {
Ok(lb_temp_dir::new(tempfile::tempdir()?))
}
@ -165,7 +165,7 @@ impl lb_fslib {
///
/// # Errors
///
/// This function may throw if the temporary directory could not be created.
/// This function may throw if the temporary directory cannot be created.
pub extern "Lua-C" fn temp_dir_in(path: &str) -> Result<lb_temp_dir> {
Ok(lb_temp_dir::new(tempfile::tempdir_in(path)?))
}
@ -186,7 +186,7 @@ impl lb_read_dir {
///
/// # Errors
///
/// This function may throw if the directory could not be read.
/// This function may throw if the directory cannot be read.
#[call]
pub async extern "Lua-C" fn next(&self) -> Result<Option<lb_dir_entry>> {
Ok(self
@ -213,7 +213,7 @@ impl lb_read_dir_sync {
///
/// # Errors
///
/// This function may throw if the directory could not be read.
/// This function may throw if the directory cannot be read.
#[call]
pub extern "Lua-C" fn next(&self) -> Result<Option<lb_dir_entry_sync>> {
Ok(self
@ -250,7 +250,7 @@ impl lb_dir_entry {
///
/// # Errors
///
/// This function may throw if the file type could not be determined.
/// This function may throw if the file type cannot be determined.
pub async extern "Lua-C" fn r#type(&self) -> Result<lb_file_type> {
Ok(lb_file_type::new(self.0.file_type().await?))
}
@ -259,7 +259,7 @@ impl lb_dir_entry {
///
/// # Errors
///
/// This function may throw if the metadata could not be retrieved.
/// This function may throw if the metadata cannot be retrieved.
pub async extern "Lua-C" fn metadata(&self) -> Result<lb_file_meta> {
Ok(lb_file_meta::new(self.0.metadata().await?))
}
@ -302,7 +302,7 @@ impl lb_dir_entry_sync {
///
/// # Errors
///
/// This function may throw if the file type could not be determined.
/// This function may throw if the file type cannot be determined.
pub extern "Lua-C" fn r#type(&self) -> Result<lb_file_type> {
Ok(lb_file_type::new(self.0.file_type()?))
}
@ -311,7 +311,7 @@ impl lb_dir_entry_sync {
///
/// # Errors
///
/// This function may throw if the metadata could not be retrieved.
/// This function may throw if the metadata cannot be retrieved.
pub extern "Lua-C" fn metadata(&self) -> Result<lb_file_meta> {
Ok(lb_file_meta::new(self.0.metadata()?))
}
@ -418,7 +418,7 @@ impl lb_file_meta {
///
/// # Errors
///
/// This function may throw if the creation time could not be retrieved.
/// This function may throw if the creation time cannot be retrieved.
pub extern "Lua-C" fn created(&self) -> Result<f64> {
Ok(self
.0
@ -432,7 +432,7 @@ impl lb_file_meta {
///
/// # Errors
///
/// This function may throw if the modification time could not be retrieved.
/// This function may throw if the modification time cannot be retrieved.
pub extern "Lua-C" fn modified(&self) -> Result<f64> {
Ok(self
.0
@ -446,7 +446,7 @@ impl lb_file_meta {
///
/// # Errors
///
/// This function may throw if the access time could not be retrieved.
/// This function may throw if the access time cannot be retrieved.
pub extern "Lua-C" fn accessed(&self) -> Result<f64> {
Ok(self
.0
@ -509,7 +509,7 @@ impl lb_walk_dir {
///
/// # Errors
///
/// This function may throw if the directory could not be read.
/// This function may throw if the directory cannot be read.
#[call]
pub extern "Lua-C" fn next(&self) -> Result<Option<lb_walk_dir_entry>> {
Ok(self
@ -551,7 +551,7 @@ impl lb_walk_dir_entry {
///
/// # Errors
///
/// This function may throw if the metadata could not be retrieved.
/// This function may throw if the metadata cannot be retrieved.
pub extern "Lua-C" fn metadata(&self) -> Result<lb_file_meta> {
Ok(lb_file_meta::new(self.0.metadata()?))
}
@ -606,7 +606,7 @@ impl lb_glob_dir {
///
/// # Errors
///
/// This function may throw if the directory could not be read.
/// This function may throw if the directory cannot be read.
#[call]
pub extern "Lua-C" fn next(&self) -> Result<Option<lb_walk_dir_entry>> {
while let Some(res) = self.iter.try_borrow_mut()?.next() {

View File

@ -510,12 +510,12 @@ pub struct lb_socketaddr(#[opaque] SocketAddr);
#[metatype]
impl lb_socketaddr {
/// The IP part of this address.
/// Returns the IP part of this address.
pub extern "Lua-C" fn ip(&self) -> lb_ipaddr {
self.0.ip().into()
}
/// The port part of this address.
/// Returns the port part of this address.
pub extern "Lua-C" fn port(&self) -> u16 {
self.0.port()
}
@ -775,16 +775,16 @@ impl lb_tcpstream {
Ok(self.write.try_borrow_mut()?)
}
/// The local socket address that this stream is bound to.
pub extern "Lua-C" fn local_addr(&self) -> Result<lb_socketaddr> {
Ok(self.read_half()?.local_addr()?.into())
}
/// The remote socket address that this stream is connected to.
/// Gets the remote socket address of this stream.
pub extern "Lua-C" fn peer_addr(&self) -> Result<lb_socketaddr> {
Ok(self.read_half()?.peer_addr()?.into())
}
/// Gets the local socket address of this stream.
pub extern "Lua-C" fn local_addr(&self) -> Result<lb_socketaddr> {
Ok(self.read_half()?.local_addr()?.into())
}
/// Waits for this stream to be ready in the given half.
///
/// The argument `half` can be `"read"` for the readable half, `"write"` for the writable half,
@ -936,7 +936,7 @@ impl lb_tcplistener {
}
}
/// The local socket address that this listener is bound to.
/// Returns the local socket address that this listener is bound to.
pub extern "Lua-C" fn local_addr(&self) -> Result<lb_socketaddr> {
Ok(self.listener.local_addr()?.into())
}
@ -1019,12 +1019,12 @@ impl lb_tcplistener_stream {
}
}
/// The local socket address that the listener is bound to.
/// Returns the local socket address that the listener is bound to.
pub extern "Lua-C" fn local_addr(&self) -> Result<lb_socketaddr> {
Ok(self.stream()?.local_addr()?.into())
}
/// The remote socket address that this stream is connected to.
/// Returns the remote socket address of this stream.
pub extern "Lua-C" fn peer_addr(&self) -> Result<lb_socketaddr> {
Ok(self.stream()?.peer_addr()?.into())
}

View File

@ -14,7 +14,6 @@ pub type ErrorFn = dyn Fn(&luajit::Error);
pub struct Builder {
registry: Registry,
report_err: Rc<ErrorFn>,
jit_opts: Vec<String>,
prohibit_globals: bool,
}
@ -26,14 +25,6 @@ impl Builder {
Some(trace) => eprintln!("unhandled lua error: {err}\n{trace}"),
None => eprintln!("unhandled lua error: {err}"),
}),
jit_opts: vec![
// more aggressive jit options based on OpenResty's defaults
// https://github.com/openresty/luajit2#updated-jit-default-parameters
"maxtrace=8000".into(),
"maxrecord=16000".into(),
"minstitch=3".into(),
"maxmcode=40960".into(),
],
prohibit_globals: false,
}
}
@ -52,18 +43,6 @@ impl Builder {
self
}
pub fn jit_opt(&mut self, opt: impl AsRef<str>) -> &mut Self {
self.jit_opts.push(opt.as_ref().into());
self
}
pub fn jit_opts(&mut self, opts: impl IntoIterator<Item: AsRef<str>>) -> &mut Self {
for opt in opts {
self.jit_opt(opt);
}
self
}
pub fn module<T: Module>(&mut self) -> &mut Self {
self.registry.preload::<T>();
self
@ -75,11 +54,21 @@ impl Builder {
state.eval(&chunk, 0, Some(0))?;
if self.prohibit_globals {
state_prohibit_globals(&mut state)?;
}
for opt in self.jit_opts.iter() {
state_set_jitopt(&mut state, opt)?;
let mut s = state.guard();
s.eval(
&Chunk::new(luaify_chunk!({
return |self, key, value| {
error(("undeclared local variable '%s'").format(key), 2);
};
})),
0,
Some(1),
)
.unwrap();
s.push(NewTable::new());
(s.push("__index"), s.push_idx(-3), s.set(-3));
(s.push("__newindex"), s.push_idx(-3), s.set(-3));
s.set_metatable(Index::globals());
}
Ok(Runtime {
@ -92,60 +81,6 @@ impl Builder {
}
}
fn state_prohibit_globals(state: &mut State) -> luajit::Result<()> {
let mut s = state.guard();
let chunk = Chunk::new(luaify_chunk!({
return |self, key, value| {
error(("undeclared local variable '%s'").format(key), 2);
};
}))
.with_path("[luby]");
s.eval(&chunk, 0, Some(1)).unwrap();
s.push(NewTable::new());
(s.push("__index"), s.push_idx(-3), s.set(-3));
(s.push("__newindex"), s.push_idx(-3), s.set(-3));
s.set_metatable(Index::globals());
Ok(())
}
fn state_set_jitopt(state: &mut State, opt: &str) -> luajit::Result<()> {
let mut s = state.guard();
if let Some((cmd, opt)) = parse_jitlib_cmd(opt)
&& let Ok(_) = s.require(format!("jit.{cmd}"), Some(1))
{
// require("jit.{cmd}").start(opt)
(s.push("start"), s.get(-2));
s.push(opt);
s.call(1, Some(0))?;
} else {
s.require("jit", Some(1)).unwrap();
match opt {
cmd @ ("on" | "off" | "flush") => {
// require("jit").<on|off|flush>()
(s.push(cmd), s.get(-2));
s.call(0, Some(0))?;
}
_ => {
// require("jit").opt.start(opt)
(s.push("opt"), s.get(-2));
(s.push("start"), s.get(-2));
s.push(opt);
s.call(1, Some(0))?;
}
}
}
Ok(())
}
fn parse_jitlib_cmd(cmd: &str) -> Option<(&str, &str)> {
match cmd {
"p" => Some(("p", "Flspv10")), // default -jp flags
"v" => Some(("v", "-")), // default -jv flags
"dump" => Some(("dump", "tirs")), // default -jdump flags
_ => cmd.split_once('='),
}
}
#[derive(Deref, DerefMut)]
pub struct Runtime {
#[deref]

View File

@ -645,7 +645,7 @@ impl<'r, 'm> MetatypeFunctionBuilder<'r, 'm> {
}
}
pub trait Annotate {
pub trait Annotation {
fn annotation() -> impl Display;
}
@ -699,7 +699,7 @@ macro_rules! impl_primitive {
fn build(_b: &mut TypeBuilder) {}
}
impl Annotate for $rty {
impl Annotation for $rty {
fn annotation() -> impl Display {
$lty
}
@ -867,9 +867,9 @@ impl_ptr!(Option<&mut T>, true);
macro_rules! impl_ref_annotation {
($ty:ty) => {
impl<T> Annotate for $ty
impl<T> Annotation for $ty
where
T: Annotate,
T: Annotation,
{
fn annotation() -> impl Display {
display!("{}", T::annotation())
@ -1005,9 +1005,9 @@ where
}
}
impl<T> Annotate for [T]
impl<T> Annotation for [T]
where
T: Annotate,
T: Annotation,
{
fn annotation() -> impl Display {
display!("{}[]", T::annotation())
@ -1035,9 +1035,9 @@ where
}
}
impl<T, const N: usize> Annotate for [T; N]
impl<T, const N: usize> Annotation for [T; N]
where
T: Annotate,
T: Annotation,
{
fn annotation() -> impl Display {
display!("{}[]", T::annotation())
@ -1106,25 +1106,25 @@ impl_externcfn!(fn(A, B, C, D, E, F, G) -> H);
impl_externcfn!(fn(A, B, C, D, E, F, G, H) -> I);
impl_externcfn!(fn(A, B, C, D, E, F, G, H, I) -> J);
impl<'s> Annotate for &'s [u8] {
impl<'s> Annotation for &'s [u8] {
fn annotation() -> impl Display {
"string"
}
}
impl<'s> Annotate for &'s str {
impl<'s> Annotation for &'s str {
fn annotation() -> impl Display {
"string"
}
}
impl Annotate for Vec<u8> {
impl Annotation for Vec<u8> {
fn annotation() -> impl Display {
"string"
}
}
impl Annotate for String {
impl Annotation for String {
fn annotation() -> impl Display {
"string"
}

View File

@ -1,7 +1,7 @@
#![allow(non_camel_case_types)]
use crate::{
__internal::{disp, display},
Annotate,
Annotation,
};
use std::{fmt::Display, marker::PhantomData};
@ -9,7 +9,7 @@ enum Marker {}
pub struct any(Marker);
impl Annotate for any {
impl Annotation for any {
fn annotation() -> impl Display {
"any"
}
@ -17,7 +17,7 @@ impl Annotate for any {
pub struct many(Marker);
impl Annotate for many {
impl Annotation for many {
fn annotation() -> impl Display {
"..."
}
@ -25,7 +25,7 @@ impl Annotate for many {
pub struct nil(Marker);
impl Annotate for nil {
impl Annotation for nil {
fn annotation() -> impl Display {
"nil"
}
@ -33,7 +33,7 @@ impl Annotate for nil {
pub struct lightuserdata(Marker);
impl Annotate for lightuserdata {
impl Annotation for lightuserdata {
fn annotation() -> impl Display {
"lightuserdata"
}
@ -41,10 +41,10 @@ impl Annotate for lightuserdata {
pub struct table<K, V>(Marker, PhantomData<*mut [(K, V)]>);
impl<K, V> Annotate for table<K, V>
impl<K, V> Annotation for table<K, V>
where
K: Annotate,
V: Annotate,
K: Annotation,
V: Annotation,
{
fn annotation() -> impl Display {
display!("table<{}, {}>", K::annotation(), V::annotation())
@ -53,7 +53,7 @@ where
pub struct function(Marker);
impl Annotate for function {
impl Annotation for function {
fn annotation() -> impl Display {
"function"
}
@ -63,9 +63,9 @@ pub struct fun<I, O>(Marker, PhantomData<fn(I) -> O>);
macro_rules! impl_fun {
(fn($($arg:ident),*)) => {
impl<$($arg,)*> Annotate for fun<($($arg,)*), ()>
impl<$($arg,)*> Annotation for fun<($($arg,)*), ()>
where
$($arg: Annotate,)*
$($arg: Annotation,)*
{
fn annotation() -> impl Display {
disp(|f| {
@ -79,10 +79,10 @@ macro_rules! impl_fun {
};
(fn($($arg:ident),*) -> $ret:ident) => {
impl<$($arg,)* $ret> Annotate for fun<($($arg,)*), $ret>
impl<$($arg,)* $ret> Annotation for fun<($($arg,)*), $ret>
where
$($arg: Annotate,)*
$ret: Annotate,
$($arg: Annotation,)*
$ret: Annotation,
{
fn annotation() -> impl Display {
disp(|f| {
@ -111,7 +111,7 @@ impl_fun!(fn(A, B, C, D, E, F, G, H, I) -> J);
pub struct userdata(Marker);
impl Annotate for userdata {
impl Annotation for userdata {
fn annotation() -> impl Display {
"userdata"
}
@ -119,7 +119,7 @@ impl Annotate for userdata {
pub struct thread(Marker);
impl Annotate for thread {
impl Annotation for thread {
fn annotation() -> impl Display {
"thread"
}
@ -127,7 +127,7 @@ impl Annotate for thread {
pub struct cdata(Marker);
impl Annotate for cdata {
impl Annotation for cdata {
fn annotation() -> impl Display {
"cdata"
}
@ -135,10 +135,10 @@ impl Annotate for cdata {
pub struct Either<T, U>(Marker, PhantomData<(T, U)>);
impl<T, U> Annotate for Either<T, U>
impl<T, U> Annotation for Either<T, U>
where
T: Annotate,
U: Annotate,
T: Annotation,
U: Annotation,
{
fn annotation() -> impl Display {
display!("({} | {})", T::annotation(), U::annotation())
@ -149,9 +149,9 @@ pub struct OneOf<X>(Marker, PhantomData<X>);
macro_rules! impl_oneof {
($($ty:ident),+) => {
impl<$($ty),+> Annotate for OneOf<($($ty,)+)>
impl<$($ty),+> Annotation for OneOf<($($ty,)+)>
where
$($ty: Annotate),+
$($ty: Annotation),+
{
fn annotation() -> impl Display {
disp(|f| {
@ -174,18 +174,18 @@ impl_oneof!(A, B, C, D, E, F, G);
impl_oneof!(A, B, C, D, E, F, G, H);
impl_oneof!(A, B, C, D, E, F, G, H, I);
impl<T> Annotate for Option<T>
impl<T> Annotation for Option<T>
where
T: Annotate,
T: Annotation,
{
fn annotation() -> impl Display {
display!("{}?", T::annotation())
}
}
impl<T, E> Annotate for Result<T, E>
impl<T, E> Annotation for Result<T, E>
where
T: Annotate,
T: Annotation,
{
fn annotation() -> impl Display {
display!("{}", T::annotation())

View File

@ -70,7 +70,7 @@ fn generate_type(ty: &Ident) -> Result<TokenStream> {
}
}
impl #ffi::Annotate for #ty {
impl #ffi::Annotation for #ty {
fn annotation() -> impl ::std::fmt::Display { #name }
}

View File

@ -682,7 +682,7 @@ fn stub_lua_function(func: &mut ImplItemFn) -> Result<()> {
func.attrs.push(parse_quote!(#[allow(unused)]));
func.block.stmts.clear();
func.block.stmts.push(parse_quote!(
const fn has_annotation<T: #ffi::Annotate>() {}
const fn has_annotation<T: #ffi::Annotation>() {}
));
// convert `...` variadic to a `rest: luaffi::marker::Many` parameter

View File

@ -231,6 +231,7 @@ fn init_tokio(args: &Args) -> tokio::runtime::Runtime {
}
fn init_lua(args: &Args) -> lb::runtime::Runtime {
let mut rt = {
let mut rt = lb::runtime::Builder::new();
luby::open(&mut rt);
@ -240,9 +241,50 @@ fn init_lua(args: &Args) -> lb::runtime::Runtime {
rt.unhandled_error(error_cb)
.prohibit_globals(!args.allow_globals)
.jit_opts(args.jit.iter())
.build()
.unwrap()
};
for arg in args.jit.iter() {
let mut s = rt.guard();
let res = if let Some((cmd, flags)) = parse_jitlib_cmd(arg)
&& let Ok(_) = s.require(format!("jit.{cmd}"), Some(1))
{
(s.push("start"), s.get(-2));
s.push(flags);
s.call(1, Some(0)) // require("jit.{cmd}").start(flags)
} else {
s.require("jit", Some(1)).unwrap();
match arg.as_str() {
cmd @ ("on" | "off" | "flush") => {
(s.push(cmd), s.get(-2));
s.call(0, Some(0)) // require("jit").[on/off/flush]()
}
flags => {
(s.push("opt"), s.get(-2));
(s.push("start"), s.get(-2));
s.push(flags);
s.call(1, Some(0)) // require("jit").opt.start(flags)
}
}
};
if let Err(err) = res {
drop(s);
rt.report_error(&err);
}
}
rt
}
fn parse_jitlib_cmd(s: &str) -> Option<(&str, &str)> {
match s {
"p" => Some(("p", "Flspv10")), // default -jp flags
"v" => Some(("v", "-")), // default -jv flags
"dump" => Some(("dump", "tirs")), // default -jdump flags
_ => s.split_once('='),
}
}
async fn main_async(args: Args, cx: &mut lb::runtime::Context) -> ExitCode {