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().insert_variable(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    /// Apply a function to all commands. The function accepts a command name and its DeclId
746    pub fn traverse_commands(&self, mut f: impl FnMut(&[u8], DeclId)) {
747        for scope_frame in self.delta.scope.iter().rev() {
748            for overlay_id in scope_frame.active_overlays.iter().rev() {
749                let overlay_frame = scope_frame.get_overlay(*overlay_id);
750
751                for (name, decl_id) in &overlay_frame.decls {
752                    if overlay_frame.visibility.is_decl_id_visible(decl_id) {
753                        f(name, *decl_id);
754                    }
755                }
756            }
757        }
758
759        self.permanent_state.traverse_commands(f);
760    }
761
762    pub fn find_commands_by_predicate(
763        &self,
764        mut predicate: impl FnMut(&[u8]) -> bool,
765        ignore_deprecated: bool,
766    ) -> Vec<(DeclId, Vec<u8>, Option<String>, CommandType)> {
767        let mut output = vec![];
768
769        self.traverse_commands(|name, decl_id| {
770            if !predicate(name) {
771                return;
772            }
773            let command = self.get_decl(decl_id);
774            if ignore_deprecated && command.signature().category == Category::Removed {
775                return;
776            }
777            output.push((
778                decl_id,
779                name.to_vec(),
780                Some(command.description().to_string()),
781                command.command_type(),
782            ));
783        });
784
785        output
786    }
787
788    pub fn get_block(&self, block_id: BlockId) -> &Arc<Block> {
789        let num_permanent_blocks = self.permanent_state.num_blocks();
790        if block_id.get() < num_permanent_blocks {
791            self.permanent_state.get_block(block_id)
792        } else {
793            self.delta
794                .blocks
795                .get(block_id.get() - num_permanent_blocks)
796                .expect("internal error: missing block")
797        }
798    }
799
800    pub fn get_module(&self, module_id: ModuleId) -> &Module {
801        let num_permanent_modules = self.permanent_state.num_modules();
802        if module_id.get() < num_permanent_modules {
803            self.permanent_state.get_module(module_id)
804        } else {
805            self.delta
806                .modules
807                .get(module_id.get() - num_permanent_modules)
808                .expect("internal error: missing module")
809        }
810    }
811
812    pub fn get_block_mut(&mut self, block_id: BlockId) -> &mut Block {
813        let num_permanent_blocks = self.permanent_state.num_blocks();
814        if block_id.get() < num_permanent_blocks {
815            panic!("Attempt to mutate a block that is in the permanent (immutable) state")
816        } else {
817            self.delta
818                .blocks
819                .get_mut(block_id.get() - num_permanent_blocks)
820                .map(Arc::make_mut)
821                .expect("internal error: missing block")
822        }
823    }
824
825    /// Find the overlay corresponding to `name`.
826    pub fn find_overlay(&self, name: &[u8]) -> Option<&OverlayFrame> {
827        for scope_frame in self.delta.scope.iter().rev() {
828            if let Some(overlay_id) = scope_frame.find_overlay(name) {
829                return Some(scope_frame.get_overlay(overlay_id));
830            }
831        }
832
833        self.permanent_state
834            .find_overlay(name)
835            .map(|id| self.permanent_state.get_overlay(id))
836    }
837
838    pub fn last_overlay_name(&self) -> &[u8] {
839        let mut removed_overlays = vec![];
840
841        for scope_frame in self.delta.scope.iter().rev() {
842            if let Some(last_name) = scope_frame
843                .active_overlay_names(&mut removed_overlays)
844                .iter()
845                .rev()
846                .next_back()
847            {
848                return last_name;
849            }
850        }
851
852        self.permanent_state.last_overlay_name(&removed_overlays)
853    }
854
855    pub fn last_overlay(&self) -> &OverlayFrame {
856        let mut removed_overlays = vec![];
857
858        for scope_frame in self.delta.scope.iter().rev() {
859            if let Some(last_overlay) = scope_frame
860                .active_overlays(&mut removed_overlays)
861                .rev()
862                .next_back()
863            {
864                return last_overlay;
865            }
866        }
867
868        self.permanent_state.last_overlay(&removed_overlays)
869    }
870
871    pub fn last_overlay_mut(&mut self) -> &mut OverlayFrame {
872        if self.delta.last_overlay_mut().is_none() {
873            // If there is no overlay, automatically activate the last one
874            let overlay_frame = self.last_overlay();
875            let name = self.last_overlay_name().to_vec();
876            let origin = overlay_frame.origin;
877            let prefixed = overlay_frame.prefixed;
878            self.add_overlay(
879                name,
880                origin,
881                ResolvedImportPattern::new(vec![], vec![], vec![], vec![]),
882                prefixed,
883            );
884        }
885
886        self.delta
887            .last_overlay_mut()
888            .expect("internal error: missing added overlay")
889    }
890
891    /// Collect all decls that belong to an overlay
892    pub fn decls_of_overlay(&self, name: &[u8]) -> HashMap<Vec<u8>, DeclId> {
893        let mut result = HashMap::new();
894
895        if let Some(overlay_id) = self.permanent_state.find_overlay(name) {
896            let overlay_frame = self.permanent_state.get_overlay(overlay_id);
897
898            for (decl_key, decl_id) in &overlay_frame.decls {
899                result.insert(decl_key.to_owned(), *decl_id);
900            }
901        }
902
903        for scope_frame in self.delta.scope.iter() {
904            if let Some(overlay_id) = scope_frame.find_overlay(name) {
905                let overlay_frame = scope_frame.get_overlay(overlay_id);
906
907                for (decl_key, decl_id) in &overlay_frame.decls {
908                    result.insert(decl_key.to_owned(), *decl_id);
909                }
910            }
911        }
912
913        result
914    }
915
916    pub fn add_overlay(
917        &mut self,
918        name: Vec<u8>,
919        origin: ModuleId,
920        definitions: ResolvedImportPattern,
921        prefixed: bool,
922    ) {
923        let last_scope_frame = self.delta.last_scope_frame_mut();
924
925        last_scope_frame
926            .removed_overlays
927            .retain(|removed_name| removed_name != &name);
928
929        let overlay_id = if let Some(overlay_id) = last_scope_frame.find_overlay(&name) {
930            last_scope_frame.get_overlay_mut(overlay_id).origin = origin;
931
932            overlay_id
933        } else {
934            last_scope_frame
935                .overlays
936                .push((name, OverlayFrame::from_origin(origin, prefixed)));
937            OverlayId::new(last_scope_frame.overlays.len() - 1)
938        };
939
940        last_scope_frame
941            .active_overlays
942            .retain(|id| id != &overlay_id);
943        last_scope_frame.active_overlays.push(overlay_id);
944
945        self.move_predecls_to_overlay();
946
947        self.use_decls(definitions.decls);
948        self.use_modules(definitions.modules);
949
950        let mut constants = vec![];
951
952        for (name, const_vid) in definitions.constants {
953            constants.push((name, const_vid));
954        }
955
956        for (name, const_val) in definitions.constant_values {
957            let const_var_id =
958                self.add_variable(name.clone(), Span::unknown(), const_val.get_type(), false);
959            self.set_variable_const_val(const_var_id, const_val);
960            constants.push((name, const_var_id));
961        }
962        self.use_variables(constants);
963    }
964
965    pub fn remove_overlay(&mut self, name: &[u8], keep_custom: bool) {
966        let last_scope_frame = self.delta.last_scope_frame_mut();
967
968        let maybe_module_id = if let Some(overlay_id) = last_scope_frame.find_overlay(name) {
969            last_scope_frame
970                .active_overlays
971                .retain(|id| id != &overlay_id);
972
973            Some(last_scope_frame.get_overlay(overlay_id).origin)
974        } else {
975            self.permanent_state
976                .find_overlay(name)
977                .map(|id| self.permanent_state.get_overlay(id).origin)
978        };
979
980        if let Some(module_id) = maybe_module_id {
981            last_scope_frame.removed_overlays.push(name.to_owned());
982
983            if keep_custom {
984                let origin_module = self.get_module(module_id);
985
986                let decls = self
987                    .decls_of_overlay(name)
988                    .into_iter()
989                    .filter(|(n, _)| !origin_module.has_decl(n))
990                    .collect();
991
992                self.use_decls(decls);
993            }
994        }
995    }
996
997    pub fn render(self) -> StateDelta {
998        self.delta
999    }
1000
1001    pub fn build_desc(&self, spans: &[Span]) -> (String, String) {
1002        let comment_lines: Vec<&[u8]> = spans
1003            .iter()
1004            .map(|span| self.get_span_contents(*span))
1005            .collect();
1006        build_desc(&comment_lines)
1007    }
1008
1009    pub fn find_block_by_span(&self, span: Span) -> Option<Arc<Block>> {
1010        for block in &self.delta.blocks {
1011            if Some(span) == block.span {
1012                return Some(block.clone());
1013            }
1014        }
1015
1016        for block in self.permanent_state.blocks.iter() {
1017            if Some(span) == block.span {
1018                return Some(block.clone());
1019            }
1020        }
1021
1022        None
1023    }
1024
1025    pub fn find_module_by_span(&self, span: Span) -> Option<ModuleId> {
1026        for (id, module) in self.delta.modules.iter().enumerate() {
1027            if Some(span) == module.span {
1028                return Some(ModuleId::new(self.permanent_state.num_modules() + id));
1029            }
1030        }
1031
1032        for (module_id, module) in self.permanent_state.modules.iter().enumerate() {
1033            if Some(span) == module.span {
1034                return Some(ModuleId::new(module_id));
1035            }
1036        }
1037
1038        None
1039    }
1040
1041    pub fn find_virtual_path(&self, name: &str) -> Option<&VirtualPath> {
1042        // Platform appropriate virtual path (slashes or backslashes)
1043        let virtual_path_name = Path::new(name);
1044
1045        for (virtual_name, virtual_path) in self.delta.virtual_paths.iter().rev() {
1046            if Path::new(virtual_name) == virtual_path_name {
1047                return Some(virtual_path);
1048            }
1049        }
1050
1051        for (virtual_name, virtual_path) in self.permanent_state.virtual_paths.iter().rev() {
1052            if Path::new(virtual_name) == virtual_path_name {
1053                return Some(virtual_path);
1054            }
1055        }
1056
1057        None
1058    }
1059
1060    pub fn get_virtual_path(&self, virtual_path_id: VirtualPathId) -> &(String, VirtualPath) {
1061        let num_permanent_virtual_paths = self.permanent_state.num_virtual_paths();
1062        if virtual_path_id.get() < num_permanent_virtual_paths {
1063            self.permanent_state.get_virtual_path(virtual_path_id)
1064        } else {
1065            self.delta
1066                .virtual_paths
1067                .get(virtual_path_id.get() - num_permanent_virtual_paths)
1068                .expect("internal error: missing virtual path")
1069        }
1070    }
1071
1072    pub fn add_span(&mut self, span: Span) -> SpanId {
1073        let num_permanent_spans = self.permanent_state.spans.len();
1074        self.delta.spans.push(span);
1075        SpanId::new(num_permanent_spans + self.delta.spans.len() - 1)
1076    }
1077}
1078
1079impl<'a> GetSpan for &'a StateWorkingSet<'a> {
1080    fn get_span(&self, span_id: SpanId) -> Span {
1081        let num_permanent_spans = self.permanent_state.num_spans();
1082        if span_id.get() < num_permanent_spans {
1083            self.permanent_state.get_span(span_id)
1084        } else {
1085            *self
1086                .delta
1087                .spans
1088                .get(span_id.get() - num_permanent_spans)
1089                .expect("internal error: missing span")
1090        }
1091    }
1092}
1093
1094impl miette::SourceCode for &StateWorkingSet<'_> {
1095    fn read_span<'b>(
1096        &'b self,
1097        span: &miette::SourceSpan,
1098        context_lines_before: usize,
1099        context_lines_after: usize,
1100    ) -> Result<Box<dyn miette::SpanContents<'b> + 'b>, miette::MietteError> {
1101        let debugging = std::env::var("MIETTE_DEBUG").is_ok();
1102        if debugging {
1103            let finding_span = "Finding span in StateWorkingSet";
1104            dbg!(finding_span, span);
1105        }
1106        for cached_file in self.files() {
1107            let (filename, start, end) = (
1108                &cached_file.name,
1109                cached_file.covered_span.start,
1110                cached_file.covered_span.end,
1111            );
1112            if debugging {
1113                dbg!(&filename, start, end);
1114            }
1115            if span.offset() >= start && span.offset() + span.len() <= end {
1116                if debugging {
1117                    let found_file = "Found matching file";
1118                    dbg!(found_file);
1119                }
1120                let our_span = cached_file.covered_span;
1121                // We need to move to a local span because we're only reading
1122                // the specific file contents via self.get_span_contents.
1123                let local_span = (span.offset() - start, span.len()).into();
1124                if debugging {
1125                    dbg!(&local_span);
1126                }
1127                let span_contents = self.get_span_contents(our_span);
1128                if debugging {
1129                    dbg!(String::from_utf8_lossy(span_contents));
1130                }
1131                let span_contents = span_contents.read_span(
1132                    &local_span,
1133                    context_lines_before,
1134                    context_lines_after,
1135                )?;
1136                let content_span = span_contents.span();
1137                // Back to "global" indexing
1138                let retranslated = (content_span.offset() + start, content_span.len()).into();
1139                if debugging {
1140                    dbg!(&retranslated);
1141                }
1142
1143                let data = span_contents.data();
1144                if &**filename == "<cli>" {
1145                    if debugging {
1146                        let success_cli = "Successfully read CLI span";
1147                        dbg!(success_cli, String::from_utf8_lossy(data));
1148                    }
1149                    return Ok(Box::new(miette::MietteSpanContents::new(
1150                        data,
1151                        retranslated,
1152                        span_contents.line(),
1153                        span_contents.column(),
1154                        span_contents.line_count(),
1155                    )));
1156                } else {
1157                    if debugging {
1158                        let success_file = "Successfully read file span";
1159                        dbg!(success_file);
1160                    }
1161                    return Ok(Box::new(miette::MietteSpanContents::new_named(
1162                        (**filename).to_owned(),
1163                        data,
1164                        retranslated,
1165                        span_contents.line(),
1166                        span_contents.column(),
1167                        span_contents.line_count(),
1168                    )));
1169                }
1170            }
1171        }
1172        Err(miette::MietteError::OutOfBounds)
1173    }
1174}
1175
1176/// Files being evaluated, arranged as a stack.
1177///
1178/// The current active file is on the top of the stack.
1179/// When a file source/import another file, the new file is pushed onto the stack.
1180/// Attempting to add files that are already in the stack (circular import) results in an error.
1181///
1182/// Note that file paths are compared without canonicalization, so the same
1183/// physical file may still appear multiple times under different paths.
1184/// This doesn't affect circular import detection though.
1185#[derive(Debug, Default)]
1186pub struct FileStack(Vec<PathBuf>);
1187
1188impl FileStack {
1189    /// Creates an empty stack.
1190    pub fn new() -> Self {
1191        Self(vec![])
1192    }
1193
1194    /// Creates a stack with a single file on top.
1195    ///
1196    /// This is a convenience method that creates an empty stack, then pushes the file onto it.
1197    /// It skips the circular import check and always succeeds.
1198    pub fn with_file(path: PathBuf) -> Self {
1199        Self(vec![path])
1200    }
1201
1202    /// Adds a file to the stack.
1203    ///
1204    /// If the same file is already present in the stack, returns `ParseError::CircularImport`.
1205    pub fn push(&mut self, path: PathBuf, span: Span) -> Result<(), ParseError> {
1206        // Check for circular import.
1207        if let Some(i) = self.0.iter().rposition(|p| p == &path) {
1208            let filenames: Vec<String> = self.0[i..]
1209                .iter()
1210                .chain(std::iter::once(&path))
1211                .map(|p| p.to_string_lossy().to_string())
1212                .collect();
1213            let msg = filenames.join("\nuses ");
1214            return Err(ParseError::CircularImport(msg, span));
1215        }
1216
1217        self.0.push(path);
1218        Ok(())
1219    }
1220
1221    /// Removes a file from the stack and returns its path, or None if the stack is empty.
1222    pub fn pop(&mut self) -> Option<PathBuf> {
1223        self.0.pop()
1224    }
1225
1226    /// Returns the active file (that is, the file on the top of the stack), or None if the stack is empty.
1227    pub fn top(&self) -> Option<&Path> {
1228        self.0.last().map(PathBuf::as_path)
1229    }
1230
1231    /// Returns the parent directory of the active file, or None if the stack is empty
1232    /// or the active file doesn't have a parent directory as part of its path.
1233    pub fn current_working_directory(&self) -> Option<&Path> {
1234        self.0.last().and_then(|path| path.parent())
1235    }
1236}