shuck-semantic 0.0.43

Semantic analysis model for shell scripts with scopes, bindings, and dataflow
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
use rustc_hash::FxHashMap;
use shuck_ast::{Name, NormalizedCommand};
use shuck_parser::ShellProfile;
use std::path::{Path, PathBuf};

use crate::{PluginResolver, SourcePathResolver};

/// Confidence attached to a provided binding or function contract.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ContractCertainty {
    /// The contract is guaranteed along the observed path.
    Definite,
    /// The contract may apply, but not on every path.
    Possible,
}

impl ContractCertainty {
    pub(crate) fn merge_same_site(self, other: Self) -> Self {
        match (self, other) {
            (Self::Definite, Self::Definite) => Self::Definite,
            _ => Self::Possible,
        }
    }
}

/// Kind of binding described by a contract.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ProvidedBindingKind {
    /// A variable binding.
    Variable,
    /// A function binding.
    Function,
}

/// Whether a file-entry provided binding is definitely initialized on entry.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub enum FileEntryBindingInitialization {
    /// The binding is ambiently available but not guaranteed initialized.
    #[default]
    AmbientOnly,
    /// The binding is definitely initialized at file entry.
    Initialized,
}

impl FileEntryBindingInitialization {
    fn merge_same_site(self, other: Self) -> Self {
        match (self, other) {
            (Self::Initialized, _) | (_, Self::Initialized) => Self::Initialized,
            (Self::AmbientOnly, Self::AmbientOnly) => Self::AmbientOnly,
        }
    }
}

/// One binding provided by an imported file or ambient contract.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ProvidedBinding {
    /// Provided binding name.
    pub name: Name,
    /// Provided binding kind.
    pub kind: ProvidedBindingKind,
    /// Confidence attached to the binding.
    pub certainty: ContractCertainty,
    /// Whether the binding is initialized at file entry.
    pub file_entry_initialization: FileEntryBindingInitialization,
}

impl ProvidedBinding {
    /// Creates a provided binding that is ambiently available but not definitely initialized.
    pub fn new(name: Name, kind: ProvidedBindingKind, certainty: ContractCertainty) -> Self {
        Self {
            name,
            kind,
            certainty,
            file_entry_initialization: FileEntryBindingInitialization::AmbientOnly,
        }
    }

    /// Creates a provided binding that is definitely initialized at file entry.
    pub fn new_file_entry_initialized(
        name: Name,
        kind: ProvidedBindingKind,
        certainty: ContractCertainty,
    ) -> Self {
        Self {
            name,
            kind,
            certainty,
            file_entry_initialization: FileEntryBindingInitialization::Initialized,
        }
    }
}

/// Contract for one provided function.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct FunctionContract {
    /// Function name.
    pub name: Name,
    /// Names the function is expected to read from its caller environment.
    pub required_reads: Vec<Name>,
    /// Bindings the function may provide to its caller or nested analysis.
    pub provided_bindings: Vec<ProvidedBinding>,
    /// Source files that contributed this function contract.
    pub origin_paths: Vec<PathBuf>,
}

impl FunctionContract {
    /// Creates an empty contract for `name`.
    pub fn new(name: Name) -> Self {
        Self {
            name,
            required_reads: Vec::new(),
            provided_bindings: Vec::new(),
            origin_paths: Vec::new(),
        }
    }

    /// Adds a required read if it has not already been recorded.
    pub fn add_required_read(&mut self, name: Name) {
        if !self.required_reads.contains(&name) {
            self.required_reads.push(name);
        }
    }

    /// Adds or merges a provided binding into this function contract.
    pub fn add_provided_binding(&mut self, binding: ProvidedBinding) {
        let mut merged = false;
        for existing in &mut self.provided_bindings {
            if existing.name == binding.name && existing.kind == binding.kind {
                existing.certainty = existing.certainty.merge_same_site(binding.certainty);
                existing.file_entry_initialization = existing
                    .file_entry_initialization
                    .merge_same_site(binding.file_entry_initialization);
                merged = true;
                break;
            }
        }

        if !merged {
            self.provided_bindings.push(binding);
        }
    }

    /// Records a contributing origin path if it has not already been seen.
    pub fn add_origin_path(&mut self, path: PathBuf) {
        if !self.origin_paths.contains(&path) {
            self.origin_paths.push(path);
        }
    }

    pub(crate) fn merge_candidate_contracts(contracts: &[Self]) -> Option<Self> {
        let first = contracts.first()?;
        let mut merged = Self::new(first.name.clone());
        let total = contracts.len();
        let mut provided_counts: FxHashMap<
            (Name, ProvidedBindingKind),
            (usize, bool, FileEntryBindingInitialization),
        > = FxHashMap::default();

        for contract in contracts {
            for name in &contract.required_reads {
                merged.add_required_read(name.clone());
            }
            for binding in &contract.provided_bindings {
                let entry = provided_counts
                    .entry((binding.name.clone(), binding.kind))
                    .or_insert((0, true, FileEntryBindingInitialization::AmbientOnly));
                entry.0 += 1;
                entry.1 &= binding.certainty == ContractCertainty::Definite;
                entry.2 = entry.2.merge_same_site(binding.file_entry_initialization);
            }
            for path in &contract.origin_paths {
                merged.add_origin_path(path.clone());
            }
        }

        for ((name, kind), (present_count, all_definite, initialization)) in provided_counts {
            let certainty = if present_count == total && all_definite {
                ContractCertainty::Definite
            } else {
                ContractCertainty::Possible
            };
            let mut binding = ProvidedBinding::new(name, kind, certainty);
            binding.file_entry_initialization = initialization;
            merged.add_provided_binding(binding);
        }

        Some(merged)
    }
}

/// Aggregate contract applied at file entry before final semantic resolution.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct FileContract {
    /// Names required from the ambient environment before the file runs.
    pub required_reads: Vec<Name>,
    /// Bindings provided by entering the file.
    pub provided_bindings: Vec<ProvidedBinding>,
    /// Functions provided by entering the file.
    pub provided_functions: Vec<FunctionContract>,
    /// Whether the file may consume bindings through external runtime behavior.
    pub externally_consumed_bindings: bool,
    /// Exact binding names consumed through external runtime behavior.
    pub externally_consumed_binding_names: Vec<Name>,
    /// Binding name prefixes consumed through external runtime behavior.
    pub externally_consumed_binding_prefixes: Vec<Name>,
}

/// Build-time collector for file-entry contracts discovered during semantic traversal.
///
/// Implementors can observe the normalized command stream while the semantic
/// builder is already walking the file, then return a contract that should be
/// applied before final reference resolution, dataflow, and call-graph use.
pub trait FileEntryContractCollector {
    /// Observe one simple command after semantic command normalization.
    fn observe_simple_command(&mut self, command: &NormalizedCommand<'_>);

    /// Return the collected file-entry contract, when this file needs one.
    fn finish(&self) -> Option<FileContract>;
}

/// Factory for file-entry collectors used when semantic analysis opens helpers.
///
/// Source-closure summaries analyze sourced files and plugin entrypoints as
/// separate file entries. Callers that derive file-entry contracts from source
/// and path context can provide this factory so each resolved helper gets the
/// same entry-contract treatment as the primary analyzed file.
pub trait FileEntryContractCollectorFactory {
    /// Creates a collector for one helper/plugin file summary.
    fn collector_for_file<'a>(
        &self,
        source: &'a str,
        path: Option<&'a Path>,
        shell_profile: &ShellProfile,
    ) -> Option<Box<dyn FileEntryContractCollector + 'a>>;
}

impl FileContract {
    /// Adds a required read if it has not already been recorded.
    pub fn add_required_read(&mut self, name: Name) {
        if !self.required_reads.contains(&name) {
            self.required_reads.push(name);
        }
    }

    /// Adds or merges a provided binding into the file contract.
    pub fn add_provided_binding(&mut self, binding: ProvidedBinding) {
        let mut merged = false;
        for existing in &mut self.provided_bindings {
            if existing.name == binding.name && existing.kind == binding.kind {
                existing.certainty = existing.certainty.merge_same_site(binding.certainty);
                existing.file_entry_initialization = existing
                    .file_entry_initialization
                    .merge_same_site(binding.file_entry_initialization);
                merged = true;
                break;
            }
        }

        if !merged {
            self.provided_bindings.push(binding);
        }
    }

    /// Marks an exact binding name as externally consumed by this file.
    pub fn add_externally_consumed_binding_name(&mut self, name: Name) {
        if !self
            .externally_consumed_binding_names
            .iter()
            .any(|existing| existing == &name)
        {
            self.externally_consumed_binding_names.push(name);
        }
    }

    /// Marks a binding name prefix as externally consumed by this file.
    pub fn add_externally_consumed_binding_prefix(&mut self, prefix: Name) {
        if !self
            .externally_consumed_binding_prefixes
            .iter()
            .any(|existing| existing == &prefix)
        {
            self.externally_consumed_binding_prefixes.push(prefix);
        }
    }

    /// Adds or merges a provided function into the file contract.
    pub fn add_provided_function(&mut self, function: FunctionContract) {
        let mut merged = false;
        for existing in &mut self.provided_functions {
            if existing.name == function.name {
                for name in &function.required_reads {
                    existing.add_required_read(name.clone());
                }
                for binding in &function.provided_bindings {
                    existing.add_provided_binding(binding.clone());
                }
                for path in &function.origin_paths {
                    existing.add_origin_path(path.clone());
                }
                merged = true;
                break;
            }
        }

        if !merged {
            self.provided_functions.push(function);
        }
    }

    pub(crate) fn merge_candidate_contracts(contracts: &[Self]) -> Self {
        let mut merged = Self::default();
        let total = contracts.len();
        let mut provided_counts: FxHashMap<
            (Name, ProvidedBindingKind),
            (usize, bool, FileEntryBindingInitialization),
        > = FxHashMap::default();
        let mut function_contracts_by_name: FxHashMap<Name, Vec<FunctionContract>> =
            FxHashMap::default();

        for contract in contracts {
            merged.externally_consumed_bindings |= contract.externally_consumed_bindings;
            for name in &contract.externally_consumed_binding_names {
                merged.add_externally_consumed_binding_name(name.clone());
            }
            for prefix in &contract.externally_consumed_binding_prefixes {
                merged.add_externally_consumed_binding_prefix(prefix.clone());
            }
            for name in &contract.required_reads {
                merged.add_required_read(name.clone());
            }
            for binding in &contract.provided_bindings {
                let entry = provided_counts
                    .entry((binding.name.clone(), binding.kind))
                    .or_insert((0, true, FileEntryBindingInitialization::AmbientOnly));
                entry.0 += 1;
                entry.1 &= binding.certainty == ContractCertainty::Definite;
                entry.2 = entry.2.merge_same_site(binding.file_entry_initialization);
            }
            for function in &contract.provided_functions {
                function_contracts_by_name
                    .entry(function.name.clone())
                    .or_default()
                    .push(function.clone());
            }
        }

        for ((name, kind), (present_count, all_definite, initialization)) in provided_counts {
            let certainty = if present_count == total && all_definite {
                ContractCertainty::Definite
            } else {
                ContractCertainty::Possible
            };
            let mut binding = ProvidedBinding::new(name, kind, certainty);
            binding.file_entry_initialization = initialization;
            merged.add_provided_binding(binding);
        }

        for functions in function_contracts_by_name.into_values() {
            if functions.len() != total {
                continue;
            }
            if let Some(function) = FunctionContract::merge_candidate_contracts(&functions) {
                merged.add_provided_function(function);
            }
        }

        merged
    }
}

/// Options that control how a [`crate::SemanticModel`] is built.
pub struct SemanticBuildOptions<'a> {
    /// Path of the file being analyzed, used for source-closure resolution and diagnostics.
    pub source_path: Option<&'a Path>,
    /// Resolver for mapping source-like paths to candidate tracked files.
    pub source_path_resolver: Option<&'a (dyn SourcePathResolver + Send + Sync)>,
    /// Resolver for deriving zsh plugin entrypoints and optional plugin contracts.
    pub plugin_resolver: Option<&'a (dyn PluginResolver + Send + Sync)>,
    /// Precomputed file-entry contract to apply before analysis.
    pub file_entry_contract: Option<FileContract>,
    /// Optional observer that can derive a file-entry contract during traversal.
    pub file_entry_contract_collector: Option<&'a mut dyn FileEntryContractCollector>,
    /// Optional factory for deriving file-entry contracts while summarizing helpers.
    pub file_entry_contract_collector_factory:
        Option<&'a (dyn FileEntryContractCollectorFactory + Send + Sync)>,
    /// Paths already analyzed in the current source-closure walk.
    pub analyzed_paths: Option<&'a rustc_hash::FxHashSet<PathBuf>>,
    /// Explicit shell profile to use instead of inferring one from the source.
    pub shell_profile: Option<ShellProfile>,
    /// Whether sourced-file closure metadata should be resolved and imported.
    pub resolve_source_closure: bool,
}

impl Default for SemanticBuildOptions<'_> {
    fn default() -> Self {
        Self {
            source_path: None,
            source_path_resolver: None,
            plugin_resolver: None,
            file_entry_contract: None,
            file_entry_contract_collector: None,
            file_entry_contract_collector_factory: None,
            analyzed_paths: None,
            shell_profile: None,
            resolve_source_closure: true,
        }
    }
}