Skip to main content

fallow_types/
shared_state.rs

1//! Opt-in syntactic shared-state inventory, independent of counted findings.
2
3use serde::{Deserialize, Serialize};
4use std::path::PathBuf;
5
6/// Which optional facts a parser collects. Normal analysis collects none of them.
7#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
8pub enum ExtractionMode {
9    /// Ordinary extraction.
10    #[default]
11    Standard,
12    /// Include the shared-state inventory facts.
13    SharedState,
14}
15
16/// A direct property operation. Calls are not classified as writes.
17#[derive(
18    Debug,
19    Clone,
20    Copy,
21    PartialEq,
22    Eq,
23    PartialOrd,
24    Ord,
25    Serialize,
26    Deserialize,
27    bitcode::Encode,
28    bitcode::Decode,
29)]
30#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
31#[serde(rename_all = "snake_case")]
32pub enum StateOperation {
33    /// Value read, including a call receiver.
34    Read,
35    /// Simple assignment.
36    Assign,
37    /// Compound or logical assignment, which may read the previous value.
38    ReadModifyWrite,
39    /// Increment or decrement.
40    Update,
41    /// Property deletion.
42    Delete,
43}
44
45/// Binding provenance established by the semantic pass.
46#[derive(Debug, Clone, PartialEq, Eq, Serialize, bitcode::Encode, bitcode::Decode)]
47#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
48#[serde(tag = "kind", rename_all = "snake_case")]
49pub enum StateRoot {
50    /// Index in the containing module's runtime ESM import list.
51    Import {
52        /// Import index, rebased when embedded scripts are merged.
53        import_index: u32,
54    },
55    /// Exact unshadowed global identifier spelling.
56    Global {
57        /// One of window, globalThis, self or global.
58        name: String,
59    },
60}
61
62/// Compact source fact with exact static property segments.
63#[derive(Debug, Clone, PartialEq, Eq, Serialize, bitcode::Encode, bitcode::Decode)]
64#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
65pub struct StateAccessFact {
66    /// Lexically established root.
67    pub root: StateRoot,
68    /// Property segments, preserving a literal dot inside one key.
69    pub path: Vec<String>,
70    /// Direct operation on the full path.
71    pub operation: StateOperation,
72    /// Byte offset in the original source.
73    pub span_start: u32,
74}
75
76/// A retained source location.
77#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
78#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
79#[serde(deny_unknown_fields)]
80pub struct StateSite {
81    /// Project-relative source path.
82    #[serde(serialize_with = "crate::serde_path::serialize")]
83    pub path: PathBuf,
84    /// One-based source line.
85    pub line: usize,
86    /// One-based byte column.
87    pub column: usize,
88    /// Original byte offset.
89    pub offset: u32,
90}
91
92/// Manual review guidance. Inventory observations cannot be automatically fixed.
93#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
94#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
95#[serde(deny_unknown_fields)]
96pub struct StateAction {
97    /// Human-readable next step.
98    pub description: String,
99    /// Always false.
100    pub auto_fixable: bool,
101}
102
103/// A write through an imported value binding with one declaration origin.
104#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
105#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
106#[serde(deny_unknown_fields)]
107pub struct ImportedStateWrite {
108    /// Stable observation identity.
109    pub id: String,
110    /// Writer location.
111    pub writer: StateSite,
112    /// Canonical value declaration, not inferred runtime object ownership.
113    pub declaration: StateSite,
114    /// Canonical exported name.
115    pub binding: String,
116    /// Exact property segments relative to the imported value.
117    pub property: Vec<String>,
118    /// Direct write operation.
119    pub operation: StateOperation,
120    /// Manual guidance.
121    pub actions: Vec<StateAction>,
122}
123
124/// Runtime relationships that static observations cannot establish.
125#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
126#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
127#[serde(rename_all = "snake_case")]
128pub enum UnknownStateRelation {
129    /// No runtime or ordering claim.
130    Unknown,
131}
132
133/// A source access within a global group.
134#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
135#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
136#[serde(deny_unknown_fields)]
137pub struct GlobalStateAccess {
138    /// Source location.
139    pub site: StateSite,
140    /// Full path, including the direct slot.
141    pub property: Vec<String>,
142    /// Direct operation.
143    pub operation: StateOperation,
144}
145
146/// One exact root and custom slot, with retained reads and writes across files.
147#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
148#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
149#[serde(deny_unknown_fields)]
150pub struct GlobalStateGroup {
151    /// Stable observation identity.
152    pub id: String,
153    /// Exact root spelling. Roots are never normalized across runtimes.
154    pub root: String,
155    /// Direct custom slot.
156    pub slot: String,
157    /// Sorted read sites.
158    pub reads: Vec<GlobalStateAccess>,
159    /// Sorted write sites.
160    pub writes: Vec<GlobalStateAccess>,
161    /// Whether the files execute in the same runtime is unknown.
162    pub same_runtime: UnknownStateRelation,
163    /// Execution order is unknown.
164    pub execution_order: UnknownStateRelation,
165    /// Manual guidance.
166    pub actions: Vec<StateAction>,
167}
168
169/// Versioned advisory inventory. Its observations are never counted as findings.
170#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
171#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
172#[serde(deny_unknown_fields)]
173pub struct SharedStateInventory {
174    /// Inventory contract version.
175    #[cfg_attr(feature = "schema", schemars(range(min = 1, max = 1)))]
176    pub version: u32,
177    /// False if source parsing or retention limits omitted supported evidence.
178    pub complete: bool,
179    /// Whether bounded fact retention omitted sites.
180    pub truncated: bool,
181    /// Imported value property writes.
182    pub imported_writes: Vec<ImportedStateWrite>,
183    /// Exact global root/slot groups.
184    pub globals: Vec<GlobalStateGroup>,
185}
186
187/// Combine optional inventories without converting observations into findings.
188pub(crate) fn merge_inventory(
189    target: &mut Option<SharedStateInventory>,
190    other: Option<SharedStateInventory>,
191) {
192    let Some(other) = other else { return };
193    let Some(target) = target else {
194        *target = Some(other);
195        return;
196    };
197    target.complete &= other.complete;
198    target.truncated |= other.truncated;
199    target.imported_writes.extend(other.imported_writes);
200    target
201        .imported_writes
202        .sort_by(|left, right| left.id.cmp(&right.id));
203    target.imported_writes.dedup();
204    // Different project roots do not establish a shared global runtime.
205    target.globals.extend(other.globals);
206    target.globals.sort_by(|left, right| left.id.cmp(&right.id));
207    target.globals.dedup();
208}
209
210impl SharedStateInventory {
211    /// Narrow observations by source site, retaining complete global evidence groups.
212    pub fn retain_sites(&mut self, keep: impl Fn(&StateSite) -> bool) {
213        self.imported_writes.retain(|write| keep(&write.writer));
214        self.globals.retain(|group| {
215            group
216                .reads
217                .iter()
218                .chain(&group.writes)
219                .any(|access| keep(&access.site))
220        });
221    }
222}
223
224impl StateOperation {
225    /// Stable operation spelling used by inventory explanations and identities.
226    #[must_use]
227    pub const fn label(self) -> &'static str {
228        match self {
229            Self::Read => "read",
230            Self::Assign => "assign",
231            Self::ReadModifyWrite => "read_modify_write",
232            Self::Update => "update",
233            Self::Delete => "delete",
234        }
235    }
236}
237
238#[cfg(test)]
239mod tests {
240    use super::*;
241
242    #[test]
243    fn typed_state_sites_normalize_paths_without_changing_property_keys() {
244        let write = ImportedStateWrite {
245            id: "observation".to_owned(),
246            writer: StateSite {
247                path: r"src\writer.ts".into(),
248                line: 2,
249                column: 3,
250                offset: 8,
251            },
252            declaration: StateSite {
253                path: r"src\owner.ts".into(),
254                line: 1,
255                column: 1,
256                offset: 0,
257            },
258            binding: "state".to_owned(),
259            property: vec![r"literal\key".to_owned(), "a.b".to_owned()],
260            operation: StateOperation::Assign,
261            actions: Vec::new(),
262        };
263        let json = serde_json::to_value(&write).unwrap();
264        assert_eq!(json["writer"]["path"], "src/writer.ts");
265        assert_eq!(json["declaration"]["path"], "src/owner.ts");
266        assert_eq!(json["property"], serde_json::json!([r"literal\key", "a.b"]));
267        assert_eq!(json["writer"]["offset"], 8);
268    }
269}