Skip to main content

nu_protocol/engine/
engine_state.rs

1use crate::{
2    BlockId, Config, DeclId, FileId, GetSpan, Handlers, HistoryConfig, JobId, Module, ModuleId,
3    OverlayId, ShellError, SignalAction, Signals, Signature, Span, SpanId, Type, Value, VarId,
4    VirtualPathId,
5    ast::Block,
6    debugger::{Debugger, NoopDebugger},
7    engine::{
8        CachedFile, Command, DEFAULT_OVERLAY_NAME, EnvName, EnvVars, OverlayFrame, ScopeFrame,
9        Stack, StateDelta, Variable, Visibility,
10        description::{Doccomments, build_desc},
11    },
12    eval_const::create_nu_constant,
13    report_error::ReportLog,
14    shell_error::{generic::GenericError, io::IoError},
15};
16use fancy_regex::Regex;
17use lru::LruCache;
18use nu_path::AbsolutePathBuf;
19use std::{
20    collections::HashMap,
21    num::NonZeroUsize,
22    path::PathBuf,
23    sync::{
24        Arc, Mutex, MutexGuard, PoisonError,
25        atomic::{AtomicBool, AtomicU32, Ordering},
26        mpsc::Sender,
27        mpsc::channel,
28    },
29};
30
31type PoisonDebuggerError<'a> = PoisonError<MutexGuard<'a, Box<dyn Debugger>>>;
32
33#[cfg(feature = "plugin")]
34use crate::{PluginRegistryFile, PluginRegistryItem, RegisteredPlugin};
35
36use super::{CurrentJob, Jobs, Mail, Mailbox, ThreadJob};
37
38#[derive(Clone, Debug)]
39pub enum VirtualPath {
40    File(FileId),
41    Dir(Vec<VirtualPathId>),
42}
43
44#[derive(Debug)]
45pub struct ReplState {
46    pub buffer: String,
47    // A byte position, as `EditCommand::MoveToPosition` is also a byte position
48    pub cursor_pos: usize,
49    /// Immediately accept the buffer on the next loop.
50    pub accept: bool,
51}
52
53#[derive(Debug)]
54pub struct IsDebugging(AtomicBool);
55
56impl IsDebugging {
57    pub fn new(val: bool) -> Self {
58        IsDebugging(AtomicBool::new(val))
59    }
60}
61
62impl Clone for IsDebugging {
63    fn clone(&self) -> Self {
64        IsDebugging(AtomicBool::new(self.0.load(Ordering::Relaxed)))
65    }
66}
67
68/// The core global engine state. This includes all global definitions as well as any global state that
69/// will persist for the whole session.
70///
71/// Declarations, variables, blocks, and other forms of data are held in the global state and referenced
72/// elsewhere using their IDs. These IDs are simply their index into the global state. This allows us to
73/// more easily handle creating blocks, binding variables and callsites, and more, because each of these
74/// will refer to the corresponding IDs rather than their definitions directly. At runtime, this means
75/// less copying and smaller structures.
76///
77/// Many of the larger objects in this structure are stored within `Arc` to decrease the cost of
78/// cloning `EngineState`. While `Arc`s are generally immutable, they can be modified using
79/// `Arc::make_mut`, which automatically clones to a new allocation if there are other copies of
80/// the `Arc` already in use, but will let us modify the `Arc` directly if we have the only
81/// reference to it.
82///
83/// Note that the runtime stack is not part of this global state. Runtime stacks are handled differently,
84/// but they also rely on using IDs rather than full definitions.
85#[derive(Clone, derive_more::Debug)]
86pub struct EngineState {
87    files: Vec<CachedFile>,
88    pub(super) virtual_paths: Vec<(String, VirtualPath)>,
89    vars: Vec<Variable>,
90    #[debug("{:?}", decls.iter().map(|c| c.name()).collect::<Vec<_>>())]
91    decls: Arc<Vec<Box<dyn Command + 'static>>>,
92    // The Vec is wrapped in Arc so that if we don't need to modify the list, we can just clone
93    // the reference and not have to clone each individual Arc inside. These lists can be
94    // especially long, so it helps
95    #[debug("{:?}", blocks.iter().map(|b| &b.signature.name))]
96    pub(super) blocks: Arc<Vec<Arc<Block>>>,
97    #[debug("{:?}", modules.iter().map(|m| String::from_utf8_lossy(&m.name)))]
98    pub(super) modules: Arc<Vec<Arc<Module>>>,
99    pub spans: Vec<Span>,
100    doccomments: Doccomments,
101    pub scope: ScopeFrame,
102    signals: Signals,
103    pub signal_handlers: Option<Handlers>,
104    pub env_vars: Arc<EnvVars>,
105    pub previous_env_vars: Arc<HashMap<EnvName, Value>>,
106    pub config: Arc<Config>,
107    pub pipeline_externals_state: Arc<(AtomicU32, AtomicU32)>,
108    pub repl_state: Arc<Mutex<ReplState>>,
109    pub table_decl_id: Option<DeclId>,
110    #[cfg(feature = "plugin")]
111    pub plugin_path: Option<PathBuf>,
112    #[cfg(feature = "plugin")]
113    #[debug("{:?}", plugins.iter().map(|rp| rp.identity().name()).collect::<Vec<_>>())]
114    plugins: Vec<Arc<dyn RegisteredPlugin>>,
115    config_path: HashMap<String, PathBuf>,
116    pub history_enabled: bool,
117    pub history_session_id: i64,
118    /// Whether the startup-only `$env.config.history.*` options are locked from further
119    /// changes (currently `path`, `max_size`, `file_format`, `isolation`).
120    ///
121    /// Set to `true` once the REPL has finished initializing reedline's history backend.
122    /// After that point, changing any of these options would have no effect on the live
123    /// history, so attempts to mutate them are rejected with an error instead of being
124    /// silently ignored.
125    pub history_locked_after_startup: bool,
126    // Path to the file Nushell is currently evaluating, or None if we're in an interactive session.
127    pub file: Option<PathBuf>,
128    pub regex_cache: Arc<Mutex<LruCache<String, Regex>>>,
129    pub is_interactive: bool,
130    pub is_login: bool,
131    pub is_lsp: bool,
132    pub is_mcp: bool,
133    startup_time: i64,
134    is_debugging: IsDebugging,
135    pub debugger: Arc<Mutex<Box<dyn Debugger>>>,
136    pub report_log: Arc<Mutex<ReportLog>>,
137
138    pub jobs: Arc<Mutex<Jobs>>,
139
140    // The job being executed with this engine state, or None if main thread
141    pub current_job: CurrentJob,
142
143    pub root_job_sender: Sender<Mail>,
144
145    // When there are background jobs running, the interactive behavior of `exit` changes depending on
146    // the value of this flag:
147    // - if this is false, then a warning about running jobs is shown and `exit` enables this flag
148    // - if this is true, then `exit` will `std::process::exit`
149    //
150    // This ensures that running exit twice will terminate the program correctly
151    pub exit_warning_given: Arc<AtomicBool>,
152}
153
154// The max number of compiled regexes to keep around in a LRU cache, arbitrarily chosen
155const REGEX_CACHE_SIZE: usize = 100; // must be nonzero, otherwise will panic
156
157pub const NU_VARIABLE_ID: VarId = VarId::new(0);
158pub const IN_VARIABLE_ID: VarId = VarId::new(1);
159pub const ENV_VARIABLE_ID: VarId = VarId::new(2);
160// NOTE: If you add more to this list, make sure to update the > checks based on the last in the list
161
162// The first span is unknown span
163pub const UNKNOWN_SPAN_ID: SpanId = SpanId::new(0);
164
165impl EngineState {
166    pub fn new() -> Self {
167        let (send, recv) = channel::<Mail>();
168
169        Self {
170            files: vec![],
171            virtual_paths: vec![],
172            vars: vec![
173                Variable::new(Span::new(0, 0), Type::Any, false),
174                Variable::new(Span::new(0, 0), Type::Any, false),
175                Variable::new(Span::new(0, 0), Type::Any, false),
176                Variable::new(Span::new(0, 0), Type::Any, false),
177                Variable::new(Span::new(0, 0), Type::Any, false),
178            ],
179            decls: Arc::new(vec![]),
180            blocks: Arc::new(vec![]),
181            modules: Arc::new(vec![Arc::new(Module::new(
182                DEFAULT_OVERLAY_NAME.as_bytes().to_vec(),
183            ))]),
184            spans: vec![Span::unknown()],
185            doccomments: Doccomments::new(),
186            // make sure we have some default overlay:
187            scope: ScopeFrame::with_empty_overlay(
188                DEFAULT_OVERLAY_NAME.as_bytes().to_vec(),
189                ModuleId::new(0),
190                false,
191            ),
192            signal_handlers: None,
193            signals: Signals::empty(),
194            env_vars: Arc::new(
195                [(DEFAULT_OVERLAY_NAME.to_string(), HashMap::new())]
196                    .into_iter()
197                    .collect(),
198            ),
199            previous_env_vars: Arc::new(HashMap::new()),
200            config: Arc::new(Config::default()),
201            pipeline_externals_state: Arc::new((AtomicU32::new(0), AtomicU32::new(0))),
202            repl_state: Arc::new(Mutex::new(ReplState {
203                buffer: "".to_string(),
204                cursor_pos: 0,
205                accept: false,
206            })),
207            table_decl_id: None,
208            #[cfg(feature = "plugin")]
209            plugin_path: None,
210            #[cfg(feature = "plugin")]
211            plugins: vec![],
212            config_path: HashMap::new(),
213            history_enabled: true,
214            history_session_id: 0,
215            history_locked_after_startup: false,
216            file: None,
217            regex_cache: Arc::new(Mutex::new(LruCache::new(
218                NonZeroUsize::new(REGEX_CACHE_SIZE).expect("tried to create cache of size zero"),
219            ))),
220            is_interactive: false,
221            is_login: false,
222            is_lsp: false,
223            is_mcp: false,
224            startup_time: -1,
225            is_debugging: IsDebugging::new(false),
226            debugger: Arc::new(Mutex::new(Box::new(NoopDebugger))),
227            report_log: Arc::default(),
228            jobs: Arc::new(Mutex::new(Jobs::default())),
229            current_job: CurrentJob {
230                id: JobId::new(0),
231                background_thread_job: None,
232                mailbox: Arc::new(Mutex::new(Mailbox::new(recv))),
233            },
234            root_job_sender: send,
235            exit_warning_given: Arc::new(AtomicBool::new(false)),
236        }
237    }
238
239    pub fn signals(&self) -> &Signals {
240        &self.signals
241    }
242
243    pub fn reset_signals(&mut self) {
244        self.signals.reset();
245        if let Some(ref handlers) = self.signal_handlers {
246            handlers.run(SignalAction::Reset);
247        }
248    }
249
250    pub fn set_signals(&mut self, signals: Signals) {
251        self.signals = signals;
252    }
253
254    /// Merges a `StateDelta` onto the current state. These deltas come from a system, like the parser, that
255    /// creates a new set of definitions and visible symbols in the current scope. We make this transactional
256    /// as there are times when we want to run the parser and immediately throw away the results (namely:
257    /// syntax highlighting and completions).
258    ///
259    /// When we want to preserve what the parser has created, we can take its output (the `StateDelta`) and
260    /// use this function to merge it into the global state.
261    pub fn merge_delta(&mut self, mut delta: StateDelta) -> Result<(), ShellError> {
262        // Take the mutable reference and extend the permanent state from the working set
263        self.files.extend(delta.files);
264        self.virtual_paths.extend(delta.virtual_paths);
265        self.vars.extend(delta.vars);
266        self.spans.extend(delta.spans);
267        self.doccomments.merge_with(delta.doccomments);
268
269        // Avoid potentially cloning the Arcs if we aren't adding anything
270        if !delta.decls.is_empty() {
271            Arc::make_mut(&mut self.decls).extend(delta.decls);
272        }
273        if !delta.blocks.is_empty() {
274            Arc::make_mut(&mut self.blocks).extend(delta.blocks);
275        }
276        if !delta.modules.is_empty() {
277            Arc::make_mut(&mut self.modules).extend(delta.modules);
278        }
279
280        let first = delta.scope.remove(0);
281
282        for (delta_name, delta_overlay) in first.clone().overlays {
283            if let Some((_, existing_overlay)) = self
284                .scope
285                .overlays
286                .iter_mut()
287                .find(|(name, _)| name == &delta_name)
288            {
289                // Updating existing overlay
290                for item in delta_overlay.decls.into_iter() {
291                    existing_overlay.decls.insert(item.0, item.1);
292                }
293                for item in delta_overlay.vars.into_iter() {
294                    existing_overlay.insert_variable(item.0, item.1);
295                }
296                for item in delta_overlay.modules.into_iter() {
297                    existing_overlay.modules.insert(item.0, item.1);
298                }
299
300                existing_overlay
301                    .visibility
302                    .merge_with(delta_overlay.visibility);
303            } else {
304                // New overlay was added to the delta
305                self.scope.overlays.push((delta_name, delta_overlay));
306            }
307        }
308
309        let mut activated_ids = self.translate_overlay_ids(&first);
310
311        let mut removed_ids = vec![];
312
313        for name in &first.removed_overlays {
314            if let Some(overlay_id) = self.find_overlay(name) {
315                removed_ids.push(overlay_id);
316            }
317        }
318
319        // Remove overlays removed in delta
320        self.scope
321            .active_overlays
322            .retain(|id| !removed_ids.contains(id));
323
324        // Move overlays activated in the delta to be first
325        self.scope
326            .active_overlays
327            .retain(|id| !activated_ids.contains(id));
328        self.scope.active_overlays.append(&mut activated_ids);
329
330        #[cfg(feature = "plugin")]
331        if !delta.plugins.is_empty() {
332            for plugin in std::mem::take(&mut delta.plugins) {
333                // Connect plugins to the signal handlers
334                if let Some(handlers) = &self.signal_handlers {
335                    plugin.clone().configure_signal_handler(handlers)?;
336                }
337
338                // Replace plugins that overlap in identity.
339                if let Some(existing) = self
340                    .plugins
341                    .iter_mut()
342                    .find(|p| p.identity().name() == plugin.identity().name())
343                {
344                    // Stop the existing plugin, so that the new plugin definitely takes over
345                    existing.stop()?;
346                    *existing = plugin;
347                } else {
348                    self.plugins.push(plugin);
349                }
350            }
351        }
352
353        #[cfg(feature = "plugin")]
354        if !delta.plugin_registry_items.is_empty() {
355            // Update the plugin file with the new signatures.
356            if self.plugin_path.is_some() {
357                self.update_plugin_file(std::mem::take(&mut delta.plugin_registry_items))?;
358            }
359        }
360
361        Ok(())
362    }
363
364    /// Merge the environment from the runtime Stack into the engine state
365    pub fn merge_env(&mut self, stack: &mut Stack) -> Result<(), ShellError> {
366        for mut scope in stack.env_vars.drain(..) {
367            for (overlay_name, mut env) in Arc::make_mut(&mut scope).drain() {
368                if let Some(env_vars) = Arc::make_mut(&mut self.env_vars).get_mut(&overlay_name) {
369                    // Updating existing overlay
370                    env_vars.extend(env.drain());
371                } else {
372                    // Pushing a new overlay
373                    Arc::make_mut(&mut self.env_vars).insert(overlay_name, env);
374                }
375            }
376        }
377
378        let cwd = self.cwd(Some(stack))?;
379        std::env::set_current_dir(cwd)
380            .map_err(|err| IoError::new_internal(err, "Could not set current dir"))?;
381
382        if let Some(config) = stack.config.take() {
383            // If config was updated in the stack, replace it.
384            self.config = config;
385
386            // Make plugin GC config changes take effect immediately.
387            #[cfg(feature = "plugin")]
388            self.update_plugin_gc_configs(&self.config.plugin_gc);
389        }
390
391        Ok(())
392    }
393
394    /// Clean up unused variables from a Stack to prevent memory leaks.
395    /// This removes variables that are no longer referenced by any overlay.
396    pub fn cleanup_stack_variables(&mut self, stack: &mut Stack) {
397        use std::collections::HashSet;
398
399        let mut shadowed_vars = HashSet::new();
400        for (_, frame) in self.scope.overlays.iter_mut() {
401            shadowed_vars.extend(frame.shadowed_vars.to_owned());
402            frame.shadowed_vars.clear();
403        }
404
405        // Remove variables from stack that are no longer referenced
406        stack
407            .vars
408            .retain(|(var_id, _)| !shadowed_vars.contains(var_id));
409    }
410
411    pub fn active_overlay_ids<'a, 'b>(
412        &'b self,
413        removed_overlays: &'a [Vec<u8>],
414    ) -> impl DoubleEndedIterator<Item = &'b OverlayId> + 'a
415    where
416        'b: 'a,
417    {
418        self.scope.active_overlays.iter().filter(|id| {
419            !removed_overlays
420                .iter()
421                .any(|name| name == self.get_overlay_name(**id))
422        })
423    }
424
425    pub fn active_overlays<'a, 'b>(
426        &'b self,
427        removed_overlays: &'a [Vec<u8>],
428    ) -> impl DoubleEndedIterator<Item = &'b OverlayFrame> + 'a
429    where
430        'b: 'a,
431    {
432        self.active_overlay_ids(removed_overlays)
433            .map(|id| self.get_overlay(*id))
434    }
435
436    pub fn active_overlay_names<'a, 'b>(
437        &'b self,
438        removed_overlays: &'a [Vec<u8>],
439    ) -> impl DoubleEndedIterator<Item = &'b [u8]> + 'a
440    where
441        'b: 'a,
442    {
443        self.active_overlay_ids(removed_overlays)
444            .map(|id| self.get_overlay_name(*id))
445    }
446
447    /// Translate overlay IDs from other to IDs in self
448    fn translate_overlay_ids(&self, other: &ScopeFrame) -> Vec<OverlayId> {
449        let other_names = other.active_overlays.iter().map(|other_id| {
450            &other
451                .overlays
452                .get(other_id.get())
453                .expect("internal error: missing overlay")
454                .0
455        });
456
457        other_names
458            .map(|other_name| {
459                self.find_overlay(other_name)
460                    .expect("internal error: missing overlay")
461            })
462            .collect()
463    }
464
465    pub fn last_overlay_name(&self, removed_overlays: &[Vec<u8>]) -> &[u8] {
466        self.active_overlay_names(removed_overlays)
467            .last()
468            .expect("internal error: no active overlays")
469    }
470
471    pub fn last_overlay(&self, removed_overlays: &[Vec<u8>]) -> &OverlayFrame {
472        self.active_overlay_ids(removed_overlays)
473            .last()
474            .map(|id| self.get_overlay(*id))
475            .expect("internal error: no active overlays")
476    }
477
478    pub fn get_overlay_name(&self, overlay_id: OverlayId) -> &[u8] {
479        &self
480            .scope
481            .overlays
482            .get(overlay_id.get())
483            .expect("internal error: missing overlay")
484            .0
485    }
486
487    pub fn get_overlay(&self, overlay_id: OverlayId) -> &OverlayFrame {
488        &self
489            .scope
490            .overlays
491            .get(overlay_id.get())
492            .expect("internal error: missing overlay")
493            .1
494    }
495
496    pub fn render_env_vars(&self) -> HashMap<&str, &Value> {
497        let mut result: HashMap<&str, &Value> = HashMap::new();
498
499        for overlay_name in self.active_overlay_names(&[]) {
500            let name = String::from_utf8_lossy(overlay_name);
501            if let Some(env_vars) = self.env_vars.get(name.as_ref()) {
502                result.extend(env_vars.iter().map(|(k, v)| (k.as_str(), v)));
503            }
504        }
505
506        result
507    }
508
509    pub fn add_env_var(&mut self, name: String, val: Value) {
510        let overlay_name = String::from_utf8_lossy(self.last_overlay_name(&[])).to_string();
511
512        if let Some(env_vars) = Arc::make_mut(&mut self.env_vars).get_mut(&overlay_name) {
513            env_vars.insert(EnvName::from(name), val);
514        } else {
515            Arc::make_mut(&mut self.env_vars).insert(
516                overlay_name,
517                [(EnvName::from(name), val)].into_iter().collect(),
518            );
519        }
520    }
521
522    pub fn get_env_var(&self, name: &str) -> Option<&Value> {
523        for overlay_id in self.scope.active_overlays.iter().rev() {
524            let overlay_name = String::from_utf8_lossy(self.get_overlay_name(*overlay_id));
525            if let Some(env_vars) = self.env_vars.get(overlay_name.as_ref())
526                && let Some(val) = env_vars.get(&EnvName::from(name))
527            {
528                return Some(val);
529            }
530        }
531
532        None
533    }
534
535    #[cfg(feature = "plugin")]
536    pub fn plugins(&self) -> &[Arc<dyn RegisteredPlugin>] {
537        &self.plugins
538    }
539
540    #[cfg(feature = "plugin")]
541    fn update_plugin_file(&self, updated_items: Vec<PluginRegistryItem>) -> Result<(), ShellError> {
542        // Updating the signatures plugin file with the added signatures
543        use std::fs::File;
544
545        let plugin_path = self.plugin_path.as_ref().ok_or_else(|| {
546            ShellError::Generic(
547                GenericError::new_internal("Plugin file path not set", "")
548                    .with_help("you may be running nu with --no-config-file"),
549            )
550        })?;
551
552        // Read the current contents of the plugin file if it exists
553        let mut contents = match File::open(plugin_path.as_path()) {
554            Ok(mut plugin_file) => PluginRegistryFile::read_from(&mut plugin_file, None),
555            Err(err) => {
556                if err.kind() == std::io::ErrorKind::NotFound {
557                    Ok(PluginRegistryFile::default())
558                } else {
559                    Err(ShellError::Io(IoError::new_internal_with_path(
560                        err,
561                        "Failed to open plugin file",
562                        PathBuf::from(plugin_path),
563                    )))
564                }
565            }
566        }?;
567
568        // Update the given signatures
569        for item in updated_items {
570            contents.upsert_plugin(item);
571        }
572
573        // Write it to the same path
574        let plugin_file = File::create(plugin_path.as_path()).map_err(|err| {
575            IoError::new_internal_with_path(
576                err,
577                "Failed to write plugin file",
578                PathBuf::from(plugin_path),
579            )
580        })?;
581
582        contents.write_to(plugin_file, None)
583    }
584
585    /// Update plugins with new garbage collection config
586    #[cfg(feature = "plugin")]
587    fn update_plugin_gc_configs(&self, plugin_gc: &crate::PluginGcConfigs) {
588        for plugin in &self.plugins {
589            plugin.set_gc_config(plugin_gc.get(plugin.identity().name()));
590        }
591    }
592
593    pub fn num_files(&self) -> usize {
594        self.files.len()
595    }
596
597    pub fn num_virtual_paths(&self) -> usize {
598        self.virtual_paths.len()
599    }
600
601    pub fn num_vars(&self) -> usize {
602        self.vars.len()
603    }
604
605    pub fn num_decls(&self) -> usize {
606        self.decls.len()
607    }
608
609    pub fn num_blocks(&self) -> usize {
610        self.blocks.len()
611    }
612
613    pub fn num_modules(&self) -> usize {
614        self.modules.len()
615    }
616
617    pub fn num_spans(&self) -> usize {
618        self.spans.len()
619    }
620    pub fn print_vars(&self) {
621        for var in self.vars.iter().enumerate() {
622            println!("var{}: {:?}", var.0, var.1);
623        }
624    }
625
626    pub fn print_decls(&self) {
627        for decl in self.decls.iter().enumerate() {
628            println!("decl{}: {:?}", decl.0, decl.1.signature());
629        }
630    }
631
632    pub fn print_blocks(&self) {
633        for block in self.blocks.iter().enumerate() {
634            println!("block{}: {:?}", block.0, block.1);
635        }
636    }
637
638    pub fn print_contents(&self) {
639        for cached_file in self.files.iter() {
640            let string = String::from_utf8_lossy(&cached_file.content);
641            println!("{string}");
642        }
643    }
644
645    /// Find the [`DeclId`](crate::DeclId) corresponding to a declaration with `name`.
646    ///
647    /// Searches within active overlays, and filtering out overlays in `removed_overlays`.
648    pub fn find_decl(&self, name: &[u8], removed_overlays: &[Vec<u8>]) -> Option<DeclId> {
649        let mut visibility: Visibility = Visibility::new();
650
651        for overlay_frame in self.active_overlays(removed_overlays).rev() {
652            visibility.append(&overlay_frame.visibility);
653
654            if let Some(decl_id) = overlay_frame.get_decl(name)
655                && visibility.is_decl_id_visible(&decl_id)
656            {
657                return Some(decl_id);
658            }
659        }
660
661        None
662    }
663
664    /// Find the name of the declaration corresponding to `decl_id`.
665    ///
666    /// Searches within active overlays, and filtering out overlays in `removed_overlays`.
667    pub fn find_decl_name(&self, decl_id: DeclId, removed_overlays: &[Vec<u8>]) -> Option<&[u8]> {
668        let mut visibility: Visibility = Visibility::new();
669
670        for overlay_frame in self.active_overlays(removed_overlays).rev() {
671            visibility.append(&overlay_frame.visibility);
672
673            if visibility.is_decl_id_visible(&decl_id) {
674                for (name, id) in overlay_frame.decls.iter() {
675                    if id == &decl_id {
676                        return Some(name);
677                    }
678                }
679            }
680        }
681
682        None
683    }
684
685    /// Find the [`OverlayId`](crate::OverlayId) corresponding to `name`.
686    ///
687    /// Searches all overlays, not just active overlays. To search only in active overlays, use [`find_active_overlay`](EngineState::find_active_overlay)
688    pub fn find_overlay(&self, name: &[u8]) -> Option<OverlayId> {
689        self.scope.find_overlay(name)
690    }
691
692    /// Find the [`OverlayId`](crate::OverlayId) of the active overlay corresponding to `name`.
693    ///
694    /// Searches only active overlays. To search in all overlays, use [`find_overlay`](EngineState::find_active_overlay)
695    pub fn find_active_overlay(&self, name: &[u8]) -> Option<OverlayId> {
696        self.scope.find_active_overlay(name)
697    }
698
699    /// Find the [`ModuleId`](crate::ModuleId) corresponding to `name`.
700    ///
701    /// Searches within active overlays, and filtering out overlays in `removed_overlays`.
702    pub fn find_module(&self, name: &[u8], removed_overlays: &[Vec<u8>]) -> Option<ModuleId> {
703        for overlay_frame in self.active_overlays(removed_overlays).rev() {
704            if let Some(module_id) = overlay_frame.modules.get(name) {
705                return Some(*module_id);
706            }
707        }
708
709        None
710    }
711
712    pub fn get_module_comments(&self, module_id: ModuleId) -> Option<&[Span]> {
713        self.doccomments.get_module_comments(module_id)
714    }
715
716    #[cfg(feature = "plugin")]
717    pub fn plugin_decls(&self) -> impl Iterator<Item = &Box<dyn Command + 'static>> {
718        let mut unique_plugin_decls = HashMap::new();
719
720        // Make sure there are no duplicate decls: Newer one overwrites the older one
721        for decl in self.decls.iter().filter(|d| d.is_plugin()) {
722            unique_plugin_decls.insert(decl.name(), decl);
723        }
724
725        let mut plugin_decls: Vec<(&str, &Box<dyn Command>)> =
726            unique_plugin_decls.into_iter().collect();
727
728        // Sort the plugins by name so we don't end up with a random plugin file each time
729        plugin_decls.sort_by(|a, b| a.0.cmp(b.0));
730        plugin_decls.into_iter().map(|(_, decl)| decl)
731    }
732
733    pub fn which_module_has_decl(
734        &self,
735        decl_name: &[u8],
736        removed_overlays: &[Vec<u8>],
737    ) -> Option<&[u8]> {
738        for overlay_frame in self.active_overlays(removed_overlays).rev() {
739            for (module_name, module_id) in overlay_frame.modules.iter() {
740                let module = self.get_module(*module_id);
741                if module.has_decl(decl_name) {
742                    return Some(module_name);
743                }
744            }
745        }
746
747        None
748    }
749
750    /// Apply a function to all commands. The function accepts a command name and its DeclId
751    pub fn traverse_commands(&self, mut f: impl FnMut(&[u8], DeclId)) {
752        for overlay_frame in self.active_overlays(&[]).rev() {
753            for (name, decl_id) in &overlay_frame.decls {
754                if overlay_frame.visibility.is_decl_id_visible(decl_id) {
755                    f(name, *decl_id);
756                }
757            }
758        }
759    }
760
761    pub fn get_span_contents(&self, span: Span) -> &[u8] {
762        self.try_get_file_contents(span).unwrap_or(&[0u8; 0])
763    }
764
765    pub fn try_get_file_contents(&self, span: Span) -> Option<&[u8]> {
766        self.files.iter().find_map(|file| {
767            if file.covered_span.contains_span(span) {
768                let start = span.start - file.covered_span.start;
769                let end = span.end - file.covered_span.start;
770                Some(&file.content[start..end])
771            } else {
772                None
773            }
774        })
775    }
776
777    /// If the span's content starts with the given prefix, return two subspans
778    /// corresponding to this prefix, and the rest of the content.
779    pub fn span_match_prefix(&self, span: Span, prefix: &[u8]) -> Option<(Span, Span)> {
780        let contents = self.get_span_contents(span);
781
782        if contents.starts_with(prefix) {
783            span.split_at(prefix.len())
784        } else {
785            None
786        }
787    }
788
789    /// If the span's content ends with the given postfix, return two subspans
790    /// corresponding to the rest of the content, and this postfix.
791    pub fn span_match_postfix(&self, span: Span, prefix: &[u8]) -> Option<(Span, Span)> {
792        let contents = self.get_span_contents(span);
793
794        if contents.ends_with(prefix) {
795            span.split_at(span.len() - prefix.len())
796        } else {
797            None
798        }
799    }
800
801    /// Get the global config from the engine state.
802    ///
803    /// Use [`Stack::get_config()`] instead whenever the `Stack` is available, as it takes into
804    /// account local changes to `$env.config`.
805    pub fn get_config(&self) -> &Arc<Config> {
806        &self.config
807    }
808
809    pub fn set_config(&mut self, conf: impl Into<Arc<Config>>) {
810        let conf = conf.into();
811
812        #[cfg(feature = "plugin")]
813        if conf.plugin_gc != self.config.plugin_gc {
814            // Make plugin GC config changes take effect immediately.
815            self.update_plugin_gc_configs(&conf.plugin_gc);
816        }
817
818        self.config = conf;
819    }
820
821    /// Fetch the configuration for a plugin
822    ///
823    /// The `plugin` must match the registered name of a plugin.  For `plugin add
824    /// nu_plugin_example` the plugin name to use will be `"example"`
825    pub fn get_plugin_config(&self, plugin: &str) -> Option<&Value> {
826        self.config.plugins.get(plugin)
827    }
828
829    /// Returns the configuration settings for command history or `None` if history is disabled
830    pub fn history_config(&self) -> Option<HistoryConfig> {
831        self.history_enabled.then(|| self.config.history.clone())
832    }
833
834    pub fn get_var(&self, var_id: VarId) -> &Variable {
835        self.vars
836            .get(var_id.get())
837            .expect("internal error: missing variable")
838    }
839
840    pub fn get_constant(&self, var_id: VarId) -> Option<&Value> {
841        let var = self.get_var(var_id);
842        var.const_val.as_ref()
843    }
844
845    pub fn generate_nu_constant(&mut self) {
846        self.vars[NU_VARIABLE_ID.get()].const_val = Some(create_nu_constant(self, Span::unknown()));
847    }
848
849    pub fn get_decl(&self, decl_id: DeclId) -> &dyn Command {
850        self.decls
851            .get(decl_id.get())
852            .expect("internal error: missing declaration")
853            .as_ref()
854    }
855
856    /// Get all commands within scope, sorted by the commands' names
857    pub fn get_decls_sorted(&self, include_hidden: bool) -> Vec<(Vec<u8>, DeclId)> {
858        let mut decls_map = HashMap::new();
859
860        for overlay_frame in self.active_overlays(&[]) {
861            let new_decls = if include_hidden {
862                overlay_frame.decls.clone()
863            } else {
864                overlay_frame
865                    .decls
866                    .clone()
867                    .into_iter()
868                    .filter(|(_, id)| overlay_frame.visibility.is_decl_id_visible(id))
869                    .collect()
870            };
871
872            decls_map.extend(new_decls);
873        }
874
875        let mut decls: Vec<(Vec<u8>, DeclId)> = decls_map.into_iter().collect();
876
877        decls.sort_by(|a, b| a.0.cmp(&b.0));
878        decls
879    }
880
881    pub fn get_signature(&self, decl: &dyn Command) -> Signature {
882        if let Some(block_id) = decl.block_id() {
883            *self.blocks[block_id.get()].signature.clone()
884        } else {
885            decl.signature()
886        }
887    }
888
889    /// Get signatures of all commands within scope with their decl ids.
890    pub fn get_signatures_and_declids(&self, include_hidden: bool) -> Vec<(Signature, DeclId)> {
891        self.get_decls_sorted(include_hidden)
892            .into_iter()
893            .map(|(_, id)| {
894                let decl = self.get_decl(id);
895
896                (self.get_signature(decl).update_from_command(decl), id)
897            })
898            .collect()
899    }
900
901    pub fn get_block(&self, block_id: BlockId) -> &Arc<Block> {
902        self.blocks
903            .get(block_id.get())
904            .expect("internal error: missing block")
905    }
906
907    /// Optionally get a block by id, if it exists
908    ///
909    /// Prefer to use [`.get_block()`](Self::get_block) in most cases - `BlockId`s that don't exist
910    /// are normally a compiler error. This only exists to stop plugins from crashing the engine if
911    /// they send us something invalid.
912    pub fn try_get_block(&self, block_id: BlockId) -> Option<&Arc<Block>> {
913        self.blocks.get(block_id.get())
914    }
915
916    pub fn get_module(&self, module_id: ModuleId) -> &Module {
917        self.modules
918            .get(module_id.get())
919            .expect("internal error: missing module")
920    }
921
922    pub fn get_virtual_path(&self, virtual_path_id: VirtualPathId) -> &(String, VirtualPath) {
923        self.virtual_paths
924            .get(virtual_path_id.get())
925            .expect("internal error: missing virtual path")
926    }
927
928    pub fn next_span_start(&self) -> usize {
929        if let Some(cached_file) = self.files.last() {
930            cached_file.covered_span.end
931        } else {
932            0
933        }
934    }
935
936    pub fn files(
937        &self,
938    ) -> impl DoubleEndedIterator<Item = &CachedFile> + ExactSizeIterator<Item = &CachedFile> {
939        self.files.iter()
940    }
941
942    pub fn add_file(&mut self, filename: Arc<str>, content: Arc<[u8]>) -> FileId {
943        let next_span_start = self.next_span_start();
944        let next_span_end = next_span_start + content.len();
945
946        let covered_span = Span::new(next_span_start, next_span_end);
947
948        self.files.push(CachedFile {
949            name: filename,
950            content,
951            covered_span,
952        });
953
954        FileId::new(self.num_files() - 1)
955    }
956
957    pub fn set_config_path(&mut self, key: &str, val: PathBuf) {
958        self.config_path.insert(key.to_string(), val);
959    }
960
961    pub fn get_config_path(&self, key: &str) -> Option<&PathBuf> {
962        self.config_path.get(key)
963    }
964
965    pub fn build_desc(&self, spans: &[Span]) -> (String, String) {
966        let comment_lines: Vec<&[u8]> = spans
967            .iter()
968            .map(|span| self.get_span_contents(*span))
969            .collect();
970        build_desc(&comment_lines)
971    }
972
973    pub fn build_module_desc(&self, module_id: ModuleId) -> Option<(String, String)> {
974        self.get_module_comments(module_id)
975            .map(|comment_spans| self.build_desc(comment_spans))
976    }
977
978    /// Returns the current working directory, which is guaranteed to be canonicalized.
979    ///
980    /// Returns an empty String if $env.PWD doesn't exist.
981    #[deprecated(since = "0.92.3", note = "please use `EngineState::cwd()` instead")]
982    pub fn current_work_dir(&self) -> String {
983        self.cwd(None)
984            .map(|path| path.to_string_lossy().to_string())
985            .unwrap_or_default()
986    }
987
988    /// Returns the current working directory, which is guaranteed to be an
989    /// absolute path without trailing slashes (unless it's the root path), but
990    /// might contain symlink components.
991    ///
992    /// If `stack` is supplied, also considers modifications to the working
993    /// directory on the stack that have yet to be merged into the engine state.
994    pub fn cwd(&self, stack: Option<&Stack>) -> Result<AbsolutePathBuf, ShellError> {
995        // Helper function to create a simple generic error.
996        fn error(msg: &str, cwd: impl AsRef<nu_path::Path>) -> ShellError {
997            ShellError::Generic(
998                GenericError::new_internal(
999                    msg.to_string(),
1000                    format!("$env.PWD = {}", cwd.as_ref().display()),
1001                )
1002                .with_help("Use `cd` to reset $env.PWD into a good state"),
1003            )
1004        }
1005
1006        // Retrieve $env.PWD from the stack or the engine state.
1007        let pwd = if let Some(stack) = stack {
1008            stack.get_env_var(self, "PWD")
1009        } else {
1010            self.get_env_var("PWD")
1011        };
1012
1013        let pwd = pwd.ok_or_else(|| error("$env.PWD not found", ""))?;
1014
1015        if let Ok(pwd) = pwd.as_str() {
1016            let path = AbsolutePathBuf::try_from(pwd)
1017                .map_err(|_| error("$env.PWD is not an absolute path", pwd))?;
1018
1019            // Technically, a root path counts as "having trailing slashes", but
1020            // for the purpose of PWD, a root path is acceptable.
1021            if path.parent().is_some() && nu_path::has_trailing_slash(path.as_ref()) {
1022                Err(error("$env.PWD contains trailing slashes", &path))
1023            } else if !path.exists() {
1024                Err(error("$env.PWD points to a non-existent directory", &path))
1025            } else if !path.is_dir() {
1026                Err(error("$env.PWD points to a non-directory", &path))
1027            } else {
1028                Ok(path)
1029            }
1030        } else {
1031            Err(error("$env.PWD is not a string", format!("{pwd:?}")))
1032        }
1033    }
1034
1035    /// Like `EngineState::cwd()`, but returns a String instead of a PathBuf for convenience.
1036    pub fn cwd_as_string(&self, stack: Option<&Stack>) -> Result<String, ShellError> {
1037        let cwd = self.cwd(stack)?;
1038        cwd.into_os_string()
1039            .into_string()
1040            .map_err(|err| ShellError::NonUtf8Custom {
1041                msg: format!("The current working directory is not a valid utf-8 string: {err:?}"),
1042                span: Span::unknown(),
1043            })
1044    }
1045
1046    // TODO: see if we can completely get rid of this
1047    pub fn get_file_contents(&self) -> &[CachedFile] {
1048        &self.files
1049    }
1050
1051    pub fn get_startup_time(&self) -> i64 {
1052        self.startup_time
1053    }
1054
1055    pub fn set_startup_time(&mut self, startup_time: i64) {
1056        self.startup_time = startup_time;
1057    }
1058
1059    pub fn activate_debugger(
1060        &self,
1061        debugger: Box<dyn Debugger>,
1062    ) -> Result<(), PoisonDebuggerError<'_>> {
1063        let mut locked_debugger = self.debugger.lock()?;
1064        *locked_debugger = debugger;
1065        locked_debugger.activate();
1066        self.is_debugging.0.store(true, Ordering::Relaxed);
1067        Ok(())
1068    }
1069
1070    pub fn deactivate_debugger(&self) -> Result<Box<dyn Debugger>, PoisonDebuggerError<'_>> {
1071        let mut locked_debugger = self.debugger.lock()?;
1072        locked_debugger.deactivate();
1073        let ret = std::mem::replace(&mut *locked_debugger, Box::new(NoopDebugger));
1074        self.is_debugging.0.store(false, Ordering::Relaxed);
1075        Ok(ret)
1076    }
1077
1078    pub fn is_debugging(&self) -> bool {
1079        self.is_debugging.0.load(Ordering::Relaxed)
1080    }
1081
1082    pub fn recover_from_panic(&mut self) {
1083        if Mutex::is_poisoned(&self.repl_state) {
1084            self.repl_state = Arc::new(Mutex::new(ReplState {
1085                buffer: "".to_string(),
1086                cursor_pos: 0,
1087                accept: false,
1088            }));
1089        }
1090        if Mutex::is_poisoned(&self.jobs) {
1091            self.jobs = Arc::new(Mutex::new(Jobs::default()));
1092        }
1093        if Mutex::is_poisoned(&self.regex_cache) {
1094            self.regex_cache = Arc::new(Mutex::new(LruCache::new(
1095                NonZeroUsize::new(REGEX_CACHE_SIZE).expect("tried to create cache of size zero"),
1096            )));
1097        }
1098    }
1099
1100    /// Add new span and return its ID
1101    pub fn add_span(&mut self, span: Span) -> SpanId {
1102        self.spans.push(span);
1103        SpanId::new(self.num_spans() - 1)
1104    }
1105
1106    /// Find ID of a span (should be avoided if possible)
1107    pub fn find_span_id(&self, span: Span) -> Option<SpanId> {
1108        self.spans
1109            .iter()
1110            .position(|sp| sp == &span)
1111            .map(SpanId::new)
1112    }
1113
1114    // Determines whether the current state is being held by a background job
1115    pub fn is_background_job(&self) -> bool {
1116        self.current_job.background_thread_job.is_some()
1117    }
1118
1119    // Gets the thread job entry
1120    pub fn current_thread_job(&self) -> Option<&ThreadJob> {
1121        self.current_job.background_thread_job.as_ref()
1122    }
1123}
1124
1125impl GetSpan for &EngineState {
1126    /// Get existing span
1127    fn get_span(&self, span_id: SpanId) -> Span {
1128        *self
1129            .spans
1130            .get(span_id.get())
1131            .expect("internal error: missing span")
1132    }
1133}
1134
1135impl Default for EngineState {
1136    fn default() -> Self {
1137        Self::new()
1138    }
1139}
1140
1141#[cfg(test)]
1142mod engine_state_tests {
1143    use crate::engine::StateWorkingSet;
1144    use std::str::{Utf8Error, from_utf8};
1145
1146    use super::*;
1147
1148    #[test]
1149    fn add_file_gives_id() {
1150        let engine_state = EngineState::new();
1151        let mut engine_state = StateWorkingSet::new(&engine_state);
1152        let id = engine_state.add_file("test.nu", &[]);
1153
1154        assert_eq!(id, FileId::new(0));
1155    }
1156
1157    #[test]
1158    fn add_file_gives_id_including_parent() {
1159        let mut engine_state = EngineState::new();
1160        let parent_id = engine_state.add_file("test.nu".into(), Arc::new([]));
1161
1162        let mut working_set = StateWorkingSet::new(&engine_state);
1163        let working_set_id = working_set.add_file("child.nu", &[]);
1164
1165        assert_eq!(parent_id, FileId::new(0));
1166        assert_eq!(working_set_id, FileId::new(1));
1167    }
1168
1169    #[test]
1170    fn merge_states() -> Result<(), ShellError> {
1171        let mut engine_state = EngineState::new();
1172        engine_state.add_file("test.nu".into(), Arc::new([]));
1173
1174        let delta = {
1175            let mut working_set = StateWorkingSet::new(&engine_state);
1176            let _ = working_set.add_file("child.nu", &[]);
1177            working_set.render()
1178        };
1179
1180        engine_state.merge_delta(delta)?;
1181
1182        assert_eq!(engine_state.num_files(), 2);
1183        assert_eq!(&*engine_state.files[0].name, "test.nu");
1184        assert_eq!(&*engine_state.files[1].name, "child.nu");
1185
1186        Ok(())
1187    }
1188
1189    #[test]
1190    fn list_variables() -> Result<(), Utf8Error> {
1191        let varname = "something";
1192        let varname_with_sigil = "$".to_owned() + varname;
1193        let engine_state = EngineState::new();
1194        let mut working_set = StateWorkingSet::new(&engine_state);
1195        working_set.add_variable(
1196            varname.as_bytes().into(),
1197            Span { start: 0, end: 1 },
1198            Type::Int,
1199            false,
1200        );
1201        let variables = working_set
1202            .list_variables()
1203            .into_iter()
1204            .map(from_utf8)
1205            .collect::<Result<Vec<&str>, Utf8Error>>()?;
1206        assert_eq!(variables, vec![varname_with_sigil]);
1207        Ok(())
1208    }
1209
1210    #[test]
1211    fn get_plugin_config() {
1212        let mut engine_state = EngineState::new();
1213
1214        assert!(
1215            engine_state.get_plugin_config("example").is_none(),
1216            "Unexpected plugin configuration"
1217        );
1218
1219        let mut plugins = HashMap::new();
1220        plugins.insert("example".into(), Value::string("value", Span::test_data()));
1221
1222        let mut config = Config::clone(engine_state.get_config());
1223        config.plugins = plugins;
1224
1225        engine_state.set_config(config);
1226
1227        assert!(
1228            engine_state.get_plugin_config("example").is_some(),
1229            "Plugin configuration not found"
1230        );
1231    }
1232}
1233
1234#[cfg(test)]
1235mod test_cwd {
1236    //! Here're the test cases we need to cover:
1237    //!
1238    //! `EngineState::cwd()` computes the result from `self.env_vars["PWD"]` and
1239    //! optionally `stack.env_vars["PWD"]`.
1240    //!
1241    //! PWD may be unset in either `env_vars`.
1242    //! PWD should NOT be an empty string.
1243    //! PWD should NOT be a non-string value.
1244    //! PWD should NOT be a relative path.
1245    //! PWD should NOT contain trailing slashes.
1246    //! PWD may point to a directory or a symlink to directory.
1247    //! PWD should NOT point to a file or a symlink to file.
1248    //! PWD should NOT point to non-existent entities in the filesystem.
1249
1250    use crate::{
1251        Value,
1252        engine::{EngineState, Stack},
1253    };
1254    use nu_path::{AbsolutePath, Path, assert_path_eq};
1255    use tempfile::{NamedTempFile, TempDir};
1256
1257    /// Creates a symlink. Works on both Unix and Windows.
1258    #[cfg(any(unix, windows))]
1259    fn symlink(
1260        original: impl AsRef<AbsolutePath>,
1261        link: impl AsRef<AbsolutePath>,
1262    ) -> std::io::Result<()> {
1263        let original = original.as_ref();
1264        let link = link.as_ref();
1265
1266        #[cfg(unix)]
1267        {
1268            std::os::unix::fs::symlink(original, link)
1269        }
1270        #[cfg(windows)]
1271        {
1272            if original.is_dir() {
1273                std::os::windows::fs::symlink_dir(original, link)
1274            } else {
1275                std::os::windows::fs::symlink_file(original, link)
1276            }
1277        }
1278    }
1279
1280    /// Create an engine state initialized with the given PWD.
1281    fn engine_state_with_pwd(path: impl AsRef<Path>) -> EngineState {
1282        let mut engine_state = EngineState::new();
1283        engine_state.add_env_var(
1284            "PWD".into(),
1285            Value::test_string(path.as_ref().to_str().unwrap()),
1286        );
1287        engine_state
1288    }
1289
1290    /// Create a stack initialized with the given PWD.
1291    fn stack_with_pwd(path: impl AsRef<Path>) -> Stack {
1292        let mut stack = Stack::new();
1293        stack.add_env_var(
1294            "PWD".into(),
1295            Value::test_string(path.as_ref().to_str().unwrap()),
1296        );
1297        stack
1298    }
1299
1300    #[test]
1301    fn pwd_not_set() {
1302        let engine_state = EngineState::new();
1303        engine_state.cwd(None).unwrap_err();
1304    }
1305
1306    #[test]
1307    fn pwd_is_empty_string() {
1308        let engine_state = engine_state_with_pwd("");
1309        engine_state.cwd(None).unwrap_err();
1310    }
1311
1312    #[test]
1313    fn pwd_is_non_string_value() {
1314        let mut engine_state = EngineState::new();
1315        engine_state.add_env_var("PWD".into(), Value::test_glob("*"));
1316        engine_state.cwd(None).unwrap_err();
1317    }
1318
1319    #[test]
1320    fn pwd_is_relative_path() {
1321        let engine_state = engine_state_with_pwd("./foo");
1322
1323        engine_state.cwd(None).unwrap_err();
1324    }
1325
1326    #[test]
1327    fn pwd_has_trailing_slash() {
1328        let dir = TempDir::new().unwrap();
1329        let engine_state = engine_state_with_pwd(dir.path().join(""));
1330
1331        engine_state.cwd(None).unwrap_err();
1332    }
1333
1334    #[test]
1335    fn pwd_points_to_root() {
1336        #[cfg(windows)]
1337        let root = Path::new(r"C:\");
1338        #[cfg(not(windows))]
1339        let root = Path::new("/");
1340
1341        let engine_state = engine_state_with_pwd(root);
1342        let cwd = engine_state.cwd(None).unwrap();
1343        assert_path_eq!(cwd, root);
1344    }
1345
1346    #[test]
1347    fn pwd_points_to_normal_file() {
1348        let file = NamedTempFile::new().unwrap();
1349        let engine_state = engine_state_with_pwd(file.path());
1350
1351        engine_state.cwd(None).unwrap_err();
1352    }
1353
1354    #[test]
1355    fn pwd_points_to_normal_directory() {
1356        let dir = TempDir::new().unwrap();
1357        let engine_state = engine_state_with_pwd(dir.path());
1358
1359        let cwd = engine_state.cwd(None).unwrap();
1360        assert_path_eq!(cwd, dir.path());
1361    }
1362
1363    #[test]
1364    fn pwd_points_to_symlink_to_file() {
1365        let file = NamedTempFile::new().unwrap();
1366        let temp_file = AbsolutePath::try_new(file.path()).unwrap();
1367        let dir = TempDir::new().unwrap();
1368        let temp = AbsolutePath::try_new(dir.path()).unwrap();
1369
1370        let link = temp.join("link");
1371        symlink(temp_file, &link).unwrap();
1372        let engine_state = engine_state_with_pwd(&link);
1373
1374        engine_state.cwd(None).unwrap_err();
1375    }
1376
1377    #[test]
1378    fn pwd_points_to_symlink_to_directory() {
1379        let dir = TempDir::new().unwrap();
1380        let temp = AbsolutePath::try_new(dir.path()).unwrap();
1381
1382        let link = temp.join("link");
1383        symlink(temp, &link).unwrap();
1384        let engine_state = engine_state_with_pwd(&link);
1385
1386        let cwd = engine_state.cwd(None).unwrap();
1387        assert_path_eq!(cwd, link);
1388    }
1389
1390    #[test]
1391    fn pwd_points_to_broken_symlink() {
1392        let dir = TempDir::new().unwrap();
1393        let temp = AbsolutePath::try_new(dir.path()).unwrap();
1394        let other_dir = TempDir::new().unwrap();
1395        let other_temp = AbsolutePath::try_new(other_dir.path()).unwrap();
1396
1397        let link = temp.join("link");
1398        symlink(other_temp, &link).unwrap();
1399        let engine_state = engine_state_with_pwd(&link);
1400
1401        drop(other_dir);
1402        engine_state.cwd(None).unwrap_err();
1403    }
1404
1405    #[test]
1406    fn pwd_points_to_nonexistent_entity() {
1407        let engine_state = engine_state_with_pwd(TempDir::new().unwrap().path());
1408
1409        engine_state.cwd(None).unwrap_err();
1410    }
1411
1412    #[test]
1413    fn stack_pwd_not_set() {
1414        let dir = TempDir::new().unwrap();
1415        let engine_state = engine_state_with_pwd(dir.path());
1416        let stack = Stack::new();
1417
1418        let cwd = engine_state.cwd(Some(&stack)).unwrap();
1419        assert_eq!(cwd, dir.path());
1420    }
1421
1422    #[test]
1423    fn stack_pwd_is_empty_string() {
1424        let dir = TempDir::new().unwrap();
1425        let engine_state = engine_state_with_pwd(dir.path());
1426        let stack = stack_with_pwd("");
1427
1428        engine_state.cwd(Some(&stack)).unwrap_err();
1429    }
1430
1431    #[test]
1432    fn stack_pwd_points_to_normal_directory() {
1433        let dir1 = TempDir::new().unwrap();
1434        let dir2 = TempDir::new().unwrap();
1435        let engine_state = engine_state_with_pwd(dir1.path());
1436        let stack = stack_with_pwd(dir2.path());
1437
1438        let cwd = engine_state.cwd(Some(&stack)).unwrap();
1439        assert_path_eq!(cwd, dir2.path());
1440    }
1441
1442    #[test]
1443    fn stack_pwd_points_to_normal_directory_with_symlink_components() {
1444        let dir = TempDir::new().unwrap();
1445        let temp = AbsolutePath::try_new(dir.path()).unwrap();
1446
1447        // `/tmp/dir/link` points to `/tmp/dir`, then we set PWD to `/tmp/dir/link/foo`
1448        let link = temp.join("link");
1449        symlink(temp, &link).unwrap();
1450        let foo = link.join("foo");
1451        std::fs::create_dir(temp.join("foo")).unwrap();
1452        let engine_state = EngineState::new();
1453        let stack = stack_with_pwd(&foo);
1454
1455        let cwd = engine_state.cwd(Some(&stack)).unwrap();
1456        assert_path_eq!(cwd, foo);
1457    }
1458}