use std::path::{Path, PathBuf};
use crate::{
archive::Archive,
error::{Error, Result},
search,
};
const MAX_NESTING: usize = 8;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Name<'a> {
pub text: &'a str,
pub library: bool,
pub as_needed: bool,
}
impl<'a> Name<'a> {
fn new(word: &'a str, as_needed: bool) -> Self {
word.strip_prefix("-l").map_or(
Self {
text: word,
library: false,
as_needed,
},
|name| Self {
text: name,
library: true,
as_needed,
},
)
}
}
pub fn parse<'a>(
path: &Path,
text: &'a str,
out: &mut Vec<Name<'a>>,
) -> Result<()> {
out.clear();
let mut lex = Lexer::new(text);
while let Some(token) = lex.next_token(path)? {
match token {
Token::Word("INPUT" | "GROUP") => {
names(path, &mut lex, false, 0, out)?;
}
Token::Word("OUTPUT_FORMAT") => skip_list(path, &mut lex)?,
Token::Word(word) => return Err(unimplemented(path, word)),
Token::Open | Token::Close => {
return Err(refuse(
path,
"a parenthesis outside any directive".to_owned(),
));
}
}
}
Ok(())
}
pub fn looks_like(head: &[u8]) -> bool {
!head.is_empty()
&& !Archive::is_archive(head)
&& head.iter().copied().all(is_text)
}
const fn is_text(b: u8) -> bool {
matches!(b, b'\t' | b'\n' | 0x0b | 0x0c | b'\r') || (b >= 0x20 && b < 0x7f)
}
#[derive(Clone, Copy)]
pub struct Search<'a> {
pub paths: &'a [PathBuf],
pub sysroot: Option<&'a Path>,
}
impl Search<'_> {
pub fn resolve(&self, name: &Name<'_>, script: &Path) -> Option<PathBuf> {
if name.library {
return search::find_library(name.text, self.paths, self.sysroot);
}
if let Some(rest) = name.text.strip_prefix('=') {
return Some(search::rooted(self.sysroot, rest));
}
let text = Path::new(name.text);
if text.is_absolute() {
return Some(self.rooted_absolute(name.text, script));
}
let beside =
script.parent().unwrap_or_else(|| Path::new(".")).join(text);
if beside.exists() {
return Some(beside);
}
if text.exists() {
return Some(text.to_path_buf());
}
search::find_in_paths(name.text, self.paths, self.sysroot)
}
fn rooted_absolute(&self, text: &str, script: &Path) -> PathBuf {
match self.sysroot {
Some(root) if script.starts_with(root) => {
search::rooted(Some(root), text)
}
_ => PathBuf::from(text),
}
}
}
pub fn not_found(path: &Path, name: &Name<'_>) -> Error {
let spelling = if name.library { "-l" } else { "" };
refuse(
path,
format!("nothing answers to `{spelling}{}`", name.text),
)
}
fn names<'a>(
path: &Path,
lex: &mut Lexer<'a>,
as_needed: bool,
depth: usize,
out: &mut Vec<Name<'a>>,
) -> Result<()> {
if depth > MAX_NESTING {
return Err(refuse(
path,
format!("AS_NEEDED nested more than {MAX_NESTING} deep"),
));
}
expect_open(path, lex)?;
while let Some(token) = lex.next_token(path)? {
match token {
Token::Close => return Ok(()),
Token::Word("AS_NEEDED") => {
names(path, lex, true, depth.saturating_add(1), out)?;
}
Token::Word(word) => out.push(Name::new(word, as_needed)),
Token::Open => {
return Err(refuse(
path,
"an unexpected ( inside a file list".to_owned(),
));
}
}
}
Err(refuse(path, "a file list with no closing )".to_owned()))
}
fn skip_list(path: &Path, lex: &mut Lexer<'_>) -> Result<()> {
expect_open(path, lex)?;
while let Some(token) = lex.next_token(path)? {
if matches!(token, Token::Close) {
return Ok(());
}
}
Err(refuse(path, "a directive with no closing )".to_owned()))
}
fn expect_open(path: &Path, lex: &mut Lexer<'_>) -> Result<()> {
match lex.next_token(path)? {
Some(Token::Open) => Ok(()),
_ => Err(refuse(path, "a directive with no ( after it".to_owned())),
}
}
fn unimplemented(path: &Path, word: &str) -> Error {
refuse(
path,
format!(
"`{word}` is not implemented: this linker reads a script for the \
inputs it names (INPUT, GROUP, AS_NEEDED) and refuses one that \
describes the image, rather than ignoring it and producing \
something else"
),
)
}
fn refuse(path: &Path, what: String) -> Error {
Error::script(path.display().to_string(), what)
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum Token<'a> {
Open,
Close,
Word(&'a str),
}
struct Lexer<'a> {
rest: &'a str,
}
impl<'a> Lexer<'a> {
const fn new(text: &'a str) -> Self {
Self { rest: text }
}
fn next_token(&mut self, path: &Path) -> Result<Option<Token<'a>>> {
self.skip_trivia(path)?;
let Some(ch) = self.rest.chars().next() else {
return Ok(None);
};
match ch {
'(' => Ok(Some(self.punct(Token::Open))),
')' => Ok(Some(self.punct(Token::Close))),
'"' => self.quoted(path).map(|word| Some(Token::Word(word))),
_ => Ok(Some(Token::Word(self.word()))),
}
}
fn punct(&mut self, token: Token<'a>) -> Token<'a> {
self.rest = self.rest.get(1..).unwrap_or("");
token
}
fn skip_trivia(&mut self, path: &Path) -> Result<()> {
while !self.rest.is_empty() {
let trimmed = self.rest.trim_start_matches(is_separator);
let Some(body) = trimmed.strip_prefix("/*") else {
self.rest = trimmed;
return Ok(());
};
let Some(end) = body.find("*/") else {
return Err(refuse(path, "a /* comment with no */".to_owned()));
};
self.rest = body.get(end.saturating_add(2)..).unwrap_or("");
}
Ok(())
}
fn word(&mut self) -> &'a str {
let text = self.rest;
let end = text
.char_indices()
.find(|&(i, ch)| {
is_separator(ch)
|| ch == '('
|| ch == ')'
|| text.get(i..).is_some_and(|t| t.starts_with("/*"))
})
.map_or(text.len(), |(i, _)| i);
self.rest = text.get(end..).unwrap_or("");
text.get(..end).unwrap_or(text)
}
fn quoted(&mut self, path: &Path) -> Result<&'a str> {
let body = self.rest.get(1..).unwrap_or("");
let Some(end) = body.find('"') else {
return Err(refuse(path, "an unterminated quoted name".to_owned()));
};
self.rest = body.get(end.saturating_add(1)..).unwrap_or("");
Ok(body.get(..end).unwrap_or(""))
}
}
fn is_separator(ch: char) -> bool {
ch.is_whitespace() || ch == ',' || ch == ';'
}