use crate::error::{Error, Result};
pub struct Stub {
pub install_name: String,
pub exports: Vec<String>,
}
pub fn parse(text: &str) -> Result<Stub> {
let install_name = text
.lines()
.find_map(|line| scalar(line, "install-name"))
.ok_or(Error::Format("Mach-O .tbd has no install-name"))?
.to_owned();
let mut exports = Vec::new();
let mut list: Option<String> = None;
for line in text.lines() {
if let Some(buffer) = list.as_mut() {
buffer.push(' ');
buffer.push_str(line.trim());
if buffer.contains(']') {
parse_symbols(buffer, &mut exports);
list = None;
}
continue;
}
let trimmed = line.trim();
let Some((key, value)) = trimmed.split_once(':') else {
continue;
};
if !is_symbol_key(key.trim()) || !value.contains('[') {
continue;
}
if value.contains(']') {
parse_symbols(value, &mut exports);
} else {
list = Some(value.to_owned());
}
}
exports.sort_unstable();
exports.dedup();
Ok(Stub {
install_name,
exports,
})
}
fn scalar<'a>(line: &'a str, key: &str) -> Option<&'a str> {
let value = line.trim().strip_prefix(key)?.strip_prefix(':')?.trim();
let unquoted = value
.strip_prefix('\'')
.and_then(|v| v.strip_suffix('\''))
.or_else(|| value.strip_prefix('"').and_then(|v| v.strip_suffix('"')))
.unwrap_or(value);
(!unquoted.is_empty()).then_some(unquoted)
}
fn is_symbol_key(key: &str) -> bool {
matches!(key, "symbols" | "weak-symbols" | "thread-local-symbols")
}
fn parse_symbols(list: &str, out: &mut Vec<String>) {
let Some((_, body)) = list.split_once('[') else {
return;
};
let body = body.split_once(']').map_or(body, |(before, _)| before);
for item in body.split(',') {
let symbol = item.trim().trim_matches(['\'', '"']);
if !symbol.is_empty() {
out.push(symbol.to_owned());
}
}
}