OXYGENHUB

Coverage / crates/oxy-core/src/repo/revset.rs 90.0%

592 of 658 lines run, 66 of 146 functions · run #287 on main · run missed

1
//! Evaluating revsets (docs/revset_query_language.md §4) over a repository.
2
//!
3
//! The graph is the change metadata the state index already holds: a
4
//! symbol loads the closure of the heads it names, and `all()`, `X::`,
5
//! `dependents()` and `roots()` load every bookmark, remote bookmark, tag
6
//! and the working copy. Evaluation is read-only and has a time budget;
7
//! a query past it fails and says what to narrow.
8
9
use super::*;
10
use crate::ids::NodeId;
11
use crate::revset::{self, Expr};
12
use crate::state::ChangeMeta;
13
use std::time::{Duration, Instant};
14
15
type Set = BTreeSet<ChangeHash>;
16
17
/// The default budget for a command-line evaluation.
18
pub const REVSET_BUDGET: Duration = Duration::from_secs(10);
19
20
/// A revset's result with the metadata of every change it names.
21
#[derive(Clone, Debug)]
22
pub struct Revset {
23
    /// Newest first, as a log is ordered.
24
    pub hashes: Vec<ChangeHash>,
25
    pub metas: HashMap<ChangeHash, ChangeMeta>,
26
}
27
28
struct Eval<'a> {
29
    repo: &'a Repo,
30
    graph: HashMap<ChangeHash, ChangeMeta>,
31
    /// Which heads have had their closure loaded.
32
    loaded: HashSet<ChangeHash>,
33
    all_loaded: bool,
34
    dependents: Option<HashMap<ChangeHash, Vec<ChangeHash>>>,
35
    names: HashMap<KeyId, Option<(String, String)>>,
36
    /// Who authenticated each change, once asked (signature checks cost).
37
    auth: HashMap<ChangeHash, SignatureStatus>,
38
    deadline: Instant,
39
    budget: Duration,
40
    now_ms: u64,
41
    depth: usize,
42
}
43
445×
fn err(msg: impl Into<String>) -> RepoError {
455×
    RepoError::Msg(msg.into())
465×
}
47
48
impl<'a> Eval<'a> {
49224×
    fn tick(&self) -> Result<()> {
50224×
        if Instant::now() > self.deadline {
511×
            return Err(err(format!(
521×
                "the revset went past its budget of {:.0} s; narrow it with a range such as main.. or a date()",
531×
                self.budget.as_secs_f64()
541×
            )));
55223×
        }
56223×
        Ok(())
57224×
    }
58
59
    /// Load the closure of `heads` into the graph.
6083×
    fn ensure(&mut self, heads: &[ChangeHash]) -> Result<()> {
6183×
        let fresh: Vec<ChangeHash> = heads
6283×
            .iter()
6383×
            .copied()
64211×
            .filter(|h| !self.loaded.contains(h))
6583×
            .collect();
6683×
        if fresh.is_empty() {
679×
            return Ok(());
6874×
        }
69284×
        for (h, m) in self.repo.metas_of(&fresh)? {
70284×
            self.graph.insert(h, m);
71284×
        }
7274×
        self.loaded.extend(fresh);
7374×
        self.dependents = None;
7474×
        self.tick()
7583×
    }
76
77
    /// Load every change the repository names: bookmarks, remote
78
    /// bookmarks, tags, and the working copy.
7925×
    fn load_all(&mut self) -> Result<()> {
8025×
        if self.all_loaded {
810×
            return Ok(());
8225×
        }
8325×
        let view = self.repo.view()?;
8425×
        let mut heads: Vec<ChangeHash> = Vec::new();
8525×
        for st in view.bookmarks.values() {
8625×
            heads.extend(self.repo.store().get_state(st)?.heads);
87
        }
8825×
        for bookmarks in view.remotes.values() {
891×
            for st in bookmarks.values() {
901×
                heads.extend(self.repo.store().get_state(st)?.heads);
91
            }
92
        }
9325×
        for st in view.tags.values() {
944×
            heads.extend(self.repo.store().get_state(st)?.heads);
95
        }
9625×
        if let Some(wc) = self.working_copy() {
9725×
            heads.push(wc);
9825×
        }
9925×
        heads.sort();
10025×
        heads.dedup();
10125×
        self.ensure(&heads)?;
10225×
        self.all_loaded = true;
10325×
        Ok(())
10425×
    }
105
10638×
    fn working_copy(&self) -> Option<ChangeHash> {
10738×
        if self.repo.is_bare() {
1080×
            None
109
        } else {
11038×
            self.repo.working_copy().ok().map(|(h, _)| h)
111
        }
11238×
    }
113
11419×
    fn all(&mut self) -> Result<Set> {
11519×
        self.load_all()?;
11619×
        Ok(self.graph.keys().copied().collect())
11719×
    }
118
1196×
    fn dependents_map(&mut self) -> Result<&HashMap<ChangeHash, Vec<ChangeHash>>> {
1206×
        self.load_all()?;
1216×
        if self.dependents.is_none() {
1226×
            let mut map: HashMap<ChangeHash, Vec<ChangeHash>> = HashMap::new();
12330×
            for (h, m) in &self.graph {
12430×
                for d in &m.deps {
12530×
                    map.entry(*d).or_default().push(*h);
12630×
                }
127
            }
1286×
            self.dependents = Some(map);
1290×
        }
1306×
        Ok(self.dependents.as_ref().unwrap())
1316×
    }
132
133
    /// `::X`: the members and their dependency closures.
13435×
    fn ancestors(&mut self, set: &Set) -> Result<Set> {
13535×
        let mut out = set.clone();
13635×
        let mut stack: Vec<ChangeHash> = set.iter().copied().collect();
13735×
        let mut n = 0usize;
138149×
        while let Some(h) = stack.pop() {
139114×
            if let Some(m) = self.graph.get(&h) {
140114×
                for d in &m.deps {
14166×
                    if out.insert(*d) {
14238×
                        stack.push(*d);
14338×
                    }
144
                }
1450×
            }
146114×
            n += 1;
147114×
            if n.is_multiple_of(4096) {
1480×
                self.tick()?;
149114×
            }
150
        }
15135×
        Ok(out)
15235×
    }
153
154
    /// `X::`: the members and everything that transitively depends on them.
1554×
    fn descendants(&mut self, set: &Set) -> Result<Set> {
1564×
        let mut out = set.clone();
1574×
        let mut stack: Vec<ChangeHash> = set.iter().copied().collect();
1584×
        let deps = self.dependents_map()?;
15918×
        while let Some(h) = stack.pop() {
16014×
            if let Some(ds) = deps.get(&h) {
16113×
                for d in ds {
16213×
                    if out.insert(*d) {
16310×
                        stack.push(*d);
16410×
                    }
165
                }
1664×
            }
167
        }
1684×
        Ok(out)
1694×
    }
170
171
    /// Members no other member depends on, directly or through others.
1722×
    fn heads(&mut self, set: &Set) -> Result<Set> {
1732×
        let mut below: HashSet<ChangeHash> = HashSet::new();
1742×
        let mut stack: Vec<ChangeHash> = set
1752×
            .iter()
1767×
            .filter_map(|h| self.graph.get(h))
1777×
            .flat_map(|m| m.deps.iter().copied())
1782×
            .collect();
1795×
        while let Some(h) = stack.pop() {
1803×
            if below.insert(h) {
1812×
                if let Some(m) = self.graph.get(&h) {
1822×
                    stack.extend(m.deps.iter().copied());
1832×
                }
1841×
            }
185
        }
1867×
        Ok(set.iter().copied().filter(|h| !below.contains(h)).collect())
1872×
    }
188
189
    /// Members that depend on no other member, directly or through others.
1901×
    fn roots(&mut self, set: &Set) -> Result<Set> {
1911×
        let deps = self.dependents_map()?;
1921×
        let mut above: HashSet<ChangeHash> = HashSet::new();
1931×
        let mut stack: Vec<ChangeHash> = set
1941×
            .iter()
1954×
            .filter_map(|h| deps.get(h))
1964×
            .flat_map(|ds| ds.iter().copied())
1971×
            .collect();
1988×
        while let Some(h) = stack.pop() {
1997×
            if above.insert(h) {
2003×
                if let Some(ds) = deps.get(&h) {
2012×
                    stack.extend(ds.iter().copied());
2022×
                }
2034×
            }
204
        }
2054×
        Ok(set.iter().copied().filter(|h| !above.contains(h)).collect())
2061×
    }
207
20846×
    fn symbol(&mut self, name: &str) -> Result<Set> {
20946×
        if name == "@" {
2105×
            let Some(wc) = self.working_copy() else {
2110×
                return Err(err(
2120×
                    "@ names the working copy, and a bare repository has none",
2130×
                ));
214
            };
2155×
            self.ensure(&[wc])?;
2165×
            return Ok([wc].into_iter().collect());
21741×
        }
21841×
        let heads = self.repo.resolve_heads(name)?;
21940×
        self.ensure(&heads)?;
22040×
        Ok(heads.into_iter().collect())
22146×
    }
222
223
    /// The identity's name and email, if its object is known.
2245×
    fn who(&mut self, key: &KeyId) -> Option<(String, String)> {
2255×
        if let Some(w) = self.names.get(key) {
2260×
            return w.clone();
2275×
        }
2285×
        let w = self.repo.identity(key).ok().map(|id| (id.name, id.email));
2295×
        self.names.insert(*key, w.clone());
2305×
        w
2315×
    }
232
233
    /// The set a predicate ranges over: what it is intersected with when
234
    /// that is known, else everything.
23531×
    fn universe(&mut self, within: Option<&Set>) -> Result<Set> {
23631×
        match within {
23712×
            Some(s) => Ok(s.clone()),
23819×
            None => self.all(),
239
        }
24031×
    }
241
2425×
    fn filter_metas(
2435×
        &mut self,
2445×
        within: Option<&Set>,
2455×
        mut keep: impl FnMut(&ChangeHash, &ChangeMeta) -> bool,
2465×
    ) -> Result<Set> {
2475×
        let candidates = self.universe(within)?;
2485×
        let mut out = Set::new();
24924×
        for (i, h) in candidates.iter().enumerate() {
25024×
            if let Some(m) = self.graph.get(h) {
25124×
                if keep(h, m) {
2527×
                    out.insert(*h);
25317×
                }
2540×
            }
25524×
            if i % 8192 == 8191 {
2560×
                self.tick()?;
25724×
            }
258
        }
2595×
        Ok(out)
2605×
    }
261
262
    /// Changes touching any node whose path matches `glob` in the
263
    /// evaluation state: the working copy's base, or the bookmark's state
264
    /// in a bare repository. Nodes keep their identity through renames.
2655×
    fn touches(&mut self, within: Option<&Set>, glob: &str) -> Result<Set> {
2665×
        let matcher = globset::GlobBuilder::new(glob)
2675×
            .literal_separator(false)
2685×
            .build()
2695×
            .map_err(|e| err(format!("touches({glob:?}): {e}")))?
2705×
            .compile_matcher();
271
        // The tree alone names the nodes: no file graph is built. The
272
        // working copy's base comes from the workspace's state index.
2735×
        let state = match self.working_copy() {
2745×
            Some(wc) => {
2755×
                let deps = self
2765×
                    .graph
2775×
                    .get(&wc)
2785×
                    .map(|m| m.deps.clone())
2795×
                    .or_else(|| self.repo.working_copy().ok().map(|(_, c)| c.deps))
2805×
                    .unwrap_or_default();
2815×
                self.repo.load_state_indexed(&deps)?
282
            }
2830×
            None => self.repo.load_state_history(&self.repo.bookmark_heads()?)?,
284
        };
2855×
        let nodes: HashSet<NodeId> = state
2865×
            .tree()
2875×
            .view()
2885×
            .entries
2895×
            .iter()
29038×
            .filter(|(path, _)| matcher.is_match(path))
2915×
            .map(|(_, e)| e.node)
2925×
            .collect();
2935×
        if nodes.is_empty() {
2941×
            return Ok(Set::new());
2954×
        }
2964×
        let candidates = self.universe(within)?;
2974×
        let mut touched = self.repo.touched();
2984×
        touched.fill(self.repo, &candidates.iter().copied().collect::<Vec<_>>());
2994×
        let mut out = Set::new();
30018×
        for (i, h) in candidates.iter().enumerate() {
30118×
            if touched.touches(self.repo, h, &nodes) {
30210×
                out.insert(*h);
30310×
            }
30418×
            if i % 256 == 255 {
3050×
                self.tick()?;
30618×
            }
307
        }
3084×
        touched.save();
3094×
        Ok(out)
3105×
    }
311
31231×
    fn text_arg<'e>(&self, name: &str, args: &'e [Expr], i: usize) -> Result<&'e str> {
31331×
        match args.get(i) {
31431×
            Some(Expr::Symbol(s)) => Ok(s),
3150×
            _ => Err(err(format!("{name}() takes text, quoted if it has spaces"))),
316
        }
31731×
    }
318
31950×
    fn arity(&self, name: &str, args: &[Expr], n: usize) -> Result<()> {
32050×
        if args.len() != n {
3210×
            return Err(err(format!(
322
                "{name}() takes {n} argument{}, not {}",
3230×
                if n == 1 { "" } else { "s" },
3240×
                args.len()
325
            )));
32650×
        }
32750×
        Ok(())
32850×
    }
329
33055×
    fn call(&mut self, name: &str, args: &[Expr], within: Option<&Set>) -> Result<Set> {
33155×
        match name {
33255×
            "all" => {
3332×
                self.arity(name, args, 0)?;
3342×
                self.universe(within)
335
            }
33653×
            "none" => {
3371×
                self.arity(name, args, 0)?;
3381×
                Ok(Set::new())
339
            }
34052×
            "deps" => {
3411×
                self.arity(name, args, 1)?;
3421×
                let x = self.eval(&args[0], None)?;
3431×
                let mut out = Set::new();
3443×
                for h in &x {
3453×
                    if let Some(m) = self.graph.get(h) {
3463×
                        out.extend(m.deps.iter().copied());
3473×
                    }
348
                }
3491×
                Ok(out)
350
            }
35151×
            "dependents" => {
3521×
                self.arity(name, args, 1)?;
3531×
                let x = self.eval(&args[0], None)?;
3541×
                let deps = self.dependents_map()?;
3551×
                let mut out = Set::new();
3561×
                for h in &x {
3571×
                    if let Some(ds) = deps.get(h) {
3581×
                        out.extend(ds.iter().copied());
3591×
                    }
360
                }
3611×
                Ok(out)
362
            }
36350×
            "heads" => {
3642×
                self.arity(name, args, 1)?;
3652×
                let x = self.eval(&args[0], None)?;
3662×
                self.heads(&x)
367
            }
36848×
            "roots" => {
3691×
                self.arity(name, args, 1)?;
3701×
                let x = self.eval(&args[0], None)?;
3711×
                self.roots(&x)
372
            }
37347×
            "independent" => {
3742×
                self.arity(name, args, 2)?;
3752×
                let x = self.eval(&args[0], None)?;
3762×
                let inn = self.eval(&args[1], None)?;
3772×
                let below = self.ancestors(&x)?;
3782×
                let above = self.descendants(&x)?;
3792×
                Ok(inn
3802×
                    .into_iter()
3819×
                    .filter(|h| !below.contains(h) && !above.contains(h))
3822×
                    .collect())
383
            }
38445×
            "conflicts" => {
3854×
                if args.len() > 1 {
3860×
                    return Err(err(
3870×
                        "conflicts() takes a state, or nothing for the working copy's",
3880×
                    ));
3894×
                }
3904×
                let heads: Vec<ChangeHash> = match args.first() {
3911×
                    Some(e) => self.eval(e, None)?.into_iter().collect(),
3923×
                    None => match self.working_copy() {
3933×
                        Some(wc) => {
3943×
                            self.ensure(&[wc])?;
3953×
                            self.graph
3963×
                                .get(&wc)
3973×
                                .map(|m| m.deps.clone())
3983×
                                .unwrap_or_default()
399
                        }
4000×
                        None => self.repo.bookmark_heads()?,
401
                    },
402
                };
4034×
                self.conflicts(within, &heads)
404
            }
40541×
            "latest" => {
4061×
                self.arity(name, args, 2)?;
4071×
                let x = self.eval(&args[0], None)?;
4081×
                let n: usize = self
4091×
                    .text_arg(name, args, 1)?
4101×
                    .parse()
4111×
                    .map_err(|_| err("latest(X, n) takes a count"))?;
4121×
                let mut members: Vec<ChangeHash> = x.into_iter().collect();
4131×
                self.sort_newest_first(&mut members);
4141×
                Ok(members.into_iter().take(n).collect())
415
            }
41640×
            "author" => {
4177×
                self.arity(name, args, 1)?;
4187×
                let who = self.text_arg(name, args, 0)?.to_string();
4197×
                let mut matches: HashMap<KeyId, bool> = HashMap::new();
42027×
                self.filter_metas_with(within, |ev, _, m| {
42127×
                    if let Some(hit) = matches.get(&m.author) {
42220×
                        return *hit;
4237×
                    }
4247×
                    let hit = ev.names_key(&who, &m.author);
4257×
                    matches.insert(m.author, hit);
4267×
                    hit
42727×
                })
428
            }
42933×
            "description" => {
4302×
                self.arity(name, args, 1)?;
4312×
                let text = self.text_arg(name, args, 0)?.to_string();
4322×
                if text.starts_with("re:") {
4330×
                    return Err(err(
4340×
                        "description(re:…) is not supported yet; give a substring",
4350×
                    ));
4362×
                }
4372×
                let needle = text.to_lowercase();
43810×
                self.filter_metas(within, |_, m| m.message.to_lowercase().contains(&needle))
439
            }
44031×
            "date" => {
4412×
                self.arity(name, args, 1)?;
4422×
                let range = revset::parse_date_range(self.text_arg(name, args, 0)?, self.now_ms)
4432×
                    .map_err(err)?;
4449×
                self.filter_metas(within, |_, m| range.contains(m.hlc.wall_ms))
445
            }
44629×
            "kind" => {
4471×
                self.arity(name, args, 1)?;
4481×
                let kind = match self.text_arg(name, args, 0)? {
4491×
                    "normal" => ChangeKind::Normal,
4501×
                    "resolution" => ChangeKind::Resolution,
4511×
                    "working-copy" | "working_copy" => ChangeKind::WorkingCopy,
4520×
                    other => {
4530×
                        return Err(err(format!(
4540×
                            "kind({other:?}): use normal, resolution or working-copy"
4550×
                        )))
456
                    }
457
                };
4585×
                self.filter_metas(within, |_, m| m.kind == kind)
459
            }
46028×
            "touches" => {
4615×
                self.arity(name, args, 1)?;
4625×
                let glob = self.text_arg(name, args, 0)?.to_string();
4635×
                self.touches(within, &glob)
464
            }
465
            // Trust (§2.4): what authenticated a change, and what vouched
466
            // for the states it is in.
46723×
            "signed_by" => {
4685×
                self.arity(name, args, 1)?;
4695×
                let who = self.text_arg(name, args, 0)?.to_string();
47025×
                self.filter_metas_with(within, |ev, h, m| match ev.auth(h, m) {
4714×
                    SignatureStatus::Valid { key, .. } => ev.names_key(&who, &key),
47221×
                    _ => false,
47325×
                })
474
            }
47518×
            "delegated" => {
4762×
                self.arity(name, args, 0)?;
4778×
                self.filter_metas_with(within, |ev, h, m| {
4788×
                    !m.author.is_zero()
4798×
                        && matches!(ev.auth(h, m), SignatureStatus::Valid { key, .. } if key != m.author)
4808×
                })
481
            }
48216×
            "unsigned" => {
4833×
                self.arity(name, args, 0)?;
48410×
                self.filter_metas_with(within, |ev, h, m| {
48510×
                    m.kind != ChangeKind::WorkingCopy
48610×
                        && !matches!(ev.auth(h, m), SignatureStatus::Valid { .. })
48710×
                })
488
            }
48913×
            "revoked" => {
4903×
                self.arity(name, args, 0)?;
49111×
                self.filter_metas_with(within, |ev, h, m| {
49211×
                    matches!(ev.auth(h, m), SignatureStatus::Valid { revoked: true, .. })
49311×
                })
494
            }
49510×
            "attested" => {
4965×
                self.arity(name, args, 1)?;
4975×
                let kind = self.text_arg(name, args, 0)?.to_string();
4985×
                self.attested(within, &kind)
499
            }
500
            // A bookmark's heads by name: what a bare bookmark symbol means,
501
            // without falling through to tags and change prefixes.
5025×
            "bookmark" => {
5032×
                self.arity(name, args, 1)?;
5042×
                let b = self.text_arg(name, args, 0)?;
5052×
                let view = self.repo.view()?;
5062×
                let st = match view.bookmarks.get(b) {
5071×
                    Some(st) => *st,
5081×
                    None => match remote_bookmark(&view, b) {
5090×
                        Some((_, _, st)) => st,
5101×
                        None => return Err(err(format!("bookmark({b}): no such bookmark"))),
511
                    },
512
                };
5131×
                let heads = self.repo.store().get_state(&st)?.heads;
5141×
                self.ensure(&heads)?;
5151×
                Ok(heads.into_iter().collect())
516
            }
5173×
            "built" => {
5181×
                self.arity(name, args, 1)?;
5191×
                let job = self.text_arg(name, args, 0)?.to_string();
5201×
                self.built(within, &job)
521
            }
5222×
            other => {
523
                // A saved revset: `oxy config revset.NAME 'EXPR'` makes NAME().
5242×
                if let Some(saved) = self.repo.config.revsets.get(other).cloned() {
5251×
                    self.arity(name, args, 0)?;
5261×
                    if self.depth >= 16 {
5270×
                        return Err(err(format!("revset.{other} refers to itself")));
5281×
                    }
5291×
                    let e = revset::parse(&saved)
5301×
                        .map_err(|e| err(format!("revset.{other} = {saved:?}: {e}")))?;
5311×
                    self.depth += 1;
5321×
                    let r = self.eval(&e, within);
5331×
                    self.depth -= 1;
5341×
                    return r;
5351×
                }
5361×
                Err(err(format!(
5371×
                    "unknown function {other}(); see docs/revset_query_language.md"
5381×
                )))
539
            }
540
        }
54155×
    }
542
543
    /// The authentication of a change: its signature or seal, checked once.
54454×
    fn auth(&mut self, h: &ChangeHash, m: &ChangeMeta) -> SignatureStatus {
54554×
        if let Some(s) = self.auth.get(h) {
5461×
            return s.clone();
54753×
        }
54853×
        let s = self
54953×
            .repo
55053×
            .authenticate_change_known(h, Some(m))
55153×
            .unwrap_or_else(|e| SignatureStatus::Invalid(e.to_string()));
55253×
        self.auth.insert(*h, s.clone());
55353×
        s
55454×
    }
555
556
    /// Whether `who` names key `key`: by hex prefix, `me`, or the name or
557
    /// email of its identity.
55811×
    fn names_key(&mut self, who: &str, key: &KeyId) -> bool {
55911×
        (who == "me" && Some(*key) == self.repo.config.author_key)
5607×
            || key.starts_with_hex(who)
5615×
            || self.who(key).is_some_and(|(n, e)| {
5625×
                let needle = who.to_lowercase();
5635×
                n.to_lowercase().contains(&needle) || e.to_lowercase().contains(&needle)
5645×
            })
56511×
    }
566
567
    /// The closure of the states whose heads these are, within `within`.
5685×
    fn closure_of(&mut self, mut heads: Vec<ChangeHash>, within: Option<&Set>) -> Result<Set> {
5695×
        heads.sort();
5705×
        heads.dedup();
5715×
        self.ensure(&heads)?;
5725×
        let set: Set = heads.into_iter().collect();
5735×
        let closure = self.ancestors(&set)?;
5745×
        Ok(match within {
5750×
            Some(w) => closure.intersection(w).copied().collect(),
5765×
            None => closure,
577
        })
5785×
    }
579
580
    /// The closure of every state that carries an attestation of `kind`:
581
    /// `tag` (tagged states), `receipt` (states a runner reported on) or
582
    /// `ref` (states a remote attested, as its tracking bookmarks hold).
5835×
    fn attested(&mut self, within: Option<&Set>, kind: &str) -> Result<Set> {
5845×
        let mut heads: Vec<ChangeHash> = Vec::new();
5855×
        match kind {
5865×
            "tag" => {
5873×
                for t in self.repo.tags()? {
5882×
                    heads.extend(t.heads);
5892×
                }
590
            }
5912×
            "receipt" => {
5921×
                for st in self.repo.store().receipt_states()? {
5930×
                    if let Ok(s) = self.repo.store().get_state(&st) {
5940×
                        heads.extend(s.heads);
5950×
                    }
596
                }
597
            }
5981×
            "ref" => {
5990×
                let view = self.repo.view()?;
6000×
                for bookmarks in view.remotes.values() {
6010×
                    for st in bookmarks.values() {
6020×
                        heads.extend(self.repo.store().get_state(st)?.heads);
603
                    }
604
                }
605
            }
6061×
            other => return Err(err(format!("attested({other:?}): use tag, receipt or ref"))),
607
        }
6084×
        self.closure_of(heads, within)
6095×
    }
610
611
    /// The closure of every state with a valid receipt for Flow job `job`
612
    /// from a runner whose key is not revoked.
6131×
    fn built(&mut self, within: Option<&Set>, job: &str) -> Result<Set> {
6141×
        let mut heads: Vec<ChangeHash> = Vec::new();
6151×
        for st in self.repo.store().receipt_states()? {
6160×
            let Ok(state) = self.repo.store().get_state(&st) else {
6170×
                continue;
618
            };
6190×
            let good = self
6200×
                .repo
6210×
                .receipts(&state.heads)?
6220×
                .into_iter()
6230×
                .any(|r| r.signed.receipt.job_name == job && r.problem.is_none() && !r.revoked);
6240×
            if good {
6250×
                heads.extend(state.heads);
6260×
            }
6270×
            self.tick()?;
628
        }
6291×
        self.closure_of(heads, within)
6301×
    }
631
632
    /// `conflicts(S)`: the changes that contributed atoms to a conflict in
633
    /// the state `heads` name (conflicts belong to states, not changes).
6344×
    fn conflicts(&mut self, within: Option<&Set>, heads: &[ChangeHash]) -> Result<Set> {
6354×
        let state = self.repo.load_state(heads)?;
6364×
        let snapshot = state.materialize();
6374×
        let mut out = Set::new();
63836×
        for f in snapshot.files.values() {
63936×
            if !f.is_conflicted() {
64034×
                continue;
6412×
            }
6422×
            match &f.content {
6432×
                crate::state::FileContent::Text { .. } => {
6442×
                    out.extend(state.conflict_regions(&f.node).contributors);
6452×
                }
6460×
                crate::state::FileContent::Opaque { blobs } => {
6470×
                    out.extend(state.blob_contributors(&f.node, blobs));
6480×
                }
6490×
                crate::state::FileContent::Dir => {}
650
            }
6512×
            self.tick()?;
652
        }
6534×
        self.ensure(heads)?;
6544×
        Ok(match within {
6550×
            Some(w) => out.intersection(w).copied().collect(),
6564×
            None => out,
657
        })
6584×
    }
659
660
    /// `filter_metas` for a test that needs the evaluator (identity lookups).
66120×
    fn filter_metas_with(
66220×
        &mut self,
66320×
        within: Option<&Set>,
66420×
        mut keep: impl FnMut(&mut Eval<'a>, &ChangeHash, &ChangeMeta) -> bool,
66520×
    ) -> Result<Set> {
66620×
        let candidates = self.universe(within)?;
66720×
        let mut out = Set::new();
66881×
        for (i, h) in candidates.iter().enumerate() {
66981×
            if let Some(m) = self.graph.get(h).cloned() {
67081×
                if keep(self, h, &m) {
67136×
                    out.insert(*h);
67245×
                }
6730×
            }
67481×
            if i % 8192 == 8191 {
6750×
                self.tick()?;
67681×
            }
677
        }
67820×
        Ok(out)
67920×
    }
680
681
    /// Whether an expression selects by a property, so that evaluating it
682
    /// within the other side of an intersection saves scanning everything.
68323×
    fn is_predicate(e: &Expr) -> bool {
68423×
        match e {
68513×
            Expr::Call(name, _) => matches!(
68613×
                name.as_str(),
68713×
                "author"
6887×
                    | "description"
6897×
                    | "date"
6906×
                    | "kind"
6916×
                    | "touches"
6925×
                    | "all"
6935×
                    | "signed_by"
6945×
                    | "delegated"
6955×
                    | "unsigned"
6962×
                    | "revoked"
6972×
                    | "attested"
6981×
                    | "built"
6991×
                    | "conflicts"
700
            ),
7010×
            Expr::Intersection(a, b) => Self::is_predicate(a) || Self::is_predicate(b),
7020×
            Expr::Union(a, b) => Self::is_predicate(a) && Self::is_predicate(b),
7030×
            Expr::Difference(a, _) => Self::is_predicate(a),
70410×
            _ => false,
705
        }
70623×
    }
707
708148×
    fn eval(&mut self, e: &Expr, within: Option<&Set>) -> Result<Set> {
709148×
        self.tick()?;
710147×
        match e {
71146×
            Expr::Symbol(s) => self.symbol(s),
71223×
            Expr::Ancestors(x) => {
71323×
                let x = self.eval(x, None)?;
71423×
                self.ancestors(&x)
715
            }
7161×
            Expr::Descendants(x) => {
7171×
                let x = self.eval(x, None)?;
7181×
                self.descendants(&x)
719
            }
7201×
            Expr::Between(x, y) => {
7211×
                let x = self.eval(x, None)?;
7221×
                let y = self.eval(y, None)?;
7231×
                let down = self.descendants(&x)?;
7241×
                let up = self.ancestors(&y)?;
7251×
                Ok(down.intersection(&up).copied().collect())
726
            }
7272×
            Expr::Range(x, y) => {
7282×
                let x = self.eval(x, None)?;
7292×
                let y = self.eval(y, None)?;
7302×
                let from = self.ancestors(&x)?;
7312×
                let to = self.ancestors(&y)?;
7322×
                Ok(to.difference(&from).copied().collect())
733
            }
7343×
            Expr::Union(a, b) => {
7353×
                let mut a = self.eval(a, within)?;
7363×
                a.extend(self.eval(b, within)?);
7373×
                Ok(a)
738
            }
73912×
            Expr::Intersection(a, b) => {
74012×
                let (first, second) = if Self::is_predicate(a) && !Self::is_predicate(b) {
7419×
                    (b, a)
742
                } else {
7433×
                    (a, b)
744
                };
74512×
                let left = self.eval(first, within)?;
74612×
                let right = self.eval(second, Some(&left))?;
74712×
                Ok(left.intersection(&right).copied().collect())
748
            }
7494×
            Expr::Difference(a, b) => {
7504×
                let left = self.eval(a, within)?;
7514×
                let right = self.eval(b, Some(&left))?;
7524×
                Ok(left.difference(&right).copied().collect())
753
            }
75455×
            Expr::Call(name, args) => self.call(name, args, within),
755
        }
756148×
    }
757
75864×
    fn sort_newest_first(&self, hashes: &mut [ChangeHash]) {
759103×
        hashes.sort_by(|a, b| {
760103×
            let (ma, mb) = (self.graph.get(a), self.graph.get(b));
761103×
            mb.map(|m| m.hlc).cmp(&ma.map(|m| m.hlc)).then(b.cmp(a))
762103×
        });
76364×
    }
764
}
765
766
impl Repo {
767
    /// Evaluate a revset within [`REVSET_BUDGET`].
76868×
    pub fn revset(&self, src: &str) -> Result<Revset> {
76968×
        self.revset_with_budget(src, REVSET_BUDGET)
77068×
    }
771
772
    /// Evaluate a revset: the changes it selects, newest first, with
773
    /// their metadata. Read-only. Fails past `budget`.
77469×
    pub fn revset_with_budget(&self, src: &str, budget: Duration) -> Result<Revset> {
77569×
        let expr = revset::parse(src).map_err(|e| err(format!("revset {src:?}: {e}")))?;
77668×
        let mut ev = Eval {
77768×
            repo: self,
77868×
            graph: HashMap::new(),
77968×
            loaded: HashSet::new(),
78068×
            all_loaded: false,
78168×
            dependents: None,
78268×
            names: HashMap::new(),
78368×
            auth: HashMap::new(),
78468×
            deadline: Instant::now() + budget,
78568×
            budget,
78668×
            now_ms: Hlc::now().wall_ms,
78768×
            depth: 0,
78868×
        };
78968×
        let set = ev.eval(&expr, None)?;
79063×
        let mut hashes: Vec<ChangeHash> = set.into_iter().collect();
79163×
        ev.sort_newest_first(&mut hashes);
79263×
        let metas = hashes
79363×
            .iter()
794119×
            .filter_map(|h| ev.graph.get(h).map(|m| (*h, m.clone())))
79563×
            .collect();
79663×
        Ok(Revset { hashes, metas })
79769×
    }
798
799
    /// The log entries a revset selects, newest first. A head of the
800
    /// current bookmark is marked as in `log`.
8012×
    pub fn log_revset(&self, src: &str) -> Result<Vec<LogEntry>> {
8022×
        let r = self.revset(src)?;
8032×
        let heads: BTreeSet<ChangeHash> = self.bookmark_heads()?.into_iter().collect();
8042×
        let wc = if self.is_bare() {
8050×
            None
806
        } else {
8072×
            self.working_copy().ok().map(|(h, _)| h)
808
        };
8092×
        let mut entries: Vec<LogEntry> = r
8102×
            .hashes
8112×
            .iter()
8127×
            .filter_map(|h| {
8137×
                r.metas.get(h).map(|m| LogEntry {
8147×
                    hash: *h,
8157×
                    change: m.clone(),
8167×
                    is_working_copy: Some(*h) == wc,
8177×
                    is_head: heads.contains(h),
8187×
                })
8197×
            })
8202×
            .collect();
821
        // The working copy first, as `log` shows it.
82210×
        entries.sort_by_key(|e| !e.is_working_copy);
8232×
        Ok(entries)
8242×
    }
825
}