Compare commits

...

10 Commits

Author SHA1 Message Date
Andy Weidenbaum
c2c257e116 update license year to 2023 2023-01-01 06:27:05 +11:00
Andy Weidenbaum
38e3838a7c update io-cat dependency 2022-08-04 14:36:15 +10:00
atweiden
4d6d2a1697 lint 2022-06-27 13:47:33 +10:00
atweiden
f05e0966cb add CatSearcher 2022-06-27 13:38:18 +10:00
atweiden
c252048e2f impl From<Error> for rlua::Error 2022-06-23 10:42:35 +10:00
Andy Weidenbaum
357f2b6fdd format comments 2022-01-24 14:24:33 +11:00
Andy Weidenbaum
dd252db5c8 update rlua to 0.18 2022-01-22 21:28:10 +11:00
Andy Weidenbaum
57492ba18f specify rust 2021 edition 2022-01-22 20:53:53 +11:00
Andy Weidenbaum
3daf079207 s/’/' to be more tty friendly 2022-01-19 20:20:46 +11:00
Andy Weidenbaum
a2a801e69d 2022 2022-01-12 17:56:13 +11:00
6 changed files with 125 additions and 25 deletions

View File

@@ -1,7 +1,7 @@
[package]
name = "rlua-searcher"
version = "0.1.0"
edition = "2018"
edition = "2021"
authors = ["Andy Weidenbaum <atweiden@ioiojo.com>"]
license = "MIT OR Apache-2.0"
keywords = ["lua"]
@@ -11,4 +11,8 @@ readme = "README.md"
description = "Require Lua modules by name"
[dependencies]
rlua = "0.17"
rlua = "0.18"
[dependencies.io-cat]
git = "https://git.sr.ht/~ioiojo/io-cat"
rev = "74167240f6a284505a1f0a334432352878a7ba99"

View File

@@ -1,6 +1,6 @@
The MIT License (MIT)
Copyright (c) 2021 Andy Weidenbaum
Copyright (c) 2023 Andy Weidenbaum
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),

View File

@@ -9,6 +9,12 @@ impl From<rlua::Error> for Error {
}
}
impl From<Error> for rlua::Error {
fn from(error: Error) -> Self {
rlua::Error::RuntimeError(format!("rlua-searcher error: {}", error))
}
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let res = match self {

View File

@@ -5,7 +5,7 @@ use std::fs::File;
use std::io::Read;
use std::path::{Path, PathBuf};
use crate::types::Result;
use crate::types::{CatMap, Result};
/// Stores Lua modules indexed by module name, and provides an `rlua::MetaMethod` to
/// enable `require`ing the stored modules by name in an `rlua::Context`.
@@ -118,18 +118,18 @@ where
/// `rlua::Context` with Rust code.
///
/// Enables exposing `UserData` types to an `rlua::Context`.
pub struct ClosureSearcher {
struct ClosureSearcher {
/// Closures must accept three parameters:
///
/// 1. An `rlua::Context`, which the closure can do what it wants with.
///
/// 2. An `rlua::Table` containing globals (i.e. Luas `_G`), which can be passed
/// to `Chunk.set_environment()`.
/// 2. An `rlua::Table` containing globals (i.e. Lua's `_G`), which can be passed to
/// `Chunk.set_environment()`.
///
/// 3. The name of the module to be loaded (`&str`).
///
/// Closures must return an `rlua::Result`-wrapped `Function`. This `Function`
/// acts as the module loader.
/// Closures must return an `rlua::Result`-wrapped `Function`. This `Function` acts as
/// the module loader.
modules: HashMap<
Cow<'static, str>,
Box<
@@ -142,7 +142,7 @@ pub struct ClosureSearcher {
}
impl ClosureSearcher {
pub fn new(
fn new(
modules: HashMap<
Cow<'static, str>,
Box<
@@ -178,22 +178,22 @@ impl UserData for ClosureSearcher {
}
}
/// Like `Searcher`, but with function pointers as `modules` values, to facilitate
/// setting up an `rlua::Context` with Rust code.
/// Like `Searcher`, but with function pointers as `modules` values, to facilitate setting
/// up an `rlua::Context` with Rust code.
///
/// Enables exposing `UserData` types to an `rlua::Context`.
pub struct FunctionSearcher {
struct FunctionSearcher {
/// Functions must accept three parameters:
///
/// 1. An `rlua::Context`, which the function body can do what it wants with.
///
/// 2. An `rlua::Table` containing globals (i.e. Luas `_G`), which can be passed
/// to `Chunk.set_environment()`.
/// 2. An `rlua::Table` containing globals (i.e. Lua's `_G`), which can be passed to
/// `Chunk.set_environment()`.
///
/// 3. The name of the module to be loaded (`&str`).
///
/// Functions must return an `rlua::Result`-wrapped `Function`. This `Function`
/// acts as the module loader.
/// Functions must return an `rlua::Result`-wrapped `Function`. This `Function` acts
/// as the module loader.
modules: HashMap<
Cow<'static, str>,
for<'ctx> fn(Context<'ctx>, Table<'ctx>, &str) -> rlua::Result<Function<'ctx>>,
@@ -203,7 +203,7 @@ pub struct FunctionSearcher {
}
impl FunctionSearcher {
pub fn new(
fn new(
modules: HashMap<
Cow<'static, str>,
for<'ctx> fn(Context<'ctx>, Table<'ctx>, &str) -> rlua::Result<Function<'ctx>>,
@@ -236,11 +236,50 @@ impl UserData for FunctionSearcher {
}
}
/// Like `Searcher`, but with `CatMap` to facilitate indexing heterogenous strings and paths -
/// all presumed to resolve to Lua module content - by module names in `modules`.
struct CatSearcher {
modules: CatMap,
globals: RegistryKey,
}
impl CatSearcher {
fn new(modules: CatMap, globals: RegistryKey) -> Self {
Self { modules, globals }
}
}
impl UserData for CatSearcher {
fn add_methods<'lua, M>(methods: &mut M)
where
M: UserDataMethods<'lua, Self>,
{
methods.add_meta_method(MetaMethod::Call, |lua_ctx, this, name: String| {
let name = Cow::from(name);
match this.modules.get(&name) {
Some(content) => {
let content = content
.cat()
.map_err(|e| rlua::Error::RuntimeError(format!("io error: {}", e)))?;
Ok(Value::Function(
lua_ctx
.load(&content)
.set_name(name.as_ref())?
.set_environment(lua_ctx.registry_value::<Table>(&this.globals)?)?
.into_function()?,
))
}
None => Ok(Value::Nil),
}
});
}
}
/// Extend `rlua::Context` to support `require`ing Lua modules by name.
pub trait AddSearcher {
/// Add a `HashMap` of Lua modules indexed by module name to Luas
/// `package.searchers` table in an `rlua::Context`, with lookup functionality
/// provided by the `rlua_searcher::Searcher` struct.
/// Add a `HashMap` of Lua modules indexed by module name to Lua's `package.searchers`
/// table in an `rlua::Context`, with lookup functionality provided by the
/// `rlua_searcher::Searcher` struct.
fn add_searcher(&self, modules: HashMap<Cow<'static, str>, Cow<'static, str>>) -> Result<()>;
/// Like `add_searcher`, but with `modules` values given as paths to files containing
@@ -249,8 +288,8 @@ pub trait AddSearcher {
where
P: 'static + AsRef<Path> + Send;
/// Like `add_path_searcher`, but with user-provided closure for transforming
/// source code to Lua.
/// Like `add_path_searcher`, but with user-provided closure for transforming source
/// code to Lua.
fn add_path_searcher_poly<P>(
&self,
modules: HashMap<Cow<'static, str>, P>,
@@ -279,6 +318,10 @@ pub trait AddSearcher {
for<'ctx> fn(Context<'ctx>, Table<'ctx>, &str) -> rlua::Result<Function<'ctx>>,
>,
) -> Result<()>;
/// Like `add_searcher`, except `modules` can contain heterogenous strings and paths
/// indexed by module name.
fn add_cat_searcher(&self, modules: CatMap) -> Result<()>;
}
impl<'a> AddSearcher for Context<'a> {
@@ -358,4 +401,14 @@ impl<'a> AddSearcher for Context<'a> {
.set(searchers.len()? + 1, searcher)
.map_err(|e| e.into())
}
fn add_cat_searcher(&self, modules: CatMap) -> Result<()> {
let globals = self.globals();
let searchers: Table = globals.get::<_, Table>("package")?.get("searchers")?;
let registry_key = self.create_registry_value(globals)?;
let searcher = CatSearcher::new(modules, registry_key);
searchers
.set(searchers.len()? + 1, searcher)
.map_err(|e| e.into())
}
}

View File

@@ -1,3 +1,7 @@
use std::borrow::Cow;
use std::result;
use crate::error::Error;
pub type Result<A> = std::result::Result<A, Error>;
pub(crate) type CatMap = io_cat::CatMap<Cow<'static, str>>;
pub type Result<A> = result::Result<A, Error>;

View File

@@ -1,3 +1,4 @@
use io_cat::CatMap;
use rlua::{Context, Function, Lua, Table, UserData, UserDataMethods, Value};
use rlua_searcher::{AddSearcher, Result};
use std::borrow::Cow;
@@ -126,7 +127,7 @@ fn module_reloading_works() {
assert_eq!("hello lume", hello);
// Remove lume module from Luas `package.loaded` cache to facilitate reload.
// Remove lume module from Lua's `package.loaded` cache to facilitate reload.
lua.context::<_, rlua::Result<()>>(|lua_ctx| {
let globals = lua_ctx.globals();
let loaded: Table = globals.get::<_, Table>("package")?.get("loaded")?;
@@ -330,3 +331,35 @@ fn cartridge_loader<'ctx>(
.set_environment(env)?
.into_function()?)
}
#[test]
fn add_cat_searcher_works() {
let name = Cow::from("lume".to_string());
let path = PathBuf::new()
.join(std::env::var("CARGO_MANIFEST_DIR").unwrap())
.join("tests")
.join("data")
.join("lume.lua");
let mut map: CatMap<Cow<'static, str>> = CatMap::new();
map.insert(name, Box::new(path));
map.insert(Cow::from("loon"), Box::new(r#"return "hello loon""#));
let lua = Lua::new();
let hello = lua
.context::<_, Result<String>>(|lua_ctx| {
lua_ctx.add_cat_searcher(map)?;
Ok(lua_ctx.load(r#"return require("lume")"#).eval()?)
})
.unwrap();
assert_eq!("hello lume", hello);
let hello = lua
.context::<_, Result<String>>(|lua_ctx| {
Ok(lua_ctx.load(r#"return require("loon")"#).eval()?)
})
.unwrap();
assert_eq!("hello loon", hello);
}