sealmap_extract/raw.rs
1//! The raw flow IR: what a language adapter records while walking a function body,
2//! before any name is resolved.
3//!
4//! Everything here is owned `String`s and `Vec`s (no parser nodes), so files
5//! can be walked in parallel and resolved afterwards in one deterministic
6//! pass. [`lower`](crate::lower) turns it into a model
7//! [`Flow`](sealmap_model::Flow).
8//!
9//! ```
10//! use sealmap_extract::raw::{Callee, RawCall, RawStep, last_call_mut};
11//! use sealmap_model::CallKind;
12//!
13//! let mut out = vec![RawStep::Call(RawCall::new(Callee::Path(vec!["load".into()]), "load()".into(), CallKind::Function, 3))];
14//! // `load()?` — the walker marks the call it just pushed as fallible.
15//! if let Some(RawStep::Call(c)) = last_call_mut(&mut out) {
16//! c.fallible = true;
17//! }
18//! assert!(matches!(&out[0], RawStep::Call(c) if c.fallible));
19//! ```
20
21use sealmap_model::{Call, CallKind, Confidence, SymbolId};
22
23/// Path segments as written, generics stripped: `std::collections::HashMap`
24/// is `["std", "collections", "HashMap"]`.
25pub type Segs = Vec<String>;
26
27/// One step of an unresolved flow.
28#[derive(Debug, Clone, PartialEq, Eq)]
29pub enum RawStep {
30 /// A call.
31 Call(RawCall),
32 /// Alternatives (`if`/`else`, `match`): `(label, steps)` per arm. Empty
33 /// arms are kept so that [`lower`](crate::lower) can describe the arm that
34 /// survives resolution.
35 Branch(Vec<(String, Vec<RawStep>)>),
36 /// A loop with its label and body.
37 Loop(String, Vec<RawStep>),
38 /// A body that may or may not run, with its label.
39 Optional(String, Vec<RawStep>),
40 /// Concurrent arms (spawned tasks): `(label, steps)` per arm.
41 Parallel(Vec<(String, Vec<RawStep>)>),
42 /// An early exit: label and 1-based line.
43 Return(String, u32),
44}
45
46/// An unresolved call.
47#[derive(Debug, Clone, PartialEq, Eq)]
48pub struct RawCall {
49 /// What is called, as written.
50 pub callee: Callee,
51 /// Short message text for diagrams (see
52 /// [`labels::call_label`](crate::labels::call_label)).
53 pub label: String,
54 /// How it is called.
55 pub kind: CallKind,
56 /// Awaited (`.await`).
57 pub awaited: bool,
58 /// Error-propagating (`?`).
59 pub fallible: bool,
60 /// 1-based source line.
61 pub line: u32,
62}
63
64impl RawCall {
65 /// A call that is neither awaited nor fallible (the walker sets those
66 /// flags afterwards, through [`last_call_mut`]).
67 pub fn new(callee: Callee, label: String, kind: CallKind, line: u32) -> Self {
68 Self { callee, label, kind, awaited: false, fallible: false, line }
69 }
70
71 /// The model call for this raw call, once its target is resolved.
72 pub fn to_call(&self, target: SymbolId, confidence: Confidence) -> Call {
73 Call {
74 target,
75 label: self.label.clone(),
76 kind: self.kind,
77 confidence,
78 awaited: self.awaited,
79 fallible: self.fallible,
80 line: self.line,
81 }
82 }
83}
84
85/// The callee of a [`RawCall`].
86#[derive(Debug, Clone, PartialEq, Eq)]
87pub enum Callee {
88 /// `a::b::c(..)`.
89 Path(Segs),
90 /// `recv.name(..)`.
91 Method {
92 /// What the method is called on.
93 recv: Recv,
94 /// Method name.
95 name: String,
96 },
97}
98
99/// What a method is called on, as far as the walker can tell without types.
100#[derive(Debug, Clone, PartialEq, Eq)]
101pub enum Recv {
102 /// `self`.
103 SelfValue,
104 /// `self.field`.
105 SelfField(String),
106 /// A local or parameter whose declared/constructed type mentions these
107 /// paths (outermost first, e.g. `Arc<Db>` → `[Arc], [Db]`).
108 Typed(Vec<Segs>),
109 /// A plain variable or field whose type is not evident. Calls on it may
110 /// be matched to a distinctive internal method name (`inferred`).
111 Untyped,
112 /// The value returned by calling this path (`get_logger()`). Only used
113 /// as the origin of a [`Recv::Derived`] value.
114 Returned(Segs),
115 /// A value of unknown type obtained from another receiver: a part of it
116 /// taken apart by a pattern (`if let Some(x) = origin`, `for x in
117 /// origin`, a `match` arm), possibly through method calls and `?` on
118 /// the way (`origin.lock()`). Calls on it may be matched to a distinctive
119 /// internal method name only when the origin is internal code (`self`,
120 /// an internal type or function); a value derived from a `std` or
121 /// third-party one never is, so `Path::parent()` on a part of an
122 /// `Option<&Path>` is not drawn as a call to an internal `parent`.
123 Derived(Box<Recv>),
124 /// A value computed from this origin and bound by name (`let x =
125 /// origin.call()`). Its type is not evident, so calls on it are not
126 /// resolved or guessed, exactly as for [`Recv::Unknown`]; parts a
127 /// pattern takes from it ([`Recv::Derived`]) keep the origin.
128 Computed(Box<Recv>),
129 /// Anything else (call chains, indexing, literals). Not resolved.
130 Unknown,
131}
132
133/// Push the arms of an `if`/`else if`/`else` chain: nothing if every arm is
134/// empty, an [`RawStep::Optional`] for a lone arm, otherwise a
135/// [`RawStep::Branch`] that keeps its empty arms (lowering drops them after
136/// resolution and uses their labels to describe what remains).
137pub fn push_arms(arms: Vec<(String, Vec<RawStep>)>, out: &mut Vec<RawStep>) {
138 if arms.iter().all(|(_, s)| s.is_empty()) {
139 return;
140 }
141 if arms.len() == 1 {
142 let (label, steps) = arms.into_iter().next().unwrap_or_default();
143 out.push(RawStep::Optional(label, steps));
144 } else {
145 out.push(RawStep::Branch(arms));
146 }
147}
148
149/// The last call pushed at this level (fragments pushed after it, such as a
150/// deferred closure, are skipped over).
151pub fn last_call_mut(out: &mut [RawStep]) -> Option<&mut RawStep> {
152 out.iter_mut().rev().find(|s| matches!(s, RawStep::Call(_)))
153}
154
155/// Place the bodies of closures passed to `callee` after the call itself,
156/// since they run during (not before) it. A `*spawn*` callee makes each body a
157/// parallel task, a callee in `looping` (methods whose closure runs once per
158/// element) makes it a loop, and anything else an optional fragment. The
159/// labels come from [`labels::deferred_label`](crate::labels::deferred_label).
160pub fn place_deferred(callee: &str, deferred: Vec<Vec<RawStep>>, looping: &[&str], out: &mut Vec<RawStep>) {
161 use crate::labels::{DeferredShape, deferred_label, deferred_shape};
162 for steps in deferred {
163 let shape = deferred_shape(callee, looping);
164 let label = deferred_label(callee, shape);
165 out.push(match shape {
166 DeferredShape::Parallel => RawStep::Parallel(vec![(label, steps)]),
167 DeferredShape::Loop => RawStep::Loop(label, steps),
168 DeferredShape::Optional => RawStep::Optional(label, steps),
169 });
170 }
171}
172
173#[cfg(test)]
174mod tests {
175 use super::*;
176
177 fn call(n: &str) -> RawStep {
178 RawStep::Call(RawCall::new(Callee::Path(vec![n.into()]), n.into(), CallKind::Function, 1))
179 }
180
181 #[test]
182 fn push_arms_shapes() {
183 let mut out = Vec::new();
184 push_arms(vec![("a".into(), vec![]), (String::new(), vec![])], &mut out);
185 assert!(out.is_empty());
186 push_arms(vec![("a".into(), vec![call("f")])], &mut out);
187 assert!(matches!(&out[0], RawStep::Optional(l, s) if l == "a" && s.len() == 1));
188 push_arms(vec![("a".into(), vec![call("f")]), (String::new(), vec![])], &mut out);
189 assert!(matches!(&out[1], RawStep::Branch(arms) if arms.len() == 2));
190 }
191
192 #[test]
193 fn deferred_bodies_follow_the_callee_shape() {
194 let mut out = Vec::new();
195 place_deferred("spawn", vec![vec![call("a")]], &["map"], &mut out);
196 place_deferred("map", vec![vec![call("b")]], &["map"], &mut out);
197 place_deferred("with", vec![vec![call("c")]], &["map"], &mut out);
198 place_deferred("", vec![vec![call("d")]], &["map"], &mut out);
199 assert!(matches!(&out[0], RawStep::Parallel(arms) if arms[0].0 == "spawned task"));
200 assert!(matches!(&out[1], RawStep::Loop(l, _) if l == "each via map"));
201 assert!(matches!(&out[2], RawStep::Optional(l, _) if l == "via with"));
202 assert!(matches!(&out[3], RawStep::Optional(l, _) if l == "closure"));
203 }
204}