use crate::error::Error;
use crate::predicate::{Leaf, MetaMask, required_fields};
use crate::ring::{CompletionRing, Decision, DecisionToken, SqOp, SubmissionQueue};
use crate::syntax::anchor::literal_of;
use crate::syntax::dialect::Dialect;
use crate::syntax::parse::{Anchor, parse};
use crate::syntax::set::CompiledPattern;
use crate::syntax::{CaseSensitivity, CodePoint, Pattern, PatternSegment};
use std::ffi::OsStr;
use std::path::{Path, PathBuf};
use std::sync::Arc;
#[cfg(test)]
mod tests;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Root {
pub path: PathBuf,
}
impl Root {
pub fn new(path: impl Into<PathBuf>) -> Self {
Self { path: path.into() }
}
}
#[derive(Clone, Debug)]
pub struct PatternEntry {
pub glob: CompiledPattern,
pub emit: Vec<Leaf>,
pub roots: Vec<usize>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum FollowLinks {
#[default]
Never,
Always,
}
#[derive(Clone, Copy, Debug)]
pub struct Options {
pub permits: usize,
pub ring_capacity: usize,
pub cycle_detection: bool,
pub follow_links: FollowLinks,
pub default_case: Option<CaseSensitivity>,
pub confine_to_roots: bool,
}
impl Default for Options {
fn default() -> Self {
Self {
permits: 64,
ring_capacity: 1024,
cycle_detection: true,
follow_links: FollowLinks::Never,
default_case: None,
confine_to_roots: false,
}
}
}
#[derive(Clone, Debug)]
pub struct Query {
pub roots: Vec<Root>,
pub patterns: Vec<PatternEntry>,
pub descend: Vec<Leaf>,
pub result_shape: MetaMask,
pub options: Options,
}
impl Query {
pub fn fetch_mask(&self) -> MetaMask {
let mut mask = self.result_shape | required_fields(&self.descend);
for p in &self.patterns {
mask |= required_fields(&p.emit);
}
mask
}
}
pub struct QueryHandle {
completions: Arc<CompletionRing>,
submissions: Arc<SubmissionQueue>,
roots: Box<[PathBuf]>,
_engine: crate::engine::EngineHandle,
}
impl QueryHandle {
pub fn completions(&self) -> &Arc<CompletionRing> {
&self.completions
}
pub fn submissions(&self) -> &Arc<SubmissionQueue> {
&self.submissions
}
pub fn roots(&self) -> &[PathBuf] {
&self.roots
}
pub fn cancel(&self) {
self.submissions.submit(SqOp::Cancel);
}
pub fn answer(&self, token: DecisionToken, decision: Decision) {
self.submissions
.submit(SqOp::DecisionAnswer { token, decision });
}
}
#[derive(Clone, Debug)]
struct PendingPattern {
text: String,
dialect: Dialect,
emit: Vec<Leaf>,
case: Option<CaseSensitivity>,
}
#[derive(Clone, Debug, Default)]
pub struct QueryBuilder {
roots: Vec<PathBuf>,
base: Option<PathBuf>,
patterns: Vec<PendingPattern>,
descend: Vec<Leaf>,
result_shape: MetaMask,
options: Options,
}
impl QueryBuilder {
pub fn new() -> Self {
Self::default()
}
pub fn root(mut self, path: impl Into<PathBuf>) -> Self {
self.roots.push(path.into());
self
}
pub fn base(mut self, path: impl Into<PathBuf>) -> Self {
self.base = Some(path.into());
self
}
pub fn pattern(mut self, text: &str, dialect: Dialect, emit: Vec<Leaf>) -> Self {
self.patterns.push(PendingPattern {
text: text.to_string(),
dialect,
emit,
case: None,
});
self
}
pub fn pattern_cased(
mut self,
text: &str,
dialect: Dialect,
case: CaseSensitivity,
emit: Vec<Leaf>,
) -> Self {
self.patterns.push(PendingPattern {
text: text.to_string(),
dialect,
emit,
case: Some(case),
});
self
}
pub fn descend(mut self, leaves: Vec<Leaf>) -> Self {
self.descend = leaves;
self
}
pub fn follow_links(mut self, policy: FollowLinks) -> Self {
self.options.follow_links = policy;
self
}
pub fn confine_to_roots(mut self, confine: bool) -> Self {
self.options.confine_to_roots = confine;
self
}
pub fn result_shape(mut self, mask: MetaMask) -> Self {
self.result_shape = mask;
self
}
pub fn options(mut self, options: Options) -> Self {
self.options = options;
self
}
pub fn build(self) -> Result<Query, Error> {
if self.patterns.is_empty() {
return Err(Error::Pattern("query has no patterns".into()));
}
if self.options.ring_capacity == 0 {
return Err(Error::Options("ring_capacity must be non-zero".into()));
}
let mut roots: Vec<Root> = Vec::new();
let mut root_keys: Vec<RootKey> = Vec::new();
for r in &self.roots {
intern_root(&mut roots, &mut root_keys, Root::new(r.clone()))?;
}
let explicit_roots = roots.len();
for i in 0..explicit_roots {
for j in 0..explicit_roots {
if i != j && is_ancestor(&root_keys[i], &root_keys[j]) {
return Err(Error::Options(format!(
"root `{}` is nested under root `{}`; supply only one (D-73)",
roots[j].path.display(),
roots[i].path.display()
)));
}
}
}
let mut patterns: Vec<PatternEntry> = Vec::new();
let mut has_relative = false;
for pend in &self.patterns {
if !pend.dialect.is_supported() {
return Err(Error::Pattern(format!(
"dialect `{}` is not supported on this platform",
pend.dialect.id()
)));
}
let parsed = parse(&pend.text, pend.dialect)?;
let case = pend
.case
.or(self.options.default_case)
.unwrap_or_else(|| pend.dialect.default_case());
let (relative, anchor, pattern_roots) = match parsed.anchor {
Anchor::Relative => {
has_relative = true;
(
parsed.pattern,
Anchor::Relative,
(0..explicit_roots).collect::<Vec<usize>>(),
)
}
other => {
let (root, relative) = lower_self_rooting(other, parsed.pattern, &self.base)?;
let idx = intern_root(&mut roots, &mut root_keys, root)?;
(relative, other, vec![idx])
}
};
patterns.push(PatternEntry {
glob: CompiledPattern {
pattern: relative,
anchor,
dialect: pend.dialect,
case,
},
emit: pend.emit.clone(),
roots: pattern_roots,
});
}
if has_relative && explicit_roots == 0 {
return Err(Error::Pattern(
"relative pattern needs a root; call `.root(..)`".into(),
));
}
if roots.is_empty() {
return Err(Error::Pattern("query has no roots".into()));
}
Ok(Query {
roots,
patterns,
descend: self.descend,
result_shape: self.result_shape,
options: self.options,
})
}
pub fn submit(self) -> Result<QueryHandle, Error> {
let ring_capacity = self.options.ring_capacity;
let query = self.build()?;
let roots: Box<[PathBuf]> = query.roots.iter().map(|r| r.path.clone()).collect();
let completions = Arc::new(CompletionRing::with_capacity(ring_capacity));
let submissions = Arc::new(SubmissionQueue::new());
let engine =
crate::engine::spawn(query, Arc::clone(&completions), Arc::clone(&submissions));
Ok(QueryHandle {
completions,
submissions,
roots,
_engine: engine,
})
}
}
fn intern_root(roots: &mut Vec<Root>, keys: &mut Vec<RootKey>, root: Root) -> Result<usize, Error> {
let key = canon_key(&root.path)?;
if let Some(i) = keys.iter().position(|k| *k == key) {
return Ok(i);
}
keys.push(key);
roots.push(root);
Ok(roots.len() - 1)
}
type RootKey = Vec<Vec<CodePoint>>;
fn canon_key(path: &Path) -> Result<RootKey, Error> {
use std::path::Component;
if !path.is_absolute() {
return Err(Error::Options(format!(
"root must be an absolute path, got `{}` — resolve relative roots at your \
edge (e.g. `std::env::current_dir()?`) before passing them (D-74)",
path.display()
)));
}
let mut key = RootKey::new();
for comp in path.components() {
match comp {
Component::CurDir => {}
Component::ParentDir => {
return Err(Error::Options("`..` is not allowed in a root path".into()));
}
other => key.push(fold_component(other.as_os_str())),
}
}
Ok(key)
}
fn fold_component(os: &OsStr) -> Vec<CodePoint> {
let cps = crate::sys::decode_name(os);
if cfg!(windows) {
cps.into_iter().map(crate::syntax::matcher::fold).collect()
} else {
cps
}
}
fn is_ancestor(a: &RootKey, b: &RootKey) -> bool {
a.len() < b.len() && b[..a.len()] == a[..]
}
fn lower_self_rooting(
anchor: Anchor,
pattern: Pattern,
base: &Option<PathBuf>,
) -> Result<(Root, Pattern), Error> {
let mut root = match anchor {
Anchor::Root => {
match base {
Some(b) => {
if !b.is_absolute() {
return Err(Error::Pattern(
"a base for a leading-separator pattern must be an absolute \
path (D-32)"
.into(),
));
}
root_of(b)
}
None => {
if cfg!(windows) {
return Err(Error::Pattern(
"a leading-separator pattern is current-drive-relative on \
Windows; supply an absolute `.base(...)` (D-32)"
.into(),
));
}
PathBuf::from(std::path::MAIN_SEPARATOR_STR)
}
}
}
Anchor::Drive(c) => PathBuf::from(format!("{c}:\\")),
Anchor::Unc => PathBuf::from(r"\\"),
Anchor::Relative => unreachable!("relative handled by caller"),
};
let segments = pattern.segments;
let mut rest_start = 0usize;
if matches!(anchor, Anchor::Unc) {
let server = literal_segment(&segments, 0)
.ok_or_else(|| Error::Pattern("UNC pattern requires a literal server name".into()))?;
let share = literal_segment(&segments, 1)
.ok_or_else(|| Error::Pattern("UNC pattern requires a literal share name".into()))?;
root.push(server);
root.push(share);
rest_start = 2;
}
while rest_start + 1 < segments.len() {
let Some(lit) = literal_segment(&segments, rest_start) else {
break;
};
root.push(lit);
rest_start += 1;
}
let relative = Pattern {
segments: segments[rest_start..].to_vec(),
};
Ok((Root::new(root), relative))
}
fn root_of(path: &std::path::Path) -> PathBuf {
use std::path::Component;
let mut root = PathBuf::new();
for comp in path.components() {
match comp {
Component::Prefix(_) | Component::RootDir => root.push(comp.as_os_str()),
_ => break,
}
}
if root.as_os_str().is_empty() {
PathBuf::from(std::path::MAIN_SEPARATOR_STR)
} else {
root
}
}
fn literal_segment(segments: &[PatternSegment], idx: usize) -> Option<String> {
match segments.get(idx)? {
PatternSegment::Match(seg) => literal_of(seg).map(|cps| code_points_to_string(&cps)),
PatternSegment::DoubleStar => None,
}
}
fn code_points_to_string(cps: &[CodePoint]) -> String {
cps.iter()
.map(|&c| char::from_u32(c).unwrap_or('\u{FFFD}'))
.collect()
}