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, EnvVars, OverlayFrame, ScopeFrame, Stack,
9        StateDelta, Variable, Visibility,
10        description::{Doccomments, build_desc},
11    },
12    eval_const::create_nu_constant,
13    report_error::ReportLog,
14    shell_error::io::IoError,
15};
16use fancy_regex::Regex;
17use lru::LruCache;
18use nu_path::AbsolutePathBuf;
19use nu_utils::IgnoreCaseExt;
20use std::{
21    collections::HashMap,
22    num::NonZeroUsize,
23    path::PathBuf,
24    sync::{
25        Arc, Mutex, MutexGuard, PoisonError,
26        atomic::{AtomicBool, AtomicU32, Ordering},
27        mpsc::Sender,
28        mpsc::channel,
29    },
30};
31
32type PoisonDebuggerError<'a> = PoisonError<MutexGuard<'a, Box<dyn Debugger>>>;
33
34#[cfg(feature = "plugin")]
35use crate::{PluginRegistryFile, PluginRegistryItem, RegisteredPlugin};
36
37use super::{CurrentJob, Jobs, Mail, Mailbox, ThreadJob};
38
39#[derive(Clone, Debug)]
40pub enum VirtualPath {
41    File(FileId),
42    Dir(Vec<VirtualPathId>),
43}
44
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
53pub struct IsDebugging(AtomicBool);
54
55impl IsDebugging {
56    pub fn new(val: bool) -> Self {
57        IsDebugging(AtomicBool::new(val))
58    }
59}
60
61impl Clone for IsDebugging {
62    fn clone(&self) -> Self {
63        IsDebugging(AtomicBool::new(self.0.load(Ordering::Relaxed)))
64    }
65}
66
67/// The core global engine state. This includes all global definitions as well as any global state that
68/// will persist for the whole session.
69///
70/// Declarations, variables, blocks, and other forms of data are held in the global state and referenced
71/// elsewhere using their IDs. These IDs are simply their index into the global state. This allows us to
72/// more easily handle creating blocks, binding variables and callsites, and more, because each of these
73/// will refer to the corresponding IDs rather than their definitions directly. At runtime, this means
74/// less copying and smaller structures.
75///
76/// Many of the larger objects in this structure are stored within `Arc` to decrease the cost of
77/// cloning `EngineState`. While `Arc`s are generally immutable, they can be modified using
78/// `Arc::make_mut`, which automatically clones to a new allocation if there are other copies of
79/// the `Arc` already in use, but will let us modify the `Arc` directly if we have the only
80/// reference to it.
81///
82/// Note that the runtime stack is not part of this global state. Runtime stacks are handled differently,
83/// but they also rely on using IDs rather than full definitions.
84#[derive(Clone)]
85pub struct EngineState {
86    files: Vec<CachedFile>,
87    pub(super) virtual_paths: Vec<(String, VirtualPath)>,
88    vars: Vec<Variable>,
89    decls: Arc<Vec<Box<dyn Command + 'static>>>,
90    // The Vec is wrapped in Arc so that if we don't need to modify the list, we can just clone
91    // the reference and not have to clone each individual Arc inside. These lists can be
92    // especially long, so it helps
93    pub(super) blocks: Arc<Vec<Arc<Block>>>,
94    pub(super) modules: Arc<Vec<Arc<Module>>>,
95    pub spans: Vec<Span>,
96    doccomments: Doccomments,
97    pub scope: ScopeFrame,
98    signals: Signals,
99    pub signal_handlers: Option<Handlers>,
100    pub env_vars: Arc<EnvVars>,
101    pub previous_env_vars: Arc<HashMap<String, Value>>,
102    pub config: Arc<Config>,
103    pub pipeline_externals_state: Arc<(AtomicU32, AtomicU32)>,
104    pub repl_state: Arc<Mutex<ReplState>>,
105    pub table_decl_id: Option<DeclId>,
106    #[cfg(feature = "plugin")]
107    pub plugin_path: Option<PathBuf>,
108    #[cfg(feature = "plugin")]
109    plugins: Vec<Arc<dyn RegisteredPlugin>>,
110    config_path: HashMap<String, PathBuf>,
111    pub history_enabled: bool,
112    pub history_session_id: i64,
113    // Path to the file Nushell is currently evaluating, or None if we're in an interactive session.
114    pub file: Option<PathBuf>,
115    pub regex_cache: Arc<Mutex<LruCache<String, Regex>>>,
116    pub is_interactive: bool,
117    pub is_login: bool,
118    pub is_lsp: bool,
119    startup_time: i64,
120    is_debugging: IsDebugging,
121    pub debugger: Arc<Mutex<Box<dyn Debugger>>>,
122    pub report_log: Arc<Mutex<ReportLog>>,
123
124    pub jobs: Arc<Mutex<Jobs>>,
125
126    // The job being executed with this engine state, or None if main thread
127    pub current_job: CurrentJob,
128
129    pub root_job_sender: Sender<Mail>,
130
131    // When there are background jobs running, the interactive behavior of `exit` changes depending on
132    // the value of this flag:
133    // - if this is false, then a warning about running jobs is shown and `exit` enables this flag
134    // - if this is true, then `exit` will `std::process::exit`
135    //
136    // This ensures that running exit twice will terminate the program correctly
137    pub exit_warning_given: Arc<AtomicBool>,
138}
139
140// The max number of compiled regexes to keep around in a LRU cache, arbitrarily chosen
141const REGEX_CACHE_SIZE: usize = 100; // must be nonzero, otherwise will panic
142
143pub const NU_VARIABLE_ID: VarId = VarId::new(0);
144pub const IN_VARIABLE_ID: VarId = VarId::new(1);
145pub const ENV_VARIABLE_ID: VarId = VarId::new(2);
146// NOTE: If you add more to this list, make sure to update the > checks based on the last in the list
147
148// The first span is unknown span
149pub const UNKNOWN_SPAN_ID: SpanId = SpanId::new(0);
150
151impl EngineState {
152    pub fn new() -> Self {
153        let (send, recv) = channel::<Mail>();
154
155        Self {
156            files: vec![],
157            virtual_paths: vec![],
158            vars: vec![
159                Variable::new(Span::new(0, 0), Type::Any, false),
160                Variable::new(Span::new(0, 0), Type::Any, false),
161                Variable::new(Span::new(0, 0), Type::Any, false),
162                Variable::new(Span::new(0, 0), Type::Any, false),
163                Variable::new(Span::new(0, 0), Type::Any, false),
164            ],
165            decls: Arc::new(vec![]),
166            blocks: Arc::new(vec![]),
167            modules: Arc::new(vec![Arc::new(Module::new(
168                DEFAULT_OVERLAY_NAME.as_bytes().to_vec(),
169            ))]),
170            spans: vec![Span::unknown()],
171            doccomments: Doccomments::new(),
172            // make sure we have some default overlay:
173            scope: ScopeFrame::with_empty_overlay(
174                DEFAULT_OVERLAY_NAME.as_bytes().to_vec(),
175                ModuleId::new(0),
176                false,
177            ),
178            signal_handlers: None,
179            signals: Signals::empty(),
180            env_vars: Arc::new(
181                [(DEFAULT_OVERLAY_NAME.to_string(), HashMap::new())]
182                    .into_iter()
183                    .collect(),
184            ),
185            previous_env_vars: Arc::new(HashMap::new()),
186            config: Arc::new(Config::default()),
187            pipeline_externals_state: Arc::new((AtomicU32::new(0), AtomicU32::new(0))),
188            repl_state: Arc::new(Mutex::new(ReplState {
189                buffer: "".to_string(),
190                cursor_pos: 0,
191                accept: false,
192            })),
193            table_decl_id: None,
194            #[cfg(feature = "plugin")]
195            plugin_path: None,
196            #[cfg(feature = "plugin")]
197            plugins: vec![],
198            config_path: HashMap::new(),
199            history_enabled: true,
200            history_session_id: 0,
201            file: None,
202            regex_cache: Arc::new(Mutex::new(LruCache::new(
203                NonZeroUsize::new(REGEX_CACHE_SIZE).expect("tried to create cache of size zero"),
204            ))),
205            is_interactive: false,
206            is_login: false,
207            is_lsp: false,
208            startup_time: -1,
209            is_debugging: IsDebugging::new(false),
210            debugger: Arc::new(Mutex::new(Box::new(NoopDebugger))),
211            report_log: Arc::default(),
212            jobs: Arc::new(Mutex::new(Jobs::default())),
213            current_job: CurrentJob {
214                id: JobId::new(0),
215                background_thread_job: None,
216                mailbox: Arc::new(Mutex::new(Mailbox::new(recv))),
217            },
218            root_job_sender: send,
219            exit_warning_given: Arc::new(AtomicBool::new(false)),
220        }
221    }
222
223    pub fn signals(&self) -> &Signals {
224        &self.signals
225    }
226
227    pub fn reset_signals(&mut self) {
228        self.signals.reset();
229        if let Some(ref handlers) = self.signal_handlers {
230            handlers.run(SignalAction::Reset);
231        }
232    }
233
234    pub fn set_signals(&mut self, signals: Signals) {
235        self.signals = signals;
236    }
237
238    /// Merges a `StateDelta` onto the current state. These deltas come from a system, like the parser, that
239    /// creates a new set of definitions and visible symbols in the current scope. We make this transactional
240    /// as there are times when we want to run the parser and immediately throw away the results (namely:
241    /// syntax highlighting and completions).
242    ///
243    /// When we want to preserve what the parser has created, we can take its output (the `StateDelta`) and
244    /// use this function to merge it into the global state.
245    pub fn merge_delta(&mut self, mut delta: StateDelta) -> Result<(), ShellError> {
246        // Take the mutable reference and extend the permanent state from the working set
247        self.files.extend(delta.files);
248        self.virtual_paths.extend(delta.virtual_paths);
249        self.vars.extend(delta.vars);
250        self.spans.extend(delta.spans);
251        self.doccomments.merge_with(delta.doccomments);
252
253        // Avoid potentially cloning the Arcs if we aren't adding anything
254        if !delta.decls.is_empty() {
255            Arc::make_mut(&mut self.decls).extend(delta.decls);
256        }
257        if !delta.blocks.is_empty() {
258            Arc::make_mut(&mut self.blocks).extend(delta.blocks);
259        }
260        if !delta.modules.is_empty() {
261            Arc::make_mut(&mut self.modules).extend(delta.modules);
262        }
263
264        let first = delta.scope.remove(0);
265
266        for (delta_name, delta_overlay) in first.clone().overlays {
267            if let Some((_, existing_overlay)) = self
268                .scope
269                .overlays
270                .iter_mut()
271                .find(|(name, _)| name == &delta_name)
272            {
273                // Updating existing overlay
274                for item in delta_overlay.decls.into_iter() {
275                    existing_overlay.decls.insert(item.0, item.1);
276                }
277                for item in delta_overlay.vars.into_iter() {
278                    existing_overlay.insert_variable(item.0, item.1);
279                }
280                for item in delta_overlay.modules.into_iter() {
281                    existing_overlay.modules.insert(item.0, item.1);
282                }
283
284                existing_overlay
285                    .visibility
286                    .merge_with(delta_overlay.visibility);
287            } else {
288                // New overlay was added to the delta
289                self.scope.overlays.push((delta_name, delta_overlay));
290            }
291        }
292
293        let mut activated_ids = self.translate_overlay_ids(&first);
294
295        let mut removed_ids = vec![];
296
297        for name in &first.removed_overlays {
298            if let Some(overlay_id) = self.find_overlay(name) {
299                removed_ids.push(overlay_id);
300            }
301        }
302
303        // Remove overlays removed in delta
304        self.scope
305            .active_overlays
306            .retain(|id| !removed_ids.contains(id));
307
308        // Move overlays activated in the delta to be first
309        self.scope
310            .active_overlays
311            .retain(|id| !activated_ids.contains(id));
312        self.scope.active_overlays.append(&mut activated_ids);
313
314        #[cfg(feature = "plugin")]
315        if !delta.plugins.is_empty() {
316            for plugin in std::mem::take(&mut delta.plugins) {
317                // Connect plugins to the signal handlers
318                if let Some(handlers) = &self.signal_handlers {
319                    plugin.clone().configure_signal_handler(handlers)?;
320                }
321
322                // Replace plugins that overlap in identity.
323                if let Some(existing) = self
324                    .plugins
325                    .iter_mut()
326                    .find(|p| p.identity().name() == plugin.identity().name())
327                {
328                    // Stop the existing plugin, so that the new plugin definitely takes over
329                    existing.stop()?;
330                    *existing = plugin;
331                } else {
332                    self.plugins.push(plugin);
333                }
334            }
335        }
336
337        #[cfg(feature = "plugin")]
338        if !delta.plugin_registry_items.is_empty() {
339            // Update the plugin file with the new signatures.
340            if self.plugin_path.is_some() {
341                self.update_plugin_file(std::mem::take(&mut delta.plugin_registry_items))?;
342            }
343        }
344
345        Ok(())
346    }
347
348    /// Merge the environment from the runtime Stack into the engine state
349    pub fn merge_env(&mut self, stack: &mut Stack) -> Result<(), ShellError> {
350        for mut scope in stack.env_vars.drain(..) {
351            for (overlay_name, mut env) in Arc::make_mut(&mut scope).drain() {
352                if let Some(env_vars) = Arc::make_mut(&mut self.env_vars).get_mut(&overlay_name) {
353                    // Updating existing overlay
354                    env_vars.extend(env.drain());
355                } else {
356                    // Pushing a new overlay
357                    Arc::make_mut(&mut self.env_vars).insert(overlay_name, env);
358                }
359            }
360        }
361
362        let cwd = self.cwd(Some(stack))?;
363        std::env::set_current_dir(cwd).map_err(|err| {
364            IoError::new_internal(err, "Could not set current dir", crate::location!())
365        })?;
366
367        if let Some(config) = stack.config.take() {
368            // If config was updated in the stack, replace it.
369            self.config = config;
370
371            // Make plugin GC config changes take effect immediately.
372            #[cfg(feature = "plugin")]
373            self.update_plugin_gc_configs(&self.config.plugin_gc);
374        }
375
376        Ok(())
377    }
378
379    /// Clean up unused variables from a Stack to prevent memory leaks.
380    /// This removes variables that are no longer referenced by any overlay.
381    pub fn cleanup_stack_variables(&mut self, stack: &mut Stack) {
382        use std::collections::HashSet;
383
384        let mut shadowed_vars = HashSet::new();
385        for (_, frame) in self.scope.overlays.iter_mut() {
386            shadowed_vars.extend(frame.shadowed_vars.to_owned());
387            frame.shadowed_vars.clear();
388        }
389
390        // Remove variables from stack that are no longer referenced
391        stack
392            .vars
393            .retain(|(var_id, _)| !shadowed_vars.contains(var_id));
394    }
395
396    pub fn active_overlay_ids<'a, 'b>(
397        &'b self,
398        removed_overlays: &'a [Vec<u8>],
399    ) -> impl DoubleEndedIterator<Item = &'b OverlayId> + 'a
400    where
401        'b: 'a,
402    {
403        self.scope.active_overlays.iter().filter(|id| {
404            !removed_overlays
405                .iter()
406                .any(|name| name == self.get_overlay_name(**id))
407        })
408    }
409
410    pub fn active_overlays<'a, 'b>(
411        &'b self,
412        removed_overlays: &'a [Vec<u8>],
413    ) -> impl DoubleEndedIterator<Item = &'b OverlayFrame> + 'a
414    where
415        'b: 'a,
416    {
417        self.active_overlay_ids(removed_overlays)
418            .map(|id| self.get_overlay(*id))
419    }
420
421    pub fn active_overlay_names<'a, 'b>(
422        &'b self,
423        removed_overlays: &'a [Vec<u8>],
424    ) -> impl DoubleEndedIterator<Item = &'b [u8]> + 'a
425    where
426        'b: 'a,
427    {
428        self.active_overlay_ids(removed_overlays)
429            .map(|id| self.get_overlay_name(*id))
430    }
431
432    /// Translate overlay IDs from other to IDs in self
433    fn translate_overlay_ids(&self, other: &ScopeFrame) -> Vec<OverlayId> {
434        let other_names = other.active_overlays.iter().map(|other_id| {
435            &other
436                .overlays
437                .get(other_id.get())
438                .expect("internal error: missing overlay")
439                .0
440        });
441
442        other_names
443            .map(|other_name| {
444                self.find_overlay(other_name)
445                    .expect("internal error: missing overlay")
446            })
447            .collect()
448    }
449
450    pub fn last_overlay_name(&self, removed_overlays: &[Vec<u8>]) -> &[u8] {
451        self.active_overlay_names(removed_overlays)
452            .last()
453            .expect("internal error: no active overlays")
454    }
455
456    pub fn last_overlay(&self, removed_overlays: &[Vec<u8>]) -> &OverlayFrame {
457        self.active_overlay_ids(removed_overlays)
458            .last()
459            .map(|id| self.get_overlay(*id))
460            .expect("internal error: no active overlays")
461    }
462
463    pub fn get_overlay_name(&self, overlay_id: OverlayId) -> &[u8] {
464        &self
465            .scope
466            .overlays
467            .get(overlay_id.get())
468            .expect("internal error: missing overlay")
469            .0
470    }
471
472    pub fn get_overlay(&self, overlay_id: OverlayId) -> &OverlayFrame {
473        &self
474            .scope
475            .overlays
476            .get(overlay_id.get())
477            .expect("internal error: missing overlay")
478            .1
479    }
480
481    pub fn render_env_vars(&self) -> HashMap<&str, &Value> {
482        let mut result: HashMap<&str, &Value> = HashMap::new();
483
484        for overlay_name in self.active_overlay_names(&[]) {
485            let name = String::from_utf8_lossy(overlay_name);
486            if let Some(env_vars) = self.env_vars.get(name.as_ref()) {
487                result.extend(env_vars.iter().map(|(k, v)| (k.as_str(), v)));
488            }
489        }
490
491        result
492    }
493
494    pub fn add_env_var(&mut self, name: String, val: Value) {
495        let overlay_name = String::from_utf8_lossy(self.last_overlay_name(&[])).to_string();
496
497        if let Some(env_vars) = Arc::make_mut(&mut self.env_vars).get_mut(&overlay_name) {
498            env_vars.insert(name, val);
499        } else {
500            Arc::make_mut(&mut self.env_vars)
501                .insert(overlay_name, [(name, val)].into_iter().collect());
502        }
503    }
504
505    pub fn get_env_var(&self, name: &str) -> Option<&Value> {
506        for overlay_id in self.scope.active_overlays.iter().rev() {
507            let overlay_name = String::from_utf8_lossy(self.get_overlay_name(*overlay_id));
508            if let Some(env_vars) = self.env_vars.get(overlay_name.as_ref())
509                && let Some(val) = env_vars.get(name)
510            {
511                return Some(val);
512            }
513        }
514
515        None
516    }
517
518    // Returns Some((name, value)) if found, None otherwise.
519    // When updating environment variables, make sure to use
520    // the same case (the returned "name") as the original
521    // environment variable name.
522    pub fn get_env_var_insensitive(&self, name: &str) -> Option<(&String, &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(v) = env_vars.iter().find(|(k, _)| k.eq_ignore_case(name))
527            {
528                return Some((v.0, v.1));
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
546            .plugin_path
547            .as_ref()
548            .ok_or_else(|| ShellError::GenericError {
549                error: "Plugin file path not set".into(),
550                msg: "".into(),
551                span: None,
552                help: Some("you may be running nu with --no-config-file".into()),
553                inner: vec![],
554            })?;
555
556        // Read the current contents of the plugin file if it exists
557        let mut contents = match File::open(plugin_path.as_path()) {
558            Ok(mut plugin_file) => PluginRegistryFile::read_from(&mut plugin_file, None),
559            Err(err) => {
560                if err.kind() == std::io::ErrorKind::NotFound {
561                    Ok(PluginRegistryFile::default())
562                } else {
563                    Err(ShellError::Io(IoError::new_internal_with_path(
564                        err,
565                        "Failed to open plugin file",
566                        crate::location!(),
567                        PathBuf::from(plugin_path),
568                    )))
569                }
570            }
571        }?;
572
573        // Update the given signatures
574        for item in updated_items {
575            contents.upsert_plugin(item);
576        }
577
578        // Write it to the same path
579        let plugin_file = File::create(plugin_path.as_path()).map_err(|err| {
580            IoError::new_internal_with_path(
581                err,
582                "Failed to write plugin file",
583                crate::location!(),
584                PathBuf::from(plugin_path),
585            )
586        })?;
587
588        contents.write_to(plugin_file, None)
589    }
590
591    /// Update plugins with new garbage collection config
592    #[cfg(feature = "plugin")]
593    fn update_plugin_gc_configs(&self, plugin_gc: &crate::PluginGcConfigs) {
594        for plugin in &self.plugins {
595            plugin.set_gc_config(plugin_gc.get(plugin.identity().name()));
596        }
597    }
598
599    pub fn num_files(&self) -> usize {
600        self.files.len()
601    }
602
603    pub fn num_virtual_paths(&self) -> usize {
604        self.virtual_paths.len()
605    }
606
607    pub fn num_vars(&self) -> usize {
608        self.vars.len()
609    }
610
611    pub fn num_decls(&self) -> usize {
612        self.decls.len()
613    }
614
615    pub fn num_blocks(&self) -> usize {
616        self.blocks.len()
617    }
618
619    pub fn num_modules(&self) -> usize {
620        self.modules.len()
621    }
622
623    pub fn num_spans(&self) -> usize {
624        self.spans.len()
625    }
626    pub fn print_vars(&self) {
627        for var in self.vars.iter().enumerate() {
628            println!("var{}: {:?}", var.0, var.1);
629        }
630    }
631
632    pub fn print_decls(&self) {
633        for decl in self.decls.iter().enumerate() {
634            println!("decl{}: {:?}", decl.0, decl.1.signature());
635        }
636    }
637
638    pub fn print_blocks(&self) {
639        for block in self.blocks.iter().enumerate() {
640            println!("block{}: {:?}", block.0, block.1);
641        }
642    }
643
644    pub fn print_contents(&self) {
645        for cached_file in self.files.iter() {
646            let string = String::from_utf8_lossy(&cached_file.content);
647            println!("{string}");
648        }
649    }
650
651    /// Find the [`DeclId`](crate::DeclId) corresponding to a declaration with `name`.
652    ///
653    /// Searches within active overlays, and filtering out overlays in `removed_overlays`.
654    pub fn find_decl(&self, name: &[u8], removed_overlays: &[Vec<u8>]) -> Option<DeclId> {
655        let mut visibility: Visibility = Visibility::new();
656
657        for overlay_frame in self.active_overlays(removed_overlays).rev() {
658            visibility.append(&overlay_frame.visibility);
659
660            if let Some(decl_id) = overlay_frame.get_decl(name)
661                && visibility.is_decl_id_visible(&decl_id)
662            {
663                return Some(decl_id);
664            }
665        }
666
667        None
668    }
669
670    /// Find the name of the declaration corresponding to `decl_id`.
671    ///
672    /// Searches within active overlays, and filtering out overlays in `removed_overlays`.
673    pub fn find_decl_name(&self, decl_id: DeclId, removed_overlays: &[Vec<u8>]) -> Option<&[u8]> {
674        let mut visibility: Visibility = Visibility::new();
675
676        for overlay_frame in self.active_overlays(removed_overlays).rev() {
677            visibility.append(&overlay_frame.visibility);
678
679            if visibility.is_decl_id_visible(&decl_id) {
680                for (name, id) in overlay_frame.decls.iter() {
681                    if id == &decl_id {
682                        return Some(name);
683                    }
684                }
685            }
686        }
687
688        None
689    }
690
691    /// Find the [`OverlayId`](crate::OverlayId) corresponding to `name`.
692    ///
693    /// Searches all overlays, not just active overlays. To search only in active overlays, use [`find_active_overlay`](EngineState::find_active_overlay)
694    pub fn find_overlay(&self, name: &[u8]) -> Option<OverlayId> {
695        self.scope.find_overlay(name)
696    }
697
698    /// Find the [`OverlayId`](crate::OverlayId) of the active overlay corresponding to `name`.
699    ///
700    /// Searches only active overlays. To search in all overlays, use [`find_overlay`](EngineState::find_active_overlay)
701    pub fn find_active_overlay(&self, name: &[u8]) -> Option<OverlayId> {
702        self.scope.find_active_overlay(name)
703    }
704
705    /// Find the [`ModuleId`](crate::ModuleId) corresponding to `name`.
706    ///
707    /// Searches within active overlays, and filtering out overlays in `removed_overlays`.
708    pub fn find_module(&self, name: &[u8], removed_overlays: &[Vec<u8>]) -> Option<ModuleId> {
709        for overlay_frame in self.active_overlays(removed_overlays).rev() {
710            if let Some(module_id) = overlay_frame.modules.get(name) {
711                return Some(*module_id);
712            }
713        }
714
715        None
716    }
717
718    pub fn get_module_comments(&self, module_id: ModuleId) -> Option<&[Span]> {
719        self.doccomments.get_module_comments(module_id)
720    }
721
722    #[cfg(feature = "plugin")]
723    pub fn plugin_decls(&self) -> impl Iterator<Item = &Box<dyn Command + 'static>> {
724        let mut unique_plugin_decls = HashMap::new();
725
726        // Make sure there are no duplicate decls: Newer one overwrites the older one
727        for decl in self.decls.iter().filter(|d| d.is_plugin()) {
728            unique_plugin_decls.insert(decl.name(), decl);
729        }
730
731        let mut plugin_decls: Vec<(&str, &Box<dyn Command>)> =
732            unique_plugin_decls.into_iter().collect();
733
734        // Sort the plugins by name so we don't end up with a random plugin file each time
735        plugin_decls.sort_by(|a, b| a.0.cmp(b.0));
736        plugin_decls.into_iter().map(|(_, decl)| decl)
737    }
738
739    pub fn which_module_has_decl(
740        &self,
741        decl_name: &[u8],
742        removed_overlays: &[Vec<u8>],
743    ) -> Option<&[u8]> {
744        for overlay_frame in self.active_overlays(removed_overlays).rev() {
745            for (module_name, module_id) in overlay_frame.modules.iter() {
746                let module = self.get_module(*module_id);
747                if module.has_decl(decl_name) {
748                    return Some(module_name);
749                }
750            }
751        }
752
753        None
754    }
755
756    /// Apply a function to all commands. The function accepts a command name and its DeclId
757    pub fn traverse_commands(&self, mut f: impl FnMut(&[u8], DeclId)) {
758        for overlay_frame in self.active_overlays(&[]).rev() {
759            for (name, decl_id) in &overlay_frame.decls {
760                if overlay_frame.visibility.is_decl_id_visible(decl_id) {
761                    f(name, *decl_id);
762                }
763            }
764        }
765    }
766
767    pub fn get_span_contents(&self, span: Span) -> &[u8] {
768        for file in &self.files {
769            if file.covered_span.contains_span(span) {
770                return &file.content
771                    [(span.start - file.covered_span.start)..(span.end - file.covered_span.start)];
772            }
773        }
774        &[0u8; 0]
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)
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::GenericError {
998                error: msg.into(),
999                msg: format!("$env.PWD = {}", cwd.as_ref().display()),
1000                span: None,
1001                help: Some("Use `cd` to reset $env.PWD into a good state".into()),
1002                inner: vec![],
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".into(), &[]);
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".into(), &[]);
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".into(), &[]);
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}