use std::error::Error;
use std::fmt;
use std::sync::{Mutex, PoisonError};
use airsl::mlua;
use crate::types::name::ToolName;
use crate::types::op::OpError;
use crate::types::report::{Diagnostic, Location};
use crate::types::tree::TreePath;
#[derive(Debug)]
pub(super) struct Raised {
text: String,
diagnostic: Mutex<Option<Diagnostic>>,
}
impl Raised {
pub(super) fn ordinary(diagnostic: Diagnostic) -> Self {
Self {
text: diagnostic.to_string(),
diagnostic: Mutex::new(Some(diagnostic)),
}
}
pub(super) const fn recorded(text: String) -> Self {
Self {
text,
diagnostic: Mutex::new(None),
}
}
pub(super) fn into_lua(self) -> mlua::Error {
mlua::Error::external(self)
}
fn take(&self) -> Option<Diagnostic> {
self.diagnostic
.lock()
.unwrap_or_else(PoisonError::into_inner)
.take()
}
}
impl fmt::Display for Raised {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.text)
}
}
impl Error for Raised {}
pub(super) fn wrap(tool: &ToolName, entry: &TreePath, error: &airsl::Error) -> Option<Diagnostic> {
if let Some(found) = raised(error) {
return found.take();
}
Some(lua_failure(tool, entry, error))
}
pub(super) fn lua_failure(tool: &ToolName, entry: &TreePath, error: &airsl::Error) -> Diagnostic {
let text = error.to_string();
let first_line = text.lines().next().unwrap_or_default().to_owned();
Diagnostic::new(
Location::file(format!("{tool}/{entry}")),
OpError::Lua { first_line },
)
}
fn raised(error: &airsl::Error) -> Option<&Raised> {
let mut link: Option<&(dyn Error + 'static)> = Some(error);
while let Some(current) = link {
let found = lua_error(current).and_then(mlua::Error::downcast_ref::<Raised>);
if found.is_some() {
return found;
}
link = current.source();
}
None
}
fn lua_error<'a>(link: &'a (dyn Error + 'static)) -> Option<&'a mlua::Error> {
link.downcast_ref::<mlua::Error>().or_else(|| {
link.downcast_ref::<Box<mlua::Error>>()
.map(|boxed| &**boxed)
})
}
#[cfg(test)]
mod tests {
use std::error::Error;
use airsl::Script;
use super::*;
use crate::host::engine::build_engine;
use crate::host::testing::Probe;
use crate::types::report::FieldError;
type TestResult = Result<(), Box<dyn Error>>;
fn tool() -> Result<ToolName, Box<dyn Error>> {
Ok(ToolName::new("claude")?)
}
fn entry() -> TreePath {
TreePath::from_parts(&["adapter.lua"])
}
fn failure(source: &str) -> Result<airsl::Error, Box<dyn Error>> {
let engine = build_engine(Probe::new(tool()?)?)?;
engine
.eval(&Script::from_source(source, "adapter.lua")?)
.err()
.ok_or_else(|| "the script should fail".into())
}
#[test]
fn a_recorded_refusal_adds_nothing() -> TestResult {
let error = failure("airsstack.probe.raise_recorded('already recorded')")?;
assert!(wrap(&tool()?, &entry(), &error).is_none());
Ok(())
}
#[test]
fn an_ordinary_refusal_is_its_own_located_diagnostic() -> TestResult {
let error = failure("\nairsstack.probe.raise_ordinary()")?;
let shown = wrap(&tool()?, &entry(), &error).map(|d| d.to_string());
assert_eq!(shown.as_deref(), Some("claude/adapter.lua:2: required"));
Ok(())
}
#[test]
fn any_other_failure_is_the_first_line_at_the_entry() -> TestResult {
let error = failure("error('path must be relative')")?;
let shown = wrap(&tool()?, &entry(), &error).map(|d| d.to_string());
assert_eq!(
shown.as_deref(),
Some(
"claude/adapter.lua: lua error in adapter.lua: runtime error: adapter.lua:1: path must be relative"
)
);
Ok(())
}
#[test]
fn raised_text_is_the_located_refusal() {
let diagnostic = Diagnostic::new(Location::file("claude/adapter.lua"), FieldError::Empty);
let raised = Raised::ordinary(diagnostic);
assert_eq!(raised.to_string(), "claude/adapter.lua: empty");
assert!(raised.take().is_some());
assert!(raised.take().is_none());
}
}