nu_protocol/engine/
state_working_set.rs

1use crate::{
2    BlockId, Category, CompileError, Config, DeclId, FileId, GetSpan, Module, ModuleId, OverlayId,
3    ParseError, ParseWarning, ResolvedImportPattern, Signature, Span, SpanId, Type, Value, VarId,
4    VirtualPathId,
5    ast::Block,
6    engine::{
7        CachedFile, Command, CommandType, EngineState, OverlayFrame, StateDelta, Variable,
8        VirtualPath, Visibility, description::build_desc,
9    },
10};
11use core::panic;
12use std::{
13    collections::{HashMap, HashSet},
14    path::{Path, PathBuf},
15    sync::Arc,
16};
17
18#[cfg(feature = "plugin")]
19use crate::{PluginIdentity, PluginRegistryItem, RegisteredPlugin};
20
21/// A temporary extension to the global state. This handles bridging between the global state and the
22/// additional declarations and scope changes that are not yet part of the global scope.
23///
24/// This working set is created by the parser as a way of handling declarations and scope changes that
25/// may later be merged or dropped (and not merged) depending on the needs of the code calling the parser.
26pub struct StateWorkingSet<'a> {
27    pub permanent_state: &'a EngineState,
28    pub delta: StateDelta,
29    pub files: FileStack,
30    /// Whether or not predeclarations are searched when looking up a command (used with aliases)
31    pub search_predecls: bool,
32    pub parse_errors: Vec<ParseError>,
33    pub parse_warnings: Vec<ParseWarning>,
34    pub compile_errors: Vec<CompileError>,
35}
36
37impl<'a> StateWorkingSet<'a> {
38    pub fn new(permanent_state: &'a EngineState) -> Self {
39        // Initialize the file stack with the top-level file.
40        let files = if let Some(file) = permanent_state.file.clone() {
41            FileStack::with_file(file)
42        } else {
43            FileStack::new()
44        };
45
46        Self {
47            delta: StateDelta::new(permanent_state),
48            permanent_state,
49            files,
50            search_predecls: true,
51            parse_errors: vec![],
52            parse_warnings: vec![],
53            compile_errors: vec![],
54        }
55    }
56
57    pub fn permanent(&self) -> &EngineState {
58        self.permanent_state
59    }
60
61    pub fn error(&mut self, parse_error: ParseError) {
62        self.parse_errors.push(parse_error)
63    }
64
65    pub fn warning(&mut self, parse_warning: ParseWarning) {
66        self.parse_warnings.push(parse_warning)
67    }
68
69    pub fn num_files(&self) -> usize {
70        self.delta.num_files() + self.permanent_state.num_files()
71    }
72
73    pub fn num_virtual_paths(&self) -> usize {
74        self.delta.num_virtual_paths() + self.permanent_state.num_virtual_paths()
75    }
76
77    pub fn num_vars(&self) -> usize {
78        self.delta.num_vars() + self.permanent_state.num_vars()
79    }
80
81    pub fn num_decls(&self) -> usize {
82        self.delta.num_decls() + self.permanent_state.num_decls()
83    }
84
85    pub fn num_blocks(&self) -> usize {
86        self.delta.num_blocks() + self.permanent_state.num_blocks()
87    }
88
89    pub fn num_modules(&self) -> usize {
90        self.delta.num_modules() + self.permanent_state.num_modules()
91    }
92
93    pub fn unique_overlay_names(&self) -> HashSet<&[u8]> {
94        let mut names: HashSet<&[u8]> = self.permanent_state.active_overlay_names(&[]).collect();
95
96        for scope_frame in self.delta.scope.iter().rev() {
97            for overlay_id in scope_frame.active_overlays.iter().rev() {
98                let (overlay_name, _) = scope_frame
99                    .overlays
100                    .get(overlay_id.get())
101                    .expect("internal error: missing overlay");
102
103                names.insert(overlay_name);
104                names.retain(|n| !scope_frame.removed_overlays.iter().any(|m| n == m));
105            }
106        }
107
108        names
109    }
110
111    pub fn num_overlays(&self) -> usize {
112        self.unique_overlay_names().len()
113    }
114
115    pub fn add_decl(&mut self, decl: Box<dyn Command>) -> DeclId {
116        let name = decl.name().as_bytes().to_vec();
117
118        self.delta.decls.push(decl);
119        let decl_id = self.num_decls() - 1;
120        let decl_id = DeclId::new(decl_id);
121
122        self.last_overlay_mut().insert_decl(name, decl_id);
123
124        decl_id
125    }
126
127    pub fn use_decls(&mut self, decls: Vec<(Vec<u8>, DeclId)>) {
128        let overlay_frame = self.last_overlay_mut();
129
130        for (name, decl_id) in decls {
131            overlay_frame.insert_decl(name, decl_id);
132            overlay_frame.visibility.use_decl_id(&decl_id);
133        }
134    }
135
136    pub fn use_modules(&mut self, modules: Vec<(Vec<u8>, ModuleId)>) {
137        let overlay_frame = self.last_overlay_mut();
138
139        for (name, module_id) in modules {
140            overlay_frame.insert_module(name, module_id);
141            // overlay_frame.visibility.use_module_id(&module_id);  // TODO: Add hiding modules
142        }
143    }
144
145    pub fn use_variables(&mut self, variables: Vec<(Vec<u8>, VarId)>) {
146        let overlay_frame = self.last_overlay_mut();
147
148        for (mut name, var_id) in variables {
149            if !name.starts_with(b"$") {
150                name.insert(0, b'$');
151            }
152            overlay_frame.insert_variable(name, var_id);
153        }
154    }
155
156    pub fn add_predecl(&mut self, decl: Box<dyn Command>) -> Option<DeclId> {
157        let name = decl.name().as_bytes().to_vec();
158
159        self.delta.decls.push(decl);
160        let decl_id = self.num_decls() - 1;
161        let decl_id = DeclId::new(decl_id);
162
163        self.delta
164            .last_scope_frame_mut()
165            .predecls
166            .insert(name, decl_id)
167    }
168
169    #[cfg(feature = "plugin")]
170    pub fn find_or_create_plugin(
171        &mut self,
172        identity: &PluginIdentity,
173        make: impl FnOnce() -> Arc<dyn RegisteredPlugin>,
174    ) -> Arc<dyn RegisteredPlugin> {
175        // Check in delta first, then permanent_state
176        if let Some(plugin) = self
177            .delta
178            .plugins
179            .iter()
180            .chain(self.permanent_state.plugins())
181            .find(|p| p.identity() == identity)
182        {
183            plugin.clone()
184        } else {
185            let plugin = make();
186            self.delta.plugins.push(plugin.clone());
187            plugin
188        }
189    }
190
191    #[cfg(feature = "plugin")]
192    pub fn update_plugin_registry(&mut self, item: PluginRegistryItem) {
193        self.delta.plugin_registry_items.push(item);
194    }
195
196    pub fn merge_predecl(&mut self, name: &[u8]) -> Option<DeclId> {
197        self.move_predecls_to_overlay();
198
199        let overlay_frame = self.last_overlay_mut();
200
201        if let Some(decl_id) = overlay_frame.predecls.remove(name) {
202            overlay_frame.insert_decl(name.into(), decl_id);
203
204            return Some(decl_id);
205        }
206
207        None
208    }
209
210    fn move_predecls_to_overlay(&mut self) {
211        let predecls: HashMap<Vec<u8>, DeclId> =
212            self.delta.last_scope_frame_mut().predecls.drain().collect();
213
214        self.last_overlay_mut().predecls.extend(predecls);
215    }
216
217    pub fn hide_decl(&mut self, name: &[u8]) -> Option<DeclId> {
218        let mut removed_overlays = vec![];
219        let mut visibility: Visibility = Visibility::new();
220
221        // Since we can mutate scope frames in delta, remove the id directly
222        for scope_frame in self.delta.scope.iter_mut().rev() {
223            for overlay_id in scope_frame
224                .active_overlay_ids(&mut removed_overlays)
225                .iter()
226                .rev()
227            {
228                let overlay_frame = scope_frame.get_overlay_mut(*overlay_id);
229
230                visibility.append(&overlay_frame.visibility);
231
232                if let Some(decl_id) = overlay_frame.get_decl(name)
233                    && visibility.is_decl_id_visible(&decl_id)
234                {
235                    // Hide decl only if it's not already hidden
236                    overlay_frame.visibility.hide_decl_id(&decl_id);
237                    return Some(decl_id);
238                }
239            }
240        }
241
242        // We cannot mutate the permanent state => store the information in the current overlay frame
243        // for scope in self.permanent_state.scope.iter().rev() {
244        for overlay_frame in self
245            .permanent_state
246            .active_overlays(&removed_overlays)
247            .rev()
248        {
249            visibility.append(&overlay_frame.visibility);
250
251            if let Some(decl_id) = overlay_frame.get_decl(name)
252                && visibility.is_decl_id_visible(&decl_id)
253            {
254                // Hide decl only if it's not already hidden
255                self.last_overlay_mut().visibility.hide_decl_id(&decl_id);
256                return Some(decl_id);
257            }
258        }
259
260        None
261    }
262
263    pub fn hide_decls(&mut self, decls: &[Vec<u8>]) {
264        for decl in decls.iter() {
265            self.hide_decl(decl); // let's assume no errors
266        }
267    }
268
269    pub fn add_block(&mut self, block: Arc<Block>) -> BlockId {
270        log::trace!(
271            "block id={} added, has IR = {:?}",
272            self.num_blocks(),
273            block.ir_block.is_some()
274        );
275
276        self.delta.blocks.push(block);
277
278        BlockId::new(self.num_blocks() - 1)
279    }
280
281    pub fn add_module(&mut self, name: &str, module: Module, comments: Vec<Span>) -> ModuleId {
282        let name = name.as_bytes().to_vec();
283
284        self.delta.modules.push(Arc::new(module));
285        let module_id = self.num_modules() - 1;
286        let module_id = ModuleId::new(module_id);
287
288        if !comments.is_empty() {
289            self.delta
290                .doccomments
291                .add_module_comments(module_id, comments);
292        }
293
294        self.last_overlay_mut().modules.insert(name, module_id);
295
296        module_id
297    }
298
299    pub fn get_module_comments(&self, module_id: ModuleId) -> Option<&[Span]> {
300        self.delta
301            .doccomments
302            .get_module_comments(module_id)
303            .or_else(|| self.permanent_state.get_module_comments(module_id))
304    }
305
306    pub fn next_span_start(&self) -> usize {
307        let permanent_span_start = self.permanent_state.next_span_start();
308
309        if let Some(cached_file) = self.delta.files.last() {
310            cached_file.covered_span.end
311        } else {
312            permanent_span_start
313        }
314    }
315
316    pub fn files(&self) -> impl Iterator<Item = &CachedFile> {
317        self.permanent_state.files().chain(self.delta.files.iter())
318    }
319
320    pub fn get_contents_of_file(&self, file_id: FileId) -> Option<&[u8]> {
321        if let Some(cached_file) = self.permanent_state.get_file_contents().get(file_id.get()) {
322            return Some(&cached_file.content);
323        }
324        // The index subtraction will not underflow, if we hit the permanent state first.
325        // Check if you try reordering for locality
326        if let Some(cached_file) = self
327            .delta
328            .get_file_contents()
329            .get(file_id.get() - self.permanent_state.num_files())
330        {
331            return Some(&cached_file.content);
332        }
333
334        None
335    }
336
337    #[must_use]
338    pub fn add_file(&mut self, filename: String, contents: &[u8]) -> FileId {
339        // First, look for the file to see if we already have it
340        for (idx, cached_file) in self.files().enumerate() {
341            if *cached_file.name == filename && &*cached_file.content == contents {
342                return FileId::new(idx);
343            }
344        }
345
346        let next_span_start = self.next_span_start();
347        let next_span_end = next_span_start + contents.len();
348
349        let covered_span = Span::new(next_span_start, next_span_end);
350
351        self.delta.files.push(CachedFile {
352            name: filename.into(),
353            content: contents.into(),
354            covered_span,
355        });
356
357        FileId::new(self.num_files() - 1)
358    }
359
360    #[must_use]
361    pub fn add_virtual_path(&mut self, name: String, virtual_path: VirtualPath) -> VirtualPathId {
362        self.delta.virtual_paths.push((name, virtual_path));
363
364        VirtualPathId::new(self.num_virtual_paths() - 1)
365    }
366
367    pub fn get_span_for_filename(&self, filename: &str) -> Option<Span> {
368        let predicate = |file: &CachedFile| &*file.name == filename;
369        // search from end to start, in case there're duplicated files with the same name
370        let file_id = self
371            .delta
372            .files
373            .iter()
374            .rposition(predicate)
375            .map(|idx| idx + self.permanent_state.num_files())
376            .or_else(|| self.permanent_state.files().rposition(predicate))?;
377        let file_id = FileId::new(file_id);
378
379        Some(self.get_span_for_file(file_id))
380    }
381
382    /// Panics:
383    /// On invalid `FileId`
384    ///
385    /// Use with care
386    pub fn get_span_for_file(&self, file_id: FileId) -> Span {
387        let result = self
388            .files()
389            .nth(file_id.get())
390            .expect("internal error: could not find source for previously parsed file");
391
392        result.covered_span
393    }
394
395    pub fn get_span_contents(&self, span: Span) -> &[u8] {
396        let permanent_end = self.permanent_state.next_span_start();
397        if permanent_end <= span.start {
398            for cached_file in &self.delta.files {
399                if cached_file.covered_span.contains_span(span) {
400                    return &cached_file.content[span.start - cached_file.covered_span.start
401                        ..span.end - cached_file.covered_span.start];
402                }
403            }
404        }
405
406        // if no files with span were found, fall back on permanent ones
407        self.permanent_state.get_span_contents(span)
408    }
409
410    pub fn enter_scope(&mut self) {
411        self.delta.enter_scope();
412    }
413
414    pub fn exit_scope(&mut self) {
415        self.delta.exit_scope();
416    }
417
418    /// Find the [`DeclId`](crate::DeclId) corresponding to a predeclaration with `name`.
419    pub fn find_predecl(&self, name: &[u8]) -> Option<DeclId> {
420        let mut removed_overlays = vec![];
421
422        for scope_frame in self.delta.scope.iter().rev() {
423            if let Some(decl_id) = scope_frame.predecls.get(name) {
424                return Some(*decl_id);
425            }
426
427            for overlay_frame in scope_frame.active_overlays(&mut removed_overlays).rev() {
428                if let Some(decl_id) = overlay_frame.predecls.get(name) {
429                    return Some(*decl_id);
430                }
431            }
432        }
433
434        None
435    }
436
437    /// Find the [`DeclId`](crate::DeclId) corresponding to a declaration with `name`.
438    ///
439    /// Extends [`EngineState::find_decl`] to also search for predeclarations
440    /// (if [`StateWorkingSet::search_predecls`] is set), and declarations from scopes existing
441    /// only in [`StateDelta`].
442    pub fn find_decl(&self, name: &[u8]) -> Option<DeclId> {
443        let mut removed_overlays = vec![];
444
445        let mut visibility: Visibility = Visibility::new();
446
447        for scope_frame in self.delta.scope.iter().rev() {
448            if self.search_predecls
449                && let Some(decl_id) = scope_frame.predecls.get(name)
450                && visibility.is_decl_id_visible(decl_id)
451            {
452                return Some(*decl_id);
453            }
454
455            // check overlay in delta
456            for overlay_frame in scope_frame.active_overlays(&mut removed_overlays).rev() {
457                visibility.append(&overlay_frame.visibility);
458
459                if self.search_predecls
460                    && let Some(decl_id) = overlay_frame.predecls.get(name)
461                    && visibility.is_decl_id_visible(decl_id)
462                {
463                    return Some(*decl_id);
464                }
465
466                if let Some(decl_id) = overlay_frame.get_decl(name)
467                    && visibility.is_decl_id_visible(&decl_id)
468                {
469                    return Some(decl_id);
470                }
471            }
472        }
473
474        // check overlay in perma
475        self.permanent_state.find_decl(name, &removed_overlays)
476    }
477
478    /// Find the name of the declaration corresponding to `decl_id`.
479    ///
480    /// Extends [`EngineState::find_decl_name`] to also search for predeclarations (if [`StateWorkingSet::search_predecls`] is set),
481    /// and declarations from scopes existing only in [`StateDelta`].
482    pub fn find_decl_name(&self, decl_id: DeclId) -> Option<&[u8]> {
483        let mut removed_overlays = vec![];
484
485        let mut visibility: Visibility = Visibility::new();
486
487        for scope_frame in self.delta.scope.iter().rev() {
488            if self.search_predecls {
489                for (name, id) in scope_frame.predecls.iter() {
490                    if id == &decl_id {
491                        return Some(name);
492                    }
493                }
494            }
495
496            // check overlay in delta
497            for overlay_frame in scope_frame.active_overlays(&mut removed_overlays).rev() {
498                visibility.append(&overlay_frame.visibility);
499
500                if self.search_predecls {
501                    for (name, id) in overlay_frame.predecls.iter() {
502                        if id == &decl_id {
503                            return Some(name);
504                        }
505                    }
506                }
507
508                if visibility.is_decl_id_visible(&decl_id) {
509                    for (name, id) in overlay_frame.decls.iter() {
510                        if id == &decl_id {
511                            return Some(name);
512                        }
513                    }
514                }
515            }
516        }
517
518        // check overlay in perma
519        self.permanent_state
520            .find_decl_name(decl_id, &removed_overlays)
521    }
522
523    /// Find the [`ModuleId`](crate::ModuleId) corresponding to `name`.
524    ///
525    /// Extends [`EngineState::find_module`] to also search for ,
526    /// and declarations from scopes existing only in [`StateDelta`].
527    pub fn find_module(&self, name: &[u8]) -> Option<ModuleId> {
528        let mut removed_overlays = vec![];
529
530        for scope_frame in self.delta.scope.iter().rev() {
531            for overlay_frame in scope_frame.active_overlays(&mut removed_overlays).rev() {
532                if let Some(module_id) = overlay_frame.modules.get(name) {
533                    return Some(*module_id);
534                }
535            }
536        }
537
538        for overlay_frame in self
539            .permanent_state
540            .active_overlays(&removed_overlays)
541            .rev()
542        {
543            if let Some(module_id) = overlay_frame.modules.get(name) {
544                return Some(*module_id);
545            }
546        }
547
548        None
549    }
550
551    pub fn next_var_id(&self) -> VarId {
552        let num_permanent_vars = self.permanent_state.num_vars();
553        VarId::new(num_permanent_vars + self.delta.vars.len())
554    }
555
556    pub fn list_variables(&self) -> Vec<&[u8]> {
557        let mut removed_overlays = vec![];
558        let mut variables = HashSet::new();
559        for scope_frame in self.delta.scope.iter() {
560            for overlay_frame in scope_frame.active_overlays(&mut removed_overlays) {
561                variables.extend(overlay_frame.vars.keys().map(|k| &k[..]));
562            }
563        }
564
565        let permanent_vars = self
566            .permanent_state
567            .active_overlays(&removed_overlays)
568            .flat_map(|overlay_frame| overlay_frame.vars.keys().map(|k| &k[..]));
569
570        variables.extend(permanent_vars);
571        variables.into_iter().collect()
572    }
573
574    pub fn find_variable(&self, name: &[u8]) -> Option<VarId> {
575        let mut name = name.to_vec();
576        if !name.starts_with(b"$") {
577            name.insert(0, b'$');
578        }
579        let mut removed_overlays = vec![];
580
581        for scope_frame in self.delta.scope.iter().rev() {
582            for overlay_frame in scope_frame.active_overlays(&mut removed_overlays).rev() {
583                if let Some(var_id) = overlay_frame.vars.get(&name) {
584                    return Some(*var_id);
585                }
586            }
587        }
588
589        for overlay_frame in self
590            .permanent_state
591            .active_overlays(&removed_overlays)
592            .rev()
593        {
594            if let Some(var_id) = overlay_frame.vars.get(&name) {
595                return Some(*var_id);
596            }
597        }
598
599        None
600    }
601
602    pub fn find_variable_in_current_frame(&self, name: &[u8]) -> Option<VarId> {
603        let mut removed_overlays = vec![];
604
605        for scope_frame in self.delta.scope.iter().rev().take(1) {
606            for overlay_frame in scope_frame.active_overlays(&mut removed_overlays).rev() {
607                if let Some(var_id) = overlay_frame.vars.get(name) {
608                    return Some(*var_id);
609                }
610            }
611        }
612
613        None
614    }
615
616    pub fn add_variable(
617        &mut self,
618        mut name: Vec<u8>,
619        span: Span,
620        ty: Type,
621        mutable: bool,
622    ) -> VarId {
623        let next_id = self.next_var_id();
624        // correct name if necessary
625        if !name.starts_with(b"$") {
626            name.insert(0, b'$');
627        }
628
629        self.last_overlay_mut().vars.insert(name, next_id);
630
631        self.delta.vars.push(Variable::new(span, ty, mutable));
632
633        next_id
634    }
635
636    /// Returns the current working directory as a String, which is guaranteed to be canonicalized.
637    /// Returns an empty string if $env.PWD doesn't exist, is not a String, or is not an absolute path.
638    ///
639    /// It does NOT consider modifications to the working directory made on a stack.
640    #[deprecated(since = "0.92.3", note = "please use `EngineState::cwd()` instead")]
641    pub fn get_cwd(&self) -> String {
642        self.permanent_state
643            .cwd(None)
644            .map(|path| path.to_string_lossy().to_string())
645            .unwrap_or_default()
646    }
647
648    pub fn get_env_var(&self, name: &str) -> Option<&Value> {
649        self.permanent_state.get_env_var(name)
650    }
651
652    /// Returns a reference to the config stored at permanent state
653    ///
654    /// At runtime, you most likely want to call [`Stack::get_config()`][super::Stack::get_config()]
655    /// because this method does not capture environment updates during runtime.
656    pub fn get_config(&self) -> &Arc<Config> {
657        &self.permanent_state.config
658    }
659
660    pub fn set_variable_type(&mut self, var_id: VarId, ty: Type) {
661        let num_permanent_vars = self.permanent_state.num_vars();
662        if var_id.get() < num_permanent_vars {
663            panic!("Internal error: attempted to set into permanent state from working set")
664        } else {
665            self.delta.vars[var_id.get() - num_permanent_vars].ty = ty;
666        }
667    }
668
669    pub fn set_variable_const_val(&mut self, var_id: VarId, val: Value) {
670        let num_permanent_vars = self.permanent_state.num_vars();
671        if var_id.get() < num_permanent_vars {
672            panic!("Internal error: attempted to set into permanent state from working set")
673        } else {
674            self.delta.vars[var_id.get() - num_permanent_vars].const_val = Some(val);
675        }
676    }
677
678    pub fn get_variable(&self, var_id: VarId) -> &Variable {
679        let num_permanent_vars = self.permanent_state.num_vars();
680        if var_id.get() < num_permanent_vars {
681            self.permanent_state.get_var(var_id)
682        } else {
683            self.delta
684                .vars
685                .get(var_id.get() - num_permanent_vars)
686                .expect("internal error: missing variable")
687        }
688    }
689
690    pub fn get_variable_if_possible(&self, var_id: VarId) -> Option<&Variable> {
691        let num_permanent_vars = self.permanent_state.num_vars();
692        if var_id.get() < num_permanent_vars {
693            Some(self.permanent_state.get_var(var_id))
694        } else {
695            self.delta.vars.get(var_id.get() - num_permanent_vars)
696        }
697    }
698
699    pub fn get_constant(&self, var_id: VarId) -> Result<&Value, ParseError> {
700        let var = self.get_variable(var_id);
701
702        if let Some(const_val) = &var.const_val {
703            Ok(const_val)
704        } else {
705            Err(ParseError::InternalError(
706                "constant does not have a constant value".into(),
707                var.declaration_span,
708            ))
709        }
710    }
711
712    pub fn get_decl(&self, decl_id: DeclId) -> &dyn Command {
713        let num_permanent_decls = self.permanent_state.num_decls();
714        if decl_id.get() < num_permanent_decls {
715            self.permanent_state.get_decl(decl_id)
716        } else {
717            self.delta
718                .decls
719                .get(decl_id.get() - num_permanent_decls)
720                .expect("internal error: missing declaration")
721                .as_ref()
722        }
723    }
724
725    pub fn get_decl_mut(&mut self, decl_id: DeclId) -> &mut Box<dyn Command> {
726        let num_permanent_decls = self.permanent_state.num_decls();
727        if decl_id.get() < num_permanent_decls {
728            panic!("internal error: can only mutate declarations in working set")
729        } else {
730            self.delta
731                .decls
732                .get_mut(decl_id.get() - num_permanent_decls)
733                .expect("internal error: missing declaration")
734        }
735    }
736
737    pub fn get_signature(&self, decl: &dyn Command) -> Signature {
738        if let Some(block_id) = decl.block_id() {
739            *self.get_block(block_id).signature.clone()
740        } else {
741            decl.signature()
742        }
743    }
744
745    pub fn find_commands_by_predicate(
746        &self,
747        mut predicate: impl FnMut(&[u8]) -> bool,
748        ignore_deprecated: bool,
749    ) -> Vec<(DeclId, Vec<u8>, Option<String>, CommandType)> {
750        let mut output = vec![];
751
752        for scope_frame in self.delta.scope.iter().rev() {
753            for overlay_id in scope_frame.active_overlays.iter().rev() {
754                let overlay_frame = scope_frame.get_overlay(*overlay_id);
755
756                for (name, decl_id) in &overlay_frame.decls {
757                    if overlay_frame.visibility.is_decl_id_visible(decl_id) && predicate(name) {
758                        let command = self.get_decl(*decl_id);
759                        if ignore_deprecated && command.signature().category == Category::Removed {
760                            continue;
761                        }
762                        output.push((
763                            *decl_id,
764                            name.clone(),
765                            Some(command.description().to_string()),
766                            command.command_type(),
767                        ));
768                    }
769                }
770            }
771        }
772
773        let mut permanent = self
774            .permanent_state
775            .find_commands_by_predicate(predicate, ignore_deprecated);
776
777        output.append(&mut permanent);
778
779        output
780    }
781
782    pub fn get_block(&self, block_id: BlockId) -> &Arc<Block> {
783        let num_permanent_blocks = self.permanent_state.num_blocks();
784        if block_id.get() < num_permanent_blocks {
785            self.permanent_state.get_block(block_id)
786        } else {
787            self.delta
788                .blocks
789                .get(block_id.get() - num_permanent_blocks)
790                .expect("internal error: missing block")
791        }
792    }
793
794    pub fn get_module(&self, module_id: ModuleId) -> &Module {
795        let num_permanent_modules = self.permanent_state.num_modules();
796        if module_id.get() < num_permanent_modules {
797            self.permanent_state.get_module(module_id)
798        } else {
799            self.delta
800                .modules
801                .get(module_id.get() - num_permanent_modules)
802                .expect("internal error: missing module")
803        }
804    }
805
806    pub fn get_block_mut(&mut self, block_id: BlockId) -> &mut Block {
807        let num_permanent_blocks = self.permanent_state.num_blocks();
808        if block_id.get() < num_permanent_blocks {
809            panic!("Attempt to mutate a block that is in the permanent (immutable) state")
810        } else {
811            self.delta
812                .blocks
813                .get_mut(block_id.get() - num_permanent_blocks)
814                .map(Arc::make_mut)
815                .expect("internal error: missing block")
816        }
817    }
818
819    /// Find the overlay corresponding to `name`.
820    pub fn find_overlay(&self, name: &[u8]) -> Option<&OverlayFrame> {
821        for scope_frame in self.delta.scope.iter().rev() {
822            if let Some(overlay_id) = scope_frame.find_overlay(name) {
823                return Some(scope_frame.get_overlay(overlay_id));
824            }
825        }
826
827        self.permanent_state
828            .find_overlay(name)
829            .map(|id| self.permanent_state.get_overlay(id))
830    }
831
832    pub fn last_overlay_name(&self) -> &[u8] {
833        let mut removed_overlays = vec![];
834
835        for scope_frame in self.delta.scope.iter().rev() {
836            if let Some(last_name) = scope_frame
837                .active_overlay_names(&mut removed_overlays)
838                .iter()
839                .rev()
840                .next_back()
841            {
842                return last_name;
843            }
844        }
845
846        self.permanent_state.last_overlay_name(&removed_overlays)
847    }
848
849    pub fn last_overlay(&self) -> &OverlayFrame {
850        let mut removed_overlays = vec![];
851
852        for scope_frame in self.delta.scope.iter().rev() {
853            if let Some(last_overlay) = scope_frame
854                .active_overlays(&mut removed_overlays)
855                .rev()
856                .next_back()
857            {
858                return last_overlay;
859            }
860        }
861
862        self.permanent_state.last_overlay(&removed_overlays)
863    }
864
865    pub fn last_overlay_mut(&mut self) -> &mut OverlayFrame {
866        if self.delta.last_overlay_mut().is_none() {
867            // If there is no overlay, automatically activate the last one
868            let overlay_frame = self.last_overlay();
869            let name = self.last_overlay_name().to_vec();
870            let origin = overlay_frame.origin;
871            let prefixed = overlay_frame.prefixed;
872            self.add_overlay(
873                name,
874                origin,
875                ResolvedImportPattern::new(vec![], vec![], vec![], vec![]),
876                prefixed,
877            );
878        }
879
880        self.delta
881            .last_overlay_mut()
882            .expect("internal error: missing added overlay")
883    }
884
885    /// Collect all decls that belong to an overlay
886    pub fn decls_of_overlay(&self, name: &[u8]) -> HashMap<Vec<u8>, DeclId> {
887        let mut result = HashMap::new();
888
889        if let Some(overlay_id) = self.permanent_state.find_overlay(name) {
890            let overlay_frame = self.permanent_state.get_overlay(overlay_id);
891
892            for (decl_key, decl_id) in &overlay_frame.decls {
893                result.insert(decl_key.to_owned(), *decl_id);
894            }
895        }
896
897        for scope_frame in self.delta.scope.iter() {
898            if let Some(overlay_id) = scope_frame.find_overlay(name) {
899                let overlay_frame = scope_frame.get_overlay(overlay_id);
900
901                for (decl_key, decl_id) in &overlay_frame.decls {
902                    result.insert(decl_key.to_owned(), *decl_id);
903                }
904            }
905        }
906
907        result
908    }
909
910    pub fn add_overlay(
911        &mut self,
912        name: Vec<u8>,
913        origin: ModuleId,
914        definitions: ResolvedImportPattern,
915        prefixed: bool,
916    ) {
917        let last_scope_frame = self.delta.last_scope_frame_mut();
918
919        last_scope_frame
920            .removed_overlays
921            .retain(|removed_name| removed_name != &name);
922
923        let overlay_id = if let Some(overlay_id) = last_scope_frame.find_overlay(&name) {
924            last_scope_frame.get_overlay_mut(overlay_id).origin = origin;
925
926            overlay_id
927        } else {
928            last_scope_frame
929                .overlays
930                .push((name, OverlayFrame::from_origin(origin, prefixed)));
931            OverlayId::new(last_scope_frame.overlays.len() - 1)
932        };
933
934        last_scope_frame
935            .active_overlays
936            .retain(|id| id != &overlay_id);
937        last_scope_frame.active_overlays.push(overlay_id);
938
939        self.move_predecls_to_overlay();
940
941        self.use_decls(definitions.decls);
942        self.use_modules(definitions.modules);
943
944        let mut constants = vec![];
945
946        for (name, const_vid) in definitions.constants {
947            constants.push((name, const_vid));
948        }
949
950        for (name, const_val) in definitions.constant_values {
951            let const_var_id =
952                self.add_variable(name.clone(), Span::unknown(), const_val.get_type(), false);
953            self.set_variable_const_val(const_var_id, const_val);
954            constants.push((name, const_var_id));
955        }
956        self.use_variables(constants);
957    }
958
959    pub fn remove_overlay(&mut self, name: &[u8], keep_custom: bool) {
960        let last_scope_frame = self.delta.last_scope_frame_mut();
961
962        let maybe_module_id = if let Some(overlay_id) = last_scope_frame.find_overlay(name) {
963            last_scope_frame
964                .active_overlays
965                .retain(|id| id != &overlay_id);
966
967            Some(last_scope_frame.get_overlay(overlay_id).origin)
968        } else {
969            self.permanent_state
970                .find_overlay(name)
971                .map(|id| self.permanent_state.get_overlay(id).origin)
972        };
973
974        if let Some(module_id) = maybe_module_id {
975            last_scope_frame.removed_overlays.push(name.to_owned());
976
977            if keep_custom {
978                let origin_module = self.get_module(module_id);
979
980                let decls = self
981                    .decls_of_overlay(name)
982                    .into_iter()
983                    .filter(|(n, _)| !origin_module.has_decl(n))
984                    .collect();
985
986                self.use_decls(decls);
987            }
988        }
989    }
990
991    pub fn render(self) -> StateDelta {
992        self.delta
993    }
994
995    pub fn build_desc(&self, spans: &[Span]) -> (String, String) {
996        let comment_lines: Vec<&[u8]> = spans
997            .iter()
998            .map(|span| self.get_span_contents(*span))
999            .collect();
1000        build_desc(&comment_lines)
1001    }
1002
1003    pub fn find_block_by_span(&self, span: Span) -> Option<Arc<Block>> {
1004        for block in &self.delta.blocks {
1005            if Some(span) == block.span {
1006                return Some(block.clone());
1007            }
1008        }
1009
1010        for block in self.permanent_state.blocks.iter() {
1011            if Some(span) == block.span {
1012                return Some(block.clone());
1013            }
1014        }
1015
1016        None
1017    }
1018
1019    pub fn find_module_by_span(&self, span: Span) -> Option<ModuleId> {
1020        for (id, module) in self.delta.modules.iter().enumerate() {
1021            if Some(span) == module.span {
1022                return Some(ModuleId::new(self.permanent_state.num_modules() + id));
1023            }
1024        }
1025
1026        for (module_id, module) in self.permanent_state.modules.iter().enumerate() {
1027            if Some(span) == module.span {
1028                return Some(ModuleId::new(module_id));
1029            }
1030        }
1031
1032        None
1033    }
1034
1035    pub fn find_virtual_path(&self, name: &str) -> Option<&VirtualPath> {
1036        // Platform appropriate virtual path (slashes or backslashes)
1037        let virtual_path_name = Path::new(name);
1038
1039        for (virtual_name, virtual_path) in self.delta.virtual_paths.iter().rev() {
1040            if Path::new(virtual_name) == virtual_path_name {
1041                return Some(virtual_path);
1042            }
1043        }
1044
1045        for (virtual_name, virtual_path) in self.permanent_state.virtual_paths.iter().rev() {
1046            if Path::new(virtual_name) == virtual_path_name {
1047                return Some(virtual_path);
1048            }
1049        }
1050
1051        None
1052    }
1053
1054    pub fn get_virtual_path(&self, virtual_path_id: VirtualPathId) -> &(String, VirtualPath) {
1055        let num_permanent_virtual_paths = self.permanent_state.num_virtual_paths();
1056        if virtual_path_id.get() < num_permanent_virtual_paths {
1057            self.permanent_state.get_virtual_path(virtual_path_id)
1058        } else {
1059            self.delta
1060                .virtual_paths
1061                .get(virtual_path_id.get() - num_permanent_virtual_paths)
1062                .expect("internal error: missing virtual path")
1063        }
1064    }
1065
1066    pub fn add_span(&mut self, span: Span) -> SpanId {
1067        let num_permanent_spans = self.permanent_state.spans.len();
1068        self.delta.spans.push(span);
1069        SpanId::new(num_permanent_spans + self.delta.spans.len() - 1)
1070    }
1071}
1072
1073impl<'a> GetSpan for &'a StateWorkingSet<'a> {
1074    fn get_span(&self, span_id: SpanId) -> Span {
1075        let num_permanent_spans = self.permanent_state.num_spans();
1076        if span_id.get() < num_permanent_spans {
1077            self.permanent_state.get_span(span_id)
1078        } else {
1079            *self
1080                .delta
1081                .spans
1082                .get(span_id.get() - num_permanent_spans)
1083                .expect("internal error: missing span")
1084        }
1085    }
1086}
1087
1088impl miette::SourceCode for &StateWorkingSet<'_> {
1089    fn read_span<'b>(
1090        &'b self,
1091        span: &miette::SourceSpan,
1092        context_lines_before: usize,
1093        context_lines_after: usize,
1094    ) -> Result<Box<dyn miette::SpanContents<'b> + 'b>, miette::MietteError> {
1095        let debugging = std::env::var("MIETTE_DEBUG").is_ok();
1096        if debugging {
1097            let finding_span = "Finding span in StateWorkingSet";
1098            dbg!(finding_span, span);
1099        }
1100        for cached_file in self.files() {
1101            let (filename, start, end) = (
1102                &cached_file.name,
1103                cached_file.covered_span.start,
1104                cached_file.covered_span.end,
1105            );
1106            if debugging {
1107                dbg!(&filename, start, end);
1108            }
1109            if span.offset() >= start && span.offset() + span.len() <= end {
1110                if debugging {
1111                    let found_file = "Found matching file";
1112                    dbg!(found_file);
1113                }
1114                let our_span = cached_file.covered_span;
1115                // We need to move to a local span because we're only reading
1116                // the specific file contents via self.get_span_contents.
1117                let local_span = (span.offset() - start, span.len()).into();
1118                if debugging {
1119                    dbg!(&local_span);
1120                }
1121                let span_contents = self.get_span_contents(our_span);
1122                if debugging {
1123                    dbg!(String::from_utf8_lossy(span_contents));
1124                }
1125                let span_contents = span_contents.read_span(
1126                    &local_span,
1127                    context_lines_before,
1128                    context_lines_after,
1129                )?;
1130                let content_span = span_contents.span();
1131                // Back to "global" indexing
1132                let retranslated = (content_span.offset() + start, content_span.len()).into();
1133                if debugging {
1134                    dbg!(&retranslated);
1135                }
1136
1137                let data = span_contents.data();
1138                if &**filename == "<cli>" {
1139                    if debugging {
1140                        let success_cli = "Successfully read CLI span";
1141                        dbg!(success_cli, String::from_utf8_lossy(data));
1142                    }
1143                    return Ok(Box::new(miette::MietteSpanContents::new(
1144                        data,
1145                        retranslated,
1146                        span_contents.line(),
1147                        span_contents.column(),
1148                        span_contents.line_count(),
1149                    )));
1150                } else {
1151                    if debugging {
1152                        let success_file = "Successfully read file span";
1153                        dbg!(success_file);
1154                    }
1155                    return Ok(Box::new(miette::MietteSpanContents::new_named(
1156                        (**filename).to_owned(),
1157                        data,
1158                        retranslated,
1159                        span_contents.line(),
1160                        span_contents.column(),
1161                        span_contents.line_count(),
1162                    )));
1163                }
1164            }
1165        }
1166        Err(miette::MietteError::OutOfBounds)
1167    }
1168}
1169
1170/// Files being evaluated, arranged as a stack.
1171///
1172/// The current active file is on the top of the stack.
1173/// When a file source/import another file, the new file is pushed onto the stack.
1174/// Attempting to add files that are already in the stack (circular import) results in an error.
1175///
1176/// Note that file paths are compared without canonicalization, so the same
1177/// physical file may still appear multiple times under different paths.
1178/// This doesn't affect circular import detection though.
1179#[derive(Debug, Default)]
1180pub struct FileStack(Vec<PathBuf>);
1181
1182impl FileStack {
1183    /// Creates an empty stack.
1184    pub fn new() -> Self {
1185        Self(vec![])
1186    }
1187
1188    /// Creates a stack with a single file on top.
1189    ///
1190    /// This is a convenience method that creates an empty stack, then pushes the file onto it.
1191    /// It skips the circular import check and always succeeds.
1192    pub fn with_file(path: PathBuf) -> Self {
1193        Self(vec![path])
1194    }
1195
1196    /// Adds a file to the stack.
1197    ///
1198    /// If the same file is already present in the stack, returns `ParseError::CircularImport`.
1199    pub fn push(&mut self, path: PathBuf, span: Span) -> Result<(), ParseError> {
1200        // Check for circular import.
1201        if let Some(i) = self.0.iter().rposition(|p| p == &path) {
1202            let filenames: Vec<String> = self.0[i..]
1203                .iter()
1204                .chain(std::iter::once(&path))
1205                .map(|p| p.to_string_lossy().to_string())
1206                .collect();
1207            let msg = filenames.join("\nuses ");
1208            return Err(ParseError::CircularImport(msg, span));
1209        }
1210
1211        self.0.push(path);
1212        Ok(())
1213    }
1214
1215    /// Removes a file from the stack and returns its path, or None if the stack is empty.
1216    pub fn pop(&mut self) -> Option<PathBuf> {
1217        self.0.pop()
1218    }
1219
1220    /// Returns the active file (that is, the file on the top of the stack), or None if the stack is empty.
1221    pub fn top(&self) -> Option<&Path> {
1222        self.0.last().map(PathBuf::as_path)
1223    }
1224
1225    /// Returns the parent directory of the active file, or None if the stack is empty
1226    /// or the active file doesn't have a parent directory as part of its path.
1227    pub fn current_working_directory(&self) -> Option<&Path> {
1228        self.0.last().and_then(|path| path.parent())
1229    }
1230}