litnik 0.2.1

An embedded Lit and FileCheck runner for compiler test suites.
Documentation
use std::fmt;

/// One shell argument after quote removal.
///
/// The glob variants retain which wildcard metacharacters were unquoted in
/// the source. This lets the executor expand a mixed word without treating
/// quoted wildcard characters as patterns.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Arg {
    /// Literal text that is passed to the command unchanged.
    Text(String),
    /// A pathname pattern expanded relative to the shell working directory.
    Glob(String),
    /// Text containing both literal and active wildcard characters.
    MixedGlob {
        /// Argument text after quote and escape processing.
        text: String,
        /// Character offsets of unquoted glob metacharacters.
        active_metacharacters: Vec<usize>,
    },
}

impl Arg {
    /// Borrows the argument text after quote and escape processing.
    pub fn as_str(&self) -> &str {
        match self {
            Arg::Text(v) | Arg::Glob(v) => v,
            Arg::MixedGlob { text, .. } => text,
        }
    }

    /// Consumes the argument and returns its text without expanding globs.
    pub fn into_text(self) -> String {
        match self {
            Arg::Text(v) | Arg::Glob(v) => v,
            Arg::MixedGlob { text, .. } => text,
        }
    }

    /// Parses the argument text without performing pathname expansion.
    ///
    /// # Errors
    ///
    /// Returns the error produced by `T` when the text is not a valid `T`.
    pub fn parse<T: std::str::FromStr>(&self) -> Result<T, T::Err> {
        self.as_str().parse()
    }

    /// Copies the argument text without performing pathname expansion.
    pub fn as_owned_text(&self) -> String {
        self.as_str().to_string()
    }

    pub(crate) fn from_glob_parts(text: String, active_metacharacters: Vec<usize>) -> Self {
        if !active_metacharacters.iter().any(|index| {
            text.chars()
                .nth(*index)
                .is_some_and(|ch| matches!(ch, '*' | '?' | '[' | ']'))
        }) {
            return Self::Text(text);
        }
        let metacharacter_count = text
            .chars()
            .filter(|ch| matches!(ch, '*' | '?' | '[' | ']'))
            .count();
        if metacharacter_count == active_metacharacters.len() {
            Self::Glob(text)
        } else {
            Self::MixedGlob {
                text,
                active_metacharacters,
            }
        }
    }

    pub(crate) fn active_metacharacters(&self) -> Vec<usize> {
        match self {
            Self::Text(_) => Vec::new(),
            Self::Glob(text) => text
                .chars()
                .enumerate()
                .filter_map(|(index, ch)| matches!(ch, '*' | '?' | '[' | ']').then_some(index))
                .collect(),
            Self::MixedGlob {
                active_metacharacters,
                ..
            } => active_metacharacters.clone(),
        }
    }
}

impl From<String> for Arg {
    fn from(value: String) -> Self {
        Self::Text(value)
    }
}

impl From<&str> for Arg {
    fn from(value: &str) -> Self {
        Self::Text(value.to_string())
    }
}

impl PartialEq<String> for Arg {
    fn eq(&self, other: &String) -> bool {
        self.as_str() == other
    }
}

impl PartialEq<Arg> for String {
    fn eq(&self, other: &Arg) -> bool {
        self == other.as_str()
    }
}

impl PartialEq<&str> for Arg {
    fn eq(&self, other: &&str) -> bool {
        self.as_str() == *other
    }
}

impl fmt::Display for Arg {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

/// An ordered redirection attached to a [`Command`].
///
/// `source_fd` identifies the descriptor changed by `op`. Redirections are
/// applied from left to right, including descriptor duplication such as
/// `2>&1`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Redirect {
    /// File descriptor changed by this redirection.
    pub source_fd: usize,
    /// Shell operator, such as `>`, `>>`, `<`, `>&`, or `&>`.
    pub op: String,
    /// File name or descriptor appearing to the right of the operator.
    pub target: Arg,
}

/// A command and its ordered redirections.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Command {
    /// Arguments after quote removal, with pathname-expansion intent retained.
    pub args: Vec<Arg>,
    /// Redirections in source order.
    pub redirects: Vec<Redirect>,
}

/// Commands connected by standard-output pipelines.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Pipeline {
    /// Pipeline stages in execution order.
    pub commands: Vec<Command>,
    /// Whether the final pipeline status is logically negated.
    pub negate: bool,
    /// Whether the last nonzero stage determines a failed pipeline status.
    pub pipe_fail: bool,
}

/// A parsed shell expression consisting of pipelines and sequencing operators.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ScriptNode {
    /// One pipeline, including a single command without `|`.
    Pipeline(Pipeline),
    /// Two expressions joined by a sequencing operator.
    Seq(Box<ScriptNode>, SeqOp, Box<ScriptNode>),
}

/// An operator that controls whether and when the right expression executes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SeqOp {
    /// Execute the right expression after the left expression.
    Semicolon,
    /// The parsed `&` operator.
    ///
    /// The executor rejects this operator because Litnik does not run commands
    /// in the background.
    Ampersand,
    /// Execute the right expression only when the left expression fails.
    Or,
    /// Execute the right expression only when the left expression succeeds.
    And,
}

impl fmt::Display for SeqOp {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let repr = match self {
            SeqOp::Semicolon => ";",
            SeqOp::Ampersand => "&",
            SeqOp::Or => "||",
            SeqOp::And => "&&",
        };
        write!(f, "{repr}")
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn redirect_repr() {
        let r = Redirect {
            source_fd: 1,
            op: ">".into(),
            target: "x".into(),
        };
        assert_eq!(r.source_fd, 1);
        assert_eq!(r.target, "x");
    }
}