manen

Fancy Lua REPL
Log | Files | Refs | README | LICENSE

validator.rs (1117B)


      1 use mlua::prelude::*;
      2 use reedline::{ValidationResult, Validator};
      3 
      4 // TODO; we should instead rely on the parser to determine incomplete input
      5 pub struct LuaValidator {
      6     lua: Lua,
      7 }
      8 
      9 impl LuaValidator {
     10     pub fn new() -> Self {
     11         Self { lua: Lua::new() }
     12     }
     13 }
     14 
     15 fn load_lua(lua: &Lua, code: &str) -> LuaResult<LuaFunction> {
     16     if let Ok(func) = lua.load(format!("return ({code})")).into_function() {
     17         return Ok(func);
     18     }
     19 
     20     lua.load(code).into_function()
     21 }
     22 
     23 impl Validator for LuaValidator {
     24     fn validate(&self, line: &str) -> ValidationResult {
     25         if line.starts_with(".") {
     26             return ValidationResult::Complete;
     27         }
     28 
     29         match load_lua(&self.lua, line) {
     30             Ok(_) => ValidationResult::Complete,
     31             Err(LuaError::SyntaxError {
     32                 incomplete_input, ..
     33             }) => {
     34                 if incomplete_input {
     35                     ValidationResult::Incomplete
     36                 } else {
     37                     ValidationResult::Complete
     38                 }
     39             }
     40             Err(_) => ValidationResult::Complete,
     41         }
     42     }
     43 }