inference-engine 0.1.0-alpha.14

Native Rust RDF inference engine with a shared command-line interface
Documentation
use crate::reasoning::ExecutionProfile;
use clap::{Parser, ValueEnum};
use std::{
    num::{NonZeroU32, NonZeroU64, NonZeroUsize},
    path::PathBuf,
};
#[derive(Clone, Copy, Debug, ValueEnum, PartialEq)]
pub(super) enum Format {
    Nt,
    Nq,
    Ttl,
    Trig,
}
impl Format {
    pub fn from_path(path: &std::path::Path) -> anyhow::Result<Self> {
        match path
            .extension()
            .and_then(|s| s.to_str())
            .map(str::to_ascii_lowercase)
            .as_deref()
        {
            Some("nt") => Ok(Self::Nt),
            Some("nq") => Ok(Self::Nq),
            Some("ttl") => Ok(Self::Ttl),
            Some("trig") => Ok(Self::Trig),
            _ => anyhow::bail!(
                "unknown RDF format for {}; use .nt/.nq/.ttl/.trig or an explicit format",
                path.display()
            ),
        }
    }
    pub fn rdf(self) -> oxrdfio::RdfFormat {
        match self {
            Self::Nt => oxrdfio::RdfFormat::NTriples,
            Self::Nq => oxrdfio::RdfFormat::NQuads,
            Self::Ttl => oxrdfio::RdfFormat::Turtle,
            Self::Trig => oxrdfio::RdfFormat::TriG,
        }
    }
}
#[derive(Clone, Copy, Debug, ValueEnum, PartialEq)]
pub(super) enum Emit {
    All,
    Asserted,
    Inferred,
}
#[derive(Parser, Debug)]
#[command(
    name = "inference-engine",
    version,
    about = "Run a restricted RDF/RDFS rule profile over RDF files.",
    after_help = "Turtle/N-Triples inputs share the default graph. Named graphs are isolated.
Output starts only after complete inference and serialization. Diagnostics use stderr.
Profiles are restricted selections, not full RDFS/OWL-RL conformance."
)]
pub(super) struct Args {
    /// One or more RDF files. Use - once for stdin, with --input-format.
    #[arg(required=true,num_args=1..)]
    pub inputs: Vec<PathBuf>,
    /// Exact executable rule selection: rdfs-subclass or rdfs-core.
    #[arg(long)]
    pub profile: ExecutionProfile,
    /// Destination file; defaults to stdout. File replacement is atomic on success.
    #[arg(short, long)]
    pub output: Option<PathBuf>,
    /// Override all input formats; required for stdin.
    #[arg(long, value_enum)]
    pub input_format: Option<Format>,
    /// Output format; defaults to output extension, or nq on stdout.
    #[arg(long, value_enum)]
    pub output_format: Option<Format>,
    /// Which completed facts to emit. Assertions win duplicates.
    #[arg(long, value_enum, default_value = "all")]
    pub emit: Emit,
    /// Explicitly project out generalized tuples that standard RDF cannot represent.
    /// Such tuples still participate in reasoning; their omitted count is reported.
    #[arg(long)]
    pub rdf_only: bool,
    /// Parent directory for an isolated, automatically removed disk scratch database.
    #[arg(long)]
    pub scratch_dir: Option<PathBuf>,
    #[arg(long, default_value = "128")]
    pub max_rounds: NonZeroU32,
    #[arg(long, default_value = "1000000")]
    pub max_inferred: NonZeroU64,
    #[arg(long, default_value = "10000000")]
    pub max_steps: NonZeroU64,
    #[arg(long, default_value = "1073741824")]
    pub max_scratch_bytes: NonZeroU64,
    #[arg(long, default_value = "1073741824")]
    pub max_output_bytes: NonZeroU64,
    /// Total bytes read across all inputs.
    #[arg(long, default_value = "1073741824")]
    pub max_input_bytes: NonZeroU64,
    /// Maximum bytes read per document; this is not a process memory limit.
    #[arg(long, default_value = "67108864")]
    pub max_document_bytes: NonZeroU64,
    #[arg(long, default_value = "1048576")]
    pub max_term_bytes: NonZeroUsize,
    #[arg(long, default_value = "64")]
    pub max_depth: NonZeroU32,
    /// Suppress successful-run statistics; errors are always reported.
    #[arg(short, long)]
    pub quiet: bool,
}

impl Args {
    pub fn validate(&self) -> anyhow::Result<()> {
        let destination = self
            .output
            .as_deref()
            .filter(|p| *p != std::path::Path::new("-"));
        if self.output_format.is_none()
            && let Some(p) = destination
        {
            Format::from_path(p)?;
        }
        if self.inputs.iter().any(|p| p.as_os_str() == "-") && self.input_format.is_none() {
            anyhow::bail!("stdin requires --input-format");
        }
        if let Some(path) = destination {
            let parent = path
                .parent()
                .filter(|p| !p.as_os_str().is_empty())
                .unwrap_or(std::path::Path::new("."));
            if !parent.is_dir() {
                anyhow::bail!("output parent is not a directory: {}", parent.display());
            }
            if path.is_dir() {
                anyhow::bail!("output is a directory: {}", path.display());
            }
            if path.exists() {
                let target = path.canonicalize()?;
                for input in &self.inputs {
                    if input.as_os_str() != "-" && input.canonicalize()? == target {
                        anyhow::bail!("output must not replace an input file");
                    }
                }
            }
        }
        Ok(())
    }
}