Skip to main content

luadec_rust/
lib.rs

1//! # luadec-rust
2//!
3//! A Lua 5.1 bytecode decompiler library.
4//!
5//! This crate takes compiled Lua 5.1 bytecode and produces readable Lua source code.
6//!
7//! ## Quick Start
8//!
9//! ```no_run
10//! let bytecode = std::fs::read("input.luac").unwrap();
11//! let source = luadec_rust::decompile(&bytecode).unwrap();
12//! println!("{}", source);
13//! ```
14//!
15//! ## Advanced Usage
16//!
17//! For more control, use the [`lua51`] module directly:
18//!
19//! ```no_run
20//! use luac_parser::lua_bytecode;
21//! use luadec_rust::lua51::lifter::Lifter;
22//! use luadec_rust::lua51::emit;
23//!
24//! let data = std::fs::read("input.luac").unwrap();
25//! let (_, bytecode) = lua_bytecode(&data).unwrap();
26//! let func = Lifter::decompile(&bytecode.main_chunk);
27//! let source = emit::emit_chunk(&func);
28//! ```
29
30pub mod lua51;
31
32/// Decompile Lua 5.1 bytecode into Lua source code.
33///
34/// Takes raw bytecode bytes (e.g. from a `.luac` file) and returns
35/// the decompiled Lua source as a `String`.
36///
37/// # Errors
38///
39/// Returns an error string if the bytecode cannot be parsed.
40///
41/// # Example
42///
43/// ```no_run
44/// let bytecode = std::fs::read("compiled.luac").unwrap();
45/// let source = luadec_rust::decompile(&bytecode).unwrap();
46/// println!("{}", source);
47/// ```
48pub fn decompile(bytecode: &[u8]) -> Result<String, String> {
49    let (_, bc) = luac_parser::lua_bytecode(bytecode)
50        .map_err(|e| format!("failed to parse bytecode: {:?}", e))?;
51    let func = lua51::lifter::Lifter::decompile(&bc.main_chunk);
52    Ok(lua51::emit::emit_chunk(&func))
53}