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, Expr},
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, HashSet},
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 or alias.
396    pub fn cleanup_stack_variables(&mut self, stack: &mut Stack) {
397        let mut shadowed_vars = HashSet::new();
398        for (_, frame) in self.scope.overlays.iter_mut() {
399            shadowed_vars.extend(frame.shadowed_vars.drain(..));
400        }
401
402        if shadowed_vars.is_empty() {
403            return;
404        }
405
406        // Collect VarIds still referenced by alias definitions so we don't
407        // remove them — doing so would cause a VariableNotFoundAtRuntime error
408        // when the alias is invoked after the variable has been re-bound.
409        let mut alias_var_ids = HashSet::new();
410        for decl in self.decls.iter() {
411            if let Some(alias) = decl.as_alias() {
412                collect_alias_var_ids(&alias.wrapped_call, &mut alias_var_ids);
413            }
414        }
415
416        // Remove variables from stack that are shadowed and not referenced by any alias
417        stack.vars.retain(|(var_id, _)| {
418            !shadowed_vars.contains(var_id) || alias_var_ids.contains(var_id)
419        });
420    }
421
422    pub fn active_overlay_ids<'a, 'b>(
423        &'b self,
424        removed_overlays: &'a [Vec<u8>],
425    ) -> impl DoubleEndedIterator<Item = &'b OverlayId> + 'a
426    where
427        'b: 'a,
428    {
429        self.scope.active_overlays.iter().filter(|id| {
430            !removed_overlays
431                .iter()
432                .any(|name| name == self.get_overlay_name(**id))
433        })
434    }
435
436    pub fn active_overlays<'a, 'b>(
437        &'b self,
438        removed_overlays: &'a [Vec<u8>],
439    ) -> impl DoubleEndedIterator<Item = &'b OverlayFrame> + 'a
440    where
441        'b: 'a,
442    {
443        self.active_overlay_ids(removed_overlays)
444            .map(|id| self.get_overlay(*id))
445    }
446
447    pub fn active_overlay_names<'a, 'b>(
448        &'b self,
449        removed_overlays: &'a [Vec<u8>],
450    ) -> impl DoubleEndedIterator<Item = &'b [u8]> + 'a
451    where
452        'b: 'a,
453    {
454        self.active_overlay_ids(removed_overlays)
455            .map(|id| self.get_overlay_name(*id))
456    }
457
458    /// Translate overlay IDs from other to IDs in self
459    fn translate_overlay_ids(&self, other: &ScopeFrame) -> Vec<OverlayId> {
460        let other_names = other.active_overlays.iter().map(|other_id| {
461            &other
462                .overlays
463                .get(other_id.get())
464                .expect("internal error: missing overlay")
465                .0
466        });
467
468        other_names
469            .map(|other_name| {
470                self.find_overlay(other_name)
471                    .expect("internal error: missing overlay")
472            })
473            .collect()
474    }
475
476    pub fn last_overlay_name(&self, removed_overlays: &[Vec<u8>]) -> &[u8] {
477        self.active_overlay_names(removed_overlays)
478            .last()
479            .expect("internal error: no active overlays")
480    }
481
482    pub fn last_overlay(&self, removed_overlays: &[Vec<u8>]) -> &OverlayFrame {
483        self.active_overlay_ids(removed_overlays)
484            .last()
485            .map(|id| self.get_overlay(*id))
486            .expect("internal error: no active overlays")
487    }
488
489    pub fn get_overlay_name(&self, overlay_id: OverlayId) -> &[u8] {
490        &self
491            .scope
492            .overlays
493            .get(overlay_id.get())
494            .expect("internal error: missing overlay")
495            .0
496    }
497
498    pub fn get_overlay(&self, overlay_id: OverlayId) -> &OverlayFrame {
499        &self
500            .scope
501            .overlays
502            .get(overlay_id.get())
503            .expect("internal error: missing overlay")
504            .1
505    }
506
507    pub fn render_env_vars(&self) -> HashMap<&str, &Value> {
508        let mut result: HashMap<&str, &Value> = HashMap::new();
509
510        for overlay_name in self.active_overlay_names(&[]) {
511            let name = String::from_utf8_lossy(overlay_name);
512            if let Some(env_vars) = self.env_vars.get(name.as_ref()) {
513                result.extend(env_vars.iter().map(|(k, v)| (k.as_str(), v)));
514            }
515        }
516
517        result
518    }
519
520    pub fn add_env_var(&mut self, name: String, val: Value) {
521        let overlay_name = String::from_utf8_lossy(self.last_overlay_name(&[])).to_string();
522
523        if let Some(env_vars) = Arc::make_mut(&mut self.env_vars).get_mut(&overlay_name) {
524            env_vars.insert(EnvName::from(name), val);
525        } else {
526            Arc::make_mut(&mut self.env_vars).insert(
527                overlay_name,
528                [(EnvName::from(name), val)].into_iter().collect(),
529            );
530        }
531    }
532
533    pub fn get_env_var(&self, name: &str) -> Option<&Value> {
534        for overlay_id in self.scope.active_overlays.iter().rev() {
535            let overlay_name = String::from_utf8_lossy(self.get_overlay_name(*overlay_id));
536            if let Some(env_vars) = self.env_vars.get(overlay_name.as_ref())
537                && let Some(val) = env_vars.get(&EnvName::from(name))
538            {
539                return Some(val);
540            }
541        }
542
543        None
544    }
545
546    #[cfg(feature = "plugin")]
547    pub fn plugins(&self) -> &[Arc<dyn RegisteredPlugin>] {
548        &self.plugins
549    }
550
551    #[cfg(feature = "plugin")]
552    fn update_plugin_file(&self, updated_items: Vec<PluginRegistryItem>) -> Result<(), ShellError> {
553        // Updating the signatures plugin file with the added signatures
554        use std::fs::File;
555
556        let plugin_path = self.plugin_path.as_ref().ok_or_else(|| {
557            ShellError::Generic(
558                GenericError::new_internal("Plugin file path not set", "")
559                    .with_help("you may be running nu with --no-config-file"),
560            )
561        })?;
562
563        // Read the current contents of the plugin file if it exists
564        let mut contents = match File::open(plugin_path.as_path()) {
565            Ok(mut plugin_file) => PluginRegistryFile::read_from(&mut plugin_file, None),
566            Err(err) => {
567                if err.kind() == std::io::ErrorKind::NotFound {
568                    Ok(PluginRegistryFile::default())
569                } else {
570                    Err(ShellError::Io(IoError::new_internal_with_path(
571                        err,
572                        "Failed to open plugin file",
573                        PathBuf::from(plugin_path),
574                    )))
575                }
576            }
577        }?;
578
579        // Update the given signatures
580        for item in updated_items {
581            contents.upsert_plugin(item);
582        }
583
584        // Write it to the same path
585        let plugin_file = File::create(plugin_path.as_path()).map_err(|err| {
586            IoError::new_internal_with_path(
587                err,
588                "Failed to write plugin file",
589                PathBuf::from(plugin_path),
590            )
591        })?;
592
593        contents.write_to(plugin_file, None)
594    }
595
596    /// Update plugins with new garbage collection config
597    #[cfg(feature = "plugin")]
598    fn update_plugin_gc_configs(&self, plugin_gc: &crate::PluginGcConfigs) {
599        for plugin in &self.plugins {
600            plugin.set_gc_config(plugin_gc.get(plugin.identity().name()));
601        }
602    }
603
604    pub fn num_files(&self) -> usize {
605        self.files.len()
606    }
607
608    pub fn num_virtual_paths(&self) -> usize {
609        self.virtual_paths.len()
610    }
611
612    pub fn num_vars(&self) -> usize {
613        self.vars.len()
614    }
615
616    pub fn num_decls(&self) -> usize {
617        self.decls.len()
618    }
619
620    pub fn num_blocks(&self) -> usize {
621        self.blocks.len()
622    }
623
624    pub fn num_modules(&self) -> usize {
625        self.modules.len()
626    }
627
628    pub fn num_spans(&self) -> usize {
629        self.spans.len()
630    }
631    pub fn print_vars(&self) {
632        for var in self.vars.iter().enumerate() {
633            println!("var{}: {:?}", var.0, var.1);
634        }
635    }
636
637    pub fn print_decls(&self) {
638        for decl in self.decls.iter().enumerate() {
639            println!("decl{}: {:?}", decl.0, decl.1.signature());
640        }
641    }
642
643    pub fn print_blocks(&self) {
644        for block in self.blocks.iter().enumerate() {
645            println!("block{}: {:?}", block.0, block.1);
646        }
647    }
648
649    pub fn print_contents(&self) {
650        for cached_file in self.files.iter() {
651            let string = String::from_utf8_lossy(&cached_file.content);
652            println!("{string}");
653        }
654    }
655
656    /// Find the [`DeclId`](crate::DeclId) corresponding to a declaration with `name`.
657    ///
658    /// Searches within active overlays, and filtering out overlays in `removed_overlays`.
659    pub fn find_decl(&self, name: &[u8], removed_overlays: &[Vec<u8>]) -> Option<DeclId> {
660        let mut visibility: Visibility = Visibility::new();
661
662        for overlay_frame in self.active_overlays(removed_overlays).rev() {
663            visibility.append(&overlay_frame.visibility);
664
665            if let Some(decl_id) = overlay_frame.get_decl(name)
666                && visibility.is_decl_id_visible(&decl_id)
667            {
668                return Some(decl_id);
669            }
670        }
671
672        None
673    }
674
675    /// Find the name of the declaration corresponding to `decl_id`.
676    ///
677    /// Searches within active overlays, and filtering out overlays in `removed_overlays`.
678    pub fn find_decl_name(&self, decl_id: DeclId, removed_overlays: &[Vec<u8>]) -> Option<&[u8]> {
679        let mut visibility: Visibility = Visibility::new();
680
681        for overlay_frame in self.active_overlays(removed_overlays).rev() {
682            visibility.append(&overlay_frame.visibility);
683
684            if visibility.is_decl_id_visible(&decl_id) {
685                for (name, id) in overlay_frame.decls.iter() {
686                    if id == &decl_id {
687                        return Some(name);
688                    }
689                }
690            }
691        }
692
693        None
694    }
695
696    /// Find the [`OverlayId`](crate::OverlayId) corresponding to `name`.
697    ///
698    /// Searches all overlays, not just active overlays. To search only in active overlays, use [`find_active_overlay`](EngineState::find_active_overlay)
699    pub fn find_overlay(&self, name: &[u8]) -> Option<OverlayId> {
700        self.scope.find_overlay(name)
701    }
702
703    /// Find the [`OverlayId`](crate::OverlayId) of the active overlay corresponding to `name`.
704    ///
705    /// Searches only active overlays. To search in all overlays, use [`find_overlay`](EngineState::find_active_overlay)
706    pub fn find_active_overlay(&self, name: &[u8]) -> Option<OverlayId> {
707        self.scope.find_active_overlay(name)
708    }
709
710    /// Find the [`ModuleId`](crate::ModuleId) corresponding to `name`.
711    ///
712    /// Searches within active overlays, and filtering out overlays in `removed_overlays`.
713    pub fn find_module(&self, name: &[u8], removed_overlays: &[Vec<u8>]) -> Option<ModuleId> {
714        for overlay_frame in self.active_overlays(removed_overlays).rev() {
715            if let Some(module_id) = overlay_frame.modules.get(name) {
716                return Some(*module_id);
717            }
718        }
719
720        None
721    }
722
723    pub fn get_module_comments(&self, module_id: ModuleId) -> Option<&[Span]> {
724        self.doccomments.get_module_comments(module_id)
725    }
726
727    #[cfg(feature = "plugin")]
728    pub fn plugin_decls(&self) -> impl Iterator<Item = &Box<dyn Command + 'static>> {
729        let mut unique_plugin_decls = HashMap::new();
730
731        // Make sure there are no duplicate decls: Newer one overwrites the older one
732        for decl in self.decls.iter().filter(|d| d.is_plugin()) {
733            unique_plugin_decls.insert(decl.name(), decl);
734        }
735
736        let mut plugin_decls: Vec<(&str, &Box<dyn Command>)> =
737            unique_plugin_decls.into_iter().collect();
738
739        // Sort the plugins by name so we don't end up with a random plugin file each time
740        plugin_decls.sort_by(|a, b| a.0.cmp(b.0));
741        plugin_decls.into_iter().map(|(_, decl)| decl)
742    }
743
744    pub fn which_module_has_decl(
745        &self,
746        decl_name: &[u8],
747        removed_overlays: &[Vec<u8>],
748    ) -> Option<&[u8]> {
749        for overlay_frame in self.active_overlays(removed_overlays).rev() {
750            for (module_name, module_id) in overlay_frame.modules.iter() {
751                let module = self.get_module(*module_id);
752                if module.has_decl(decl_name) {
753                    return Some(module_name);
754                }
755            }
756        }
757
758        None
759    }
760
761    /// Apply a function to all commands. The function accepts a command name and its DeclId
762    pub fn traverse_commands(&self, mut f: impl FnMut(&[u8], DeclId)) {
763        for overlay_frame in self.active_overlays(&[]).rev() {
764            for (name, decl_id) in &overlay_frame.decls {
765                if overlay_frame.visibility.is_decl_id_visible(decl_id) {
766                    f(name, *decl_id);
767                }
768            }
769        }
770    }
771
772    pub fn get_span_contents(&self, span: Span) -> &[u8] {
773        self.try_get_file_contents(span).unwrap_or(&[0u8; 0])
774    }
775
776    pub fn try_get_file_contents(&self, span: Span) -> Option<&[u8]> {
777        self.files.iter().find_map(|file| {
778            if file.covered_span.contains_span(span) {
779                let start = span.start - file.covered_span.start;
780                let end = span.end - file.covered_span.start;
781                Some(&file.content[start..end])
782            } else {
783                None
784            }
785        })
786    }
787
788    /// If the span's content starts with the given prefix, return two subspans
789    /// corresponding to this prefix, and the rest of the content.
790    pub fn span_match_prefix(&self, span: Span, prefix: &[u8]) -> Option<(Span, Span)> {
791        let contents = self.get_span_contents(span);
792
793        if contents.starts_with(prefix) {
794            span.split_at(prefix.len())
795        } else {
796            None
797        }
798    }
799
800    /// If the span's content ends with the given postfix, return two subspans
801    /// corresponding to the rest of the content, and this postfix.
802    pub fn span_match_postfix(&self, span: Span, prefix: &[u8]) -> Option<(Span, Span)> {
803        let contents = self.get_span_contents(span);
804
805        if contents.ends_with(prefix) {
806            span.split_at(span.len() - prefix.len())
807        } else {
808            None
809        }
810    }
811
812    /// Get the global config from the engine state.
813    ///
814    /// Use [`Stack::get_config()`] instead whenever the `Stack` is available, as it takes into
815    /// account local changes to `$env.config`.
816    pub fn get_config(&self) -> &Arc<Config> {
817        &self.config
818    }
819
820    pub fn set_config(&mut self, conf: impl Into<Arc<Config>>) {
821        let conf = conf.into();
822
823        #[cfg(feature = "plugin")]
824        if conf.plugin_gc != self.config.plugin_gc {
825            // Make plugin GC config changes take effect immediately.
826            self.update_plugin_gc_configs(&conf.plugin_gc);
827        }
828
829        self.config = conf;
830    }
831
832    /// Fetch the configuration for a plugin
833    ///
834    /// The `plugin` must match the registered name of a plugin.  For `plugin add
835    /// nu_plugin_example` the plugin name to use will be `"example"`
836    pub fn get_plugin_config(&self, plugin: &str) -> Option<&Value> {
837        self.config.plugins.get(plugin)
838    }
839
840    /// Returns the configuration settings for command history or `None` if history is disabled
841    pub fn history_config(&self) -> Option<HistoryConfig> {
842        self.history_enabled.then(|| self.config.history.clone())
843    }
844
845    pub fn get_var(&self, var_id: VarId) -> &Variable {
846        self.vars
847            .get(var_id.get())
848            .expect("internal error: missing variable")
849    }
850
851    pub fn get_constant(&self, var_id: VarId) -> Option<&Value> {
852        let var = self.get_var(var_id);
853        var.const_val.as_ref()
854    }
855
856    pub fn generate_nu_constant(&mut self) {
857        self.vars[NU_VARIABLE_ID.get()].const_val = Some(create_nu_constant(self, Span::unknown()));
858    }
859
860    pub fn get_decl(&self, decl_id: DeclId) -> &dyn Command {
861        self.decls
862            .get(decl_id.get())
863            .expect("internal error: missing declaration")
864            .as_ref()
865    }
866
867    /// Get all commands within scope, sorted by the commands' names
868    pub fn get_decls_sorted(&self, include_hidden: bool) -> Vec<(Vec<u8>, DeclId)> {
869        let mut decls_map = HashMap::new();
870
871        for overlay_frame in self.active_overlays(&[]) {
872            let new_decls = if include_hidden {
873                overlay_frame.decls.clone()
874            } else {
875                overlay_frame
876                    .decls
877                    .clone()
878                    .into_iter()
879                    .filter(|(_, id)| overlay_frame.visibility.is_decl_id_visible(id))
880                    .collect()
881            };
882
883            decls_map.extend(new_decls);
884        }
885
886        let mut decls: Vec<(Vec<u8>, DeclId)> = decls_map.into_iter().collect();
887
888        decls.sort_by(|a, b| a.0.cmp(&b.0));
889        decls
890    }
891
892    pub fn get_signature(&self, decl: &dyn Command) -> Signature {
893        if let Some(block_id) = decl.block_id() {
894            *self.blocks[block_id.get()].signature.clone()
895        } else {
896            decl.signature()
897        }
898    }
899
900    /// Get signatures of all commands within scope with their decl ids.
901    pub fn get_signatures_and_declids(&self, include_hidden: bool) -> Vec<(Signature, DeclId)> {
902        self.get_decls_sorted(include_hidden)
903            .into_iter()
904            .map(|(_, id)| {
905                let decl = self.get_decl(id);
906
907                (self.get_signature(decl).update_from_command(decl), id)
908            })
909            .collect()
910    }
911
912    pub fn get_block(&self, block_id: BlockId) -> &Arc<Block> {
913        self.blocks
914            .get(block_id.get())
915            .expect("internal error: missing block")
916    }
917
918    /// Optionally get a block by id, if it exists
919    ///
920    /// Prefer to use [`.get_block()`](Self::get_block) in most cases - `BlockId`s that don't exist
921    /// are normally a compiler error. This only exists to stop plugins from crashing the engine if
922    /// they send us something invalid.
923    pub fn try_get_block(&self, block_id: BlockId) -> Option<&Arc<Block>> {
924        self.blocks.get(block_id.get())
925    }
926
927    pub fn get_module(&self, module_id: ModuleId) -> &Module {
928        self.modules
929            .get(module_id.get())
930            .expect("internal error: missing module")
931    }
932
933    pub fn get_virtual_path(&self, virtual_path_id: VirtualPathId) -> &(String, VirtualPath) {
934        self.virtual_paths
935            .get(virtual_path_id.get())
936            .expect("internal error: missing virtual path")
937    }
938
939    pub fn next_span_start(&self) -> usize {
940        if let Some(cached_file) = self.files.last() {
941            cached_file.covered_span.end
942        } else {
943            0
944        }
945    }
946
947    pub fn files(
948        &self,
949    ) -> impl DoubleEndedIterator<Item = &CachedFile> + ExactSizeIterator<Item = &CachedFile> {
950        self.files.iter()
951    }
952
953    pub fn add_file(&mut self, filename: Arc<str>, content: Arc<[u8]>) -> FileId {
954        let next_span_start = self.next_span_start();
955        let next_span_end = next_span_start + content.len();
956
957        let covered_span = Span::new(next_span_start, next_span_end);
958
959        self.files.push(CachedFile {
960            name: filename,
961            content,
962            covered_span,
963        });
964
965        FileId::new(self.num_files() - 1)
966    }
967
968    pub fn set_config_path(&mut self, key: &str, val: PathBuf) {
969        self.config_path.insert(key.to_string(), val);
970    }
971
972    pub fn get_config_path(&self, key: &str) -> Option<&PathBuf> {
973        self.config_path.get(key)
974    }
975
976    pub fn build_desc(&self, spans: &[Span]) -> (String, String) {
977        let comment_lines: Vec<&[u8]> = spans
978            .iter()
979            .map(|span| self.get_span_contents(*span))
980            .collect();
981        build_desc(&comment_lines)
982    }
983
984    pub fn build_module_desc(&self, module_id: ModuleId) -> Option<(String, String)> {
985        self.get_module_comments(module_id)
986            .map(|comment_spans| self.build_desc(comment_spans))
987    }
988
989    /// Returns the current working directory, which is guaranteed to be canonicalized.
990    ///
991    /// Returns an empty String if $env.PWD doesn't exist.
992    #[deprecated(since = "0.92.3", note = "please use `EngineState::cwd()` instead")]
993    pub fn current_work_dir(&self) -> String {
994        self.cwd(None)
995            .map(|path| path.to_string_lossy().to_string())
996            .unwrap_or_default()
997    }
998
999    /// Returns the current working directory, which is guaranteed to be an
1000    /// absolute path without trailing slashes (unless it's the root path), but
1001    /// might contain symlink components.
1002    ///
1003    /// If `stack` is supplied, also considers modifications to the working
1004    /// directory on the stack that have yet to be merged into the engine state.
1005    pub fn cwd(&self, stack: Option<&Stack>) -> Result<AbsolutePathBuf, ShellError> {
1006        // Helper function to create a simple generic error.
1007        fn error(msg: &str, cwd: impl AsRef<nu_path::Path>) -> ShellError {
1008            ShellError::Generic(
1009                GenericError::new_internal(
1010                    msg.to_string(),
1011                    format!("$env.PWD = {}", cwd.as_ref().display()),
1012                )
1013                .with_help("Use `cd` to reset $env.PWD into a good state"),
1014            )
1015        }
1016
1017        // Retrieve $env.PWD from the stack or the engine state.
1018        let pwd = if let Some(stack) = stack {
1019            stack.get_env_var(self, "PWD")
1020        } else {
1021            self.get_env_var("PWD")
1022        };
1023
1024        let pwd = pwd.ok_or_else(|| error("$env.PWD not found", ""))?;
1025
1026        if let Ok(pwd) = pwd.as_str() {
1027            let path = AbsolutePathBuf::try_from(pwd)
1028                .map_err(|_| error("$env.PWD is not an absolute path", pwd))?;
1029
1030            // Technically, a root path counts as "having trailing slashes", but
1031            // for the purpose of PWD, a root path is acceptable.
1032            if path.parent().is_some() && nu_path::has_trailing_slash(path.as_ref()) {
1033                Err(error("$env.PWD contains trailing slashes", &path))
1034            } else if !path.exists() {
1035                Err(error("$env.PWD points to a non-existent directory", &path))
1036            } else if !path.is_dir() {
1037                Err(error("$env.PWD points to a non-directory", &path))
1038            } else {
1039                Ok(path)
1040            }
1041        } else {
1042            Err(error("$env.PWD is not a string", format!("{pwd:?}")))
1043        }
1044    }
1045
1046    /// Like `EngineState::cwd()`, but returns a String instead of a PathBuf for convenience.
1047    pub fn cwd_as_string(&self, stack: Option<&Stack>) -> Result<String, ShellError> {
1048        let cwd = self.cwd(stack)?;
1049        cwd.into_os_string()
1050            .into_string()
1051            .map_err(|err| ShellError::NonUtf8Custom {
1052                msg: format!("The current working directory is not a valid utf-8 string: {err:?}"),
1053                span: Span::unknown(),
1054            })
1055    }
1056
1057    // TODO: see if we can completely get rid of this
1058    pub fn get_file_contents(&self) -> &[CachedFile] {
1059        &self.files
1060    }
1061
1062    pub fn get_startup_time(&self) -> i64 {
1063        self.startup_time
1064    }
1065
1066    pub fn set_startup_time(&mut self, startup_time: i64) {
1067        self.startup_time = startup_time;
1068    }
1069
1070    pub fn activate_debugger(
1071        &self,
1072        debugger: Box<dyn Debugger>,
1073    ) -> Result<(), PoisonDebuggerError<'_>> {
1074        let mut locked_debugger = self.debugger.lock()?;
1075        *locked_debugger = debugger;
1076        locked_debugger.activate();
1077        self.is_debugging.0.store(true, Ordering::Relaxed);
1078        Ok(())
1079    }
1080
1081    pub fn deactivate_debugger(&self) -> Result<Box<dyn Debugger>, PoisonDebuggerError<'_>> {
1082        let mut locked_debugger = self.debugger.lock()?;
1083        locked_debugger.deactivate();
1084        let ret = std::mem::replace(&mut *locked_debugger, Box::new(NoopDebugger));
1085        self.is_debugging.0.store(false, Ordering::Relaxed);
1086        Ok(ret)
1087    }
1088
1089    pub fn is_debugging(&self) -> bool {
1090        self.is_debugging.0.load(Ordering::Relaxed)
1091    }
1092
1093    pub fn recover_from_panic(&mut self) {
1094        if Mutex::is_poisoned(&self.repl_state) {
1095            self.repl_state = Arc::new(Mutex::new(ReplState {
1096                buffer: "".to_string(),
1097                cursor_pos: 0,
1098                accept: false,
1099            }));
1100        }
1101        if Mutex::is_poisoned(&self.jobs) {
1102            self.jobs = Arc::new(Mutex::new(Jobs::default()));
1103        }
1104        if Mutex::is_poisoned(&self.regex_cache) {
1105            self.regex_cache = Arc::new(Mutex::new(LruCache::new(
1106                NonZeroUsize::new(REGEX_CACHE_SIZE).expect("tried to create cache of size zero"),
1107            )));
1108        }
1109    }
1110
1111    /// Add new span and return its ID
1112    pub fn add_span(&mut self, span: Span) -> SpanId {
1113        self.spans.push(span);
1114        SpanId::new(self.num_spans() - 1)
1115    }
1116
1117    /// Find ID of a span (should be avoided if possible)
1118    pub fn find_span_id(&self, span: Span) -> Option<SpanId> {
1119        self.spans
1120            .iter()
1121            .position(|sp| sp == &span)
1122            .map(SpanId::new)
1123    }
1124
1125    // Determines whether the current state is being held by a background job
1126    pub fn is_background_job(&self) -> bool {
1127        self.current_job.background_thread_job.is_some()
1128    }
1129
1130    // Gets the thread job entry
1131    pub fn current_thread_job(&self) -> Option<&ThreadJob> {
1132        self.current_job.background_thread_job.as_ref()
1133    }
1134}
1135
1136/// Collect all `VarId`s referenced by `Expr::Var` nodes in `expr`.
1137/// This is used by [`EngineState::cleanup_stack_variables`] to avoid removing
1138/// variables that are still referenced by alias definitions.
1139fn collect_alias_var_ids(expr: &crate::ast::Expression, var_ids: &mut HashSet<VarId>) {
1140    let mut queue = vec![expr];
1141
1142    while let Some(e) = queue.pop() {
1143        match &e.expr {
1144            Expr::Var(id) => {
1145                var_ids.insert(*id);
1146            }
1147            Expr::Call(call) => {
1148                for arg in &call.arguments {
1149                    if let Some(sub_expr) = arg.expr() {
1150                        queue.push(sub_expr);
1151                    }
1152                }
1153            }
1154            Expr::ExternalCall(head, args) => {
1155                queue.push(head);
1156                for arg in args.iter() {
1157                    queue.push(arg.expr());
1158                }
1159            }
1160            Expr::FullCellPath(fcp) => queue.push(&fcp.head),
1161            _ => {}
1162        }
1163    }
1164}
1165
1166impl GetSpan for &EngineState {
1167    /// Get existing span
1168    fn get_span(&self, span_id: SpanId) -> Span {
1169        *self
1170            .spans
1171            .get(span_id.get())
1172            .expect("internal error: missing span")
1173    }
1174}
1175
1176impl Default for EngineState {
1177    fn default() -> Self {
1178        Self::new()
1179    }
1180}
1181
1182#[cfg(test)]
1183mod engine_state_tests {
1184    use crate::engine::StateWorkingSet;
1185    use std::str::{Utf8Error, from_utf8};
1186
1187    use super::*;
1188
1189    #[test]
1190    fn add_file_gives_id() {
1191        let engine_state = EngineState::new();
1192        let mut engine_state = StateWorkingSet::new(&engine_state);
1193        let id = engine_state.add_file("test.nu", &[]);
1194
1195        assert_eq!(id, FileId::new(0));
1196    }
1197
1198    #[test]
1199    fn add_file_gives_id_including_parent() {
1200        let mut engine_state = EngineState::new();
1201        let parent_id = engine_state.add_file("test.nu".into(), Arc::new([]));
1202
1203        let mut working_set = StateWorkingSet::new(&engine_state);
1204        let working_set_id = working_set.add_file("child.nu", &[]);
1205
1206        assert_eq!(parent_id, FileId::new(0));
1207        assert_eq!(working_set_id, FileId::new(1));
1208    }
1209
1210    #[test]
1211    fn merge_states() -> Result<(), ShellError> {
1212        let mut engine_state = EngineState::new();
1213        engine_state.add_file("test.nu".into(), Arc::new([]));
1214
1215        let delta = {
1216            let mut working_set = StateWorkingSet::new(&engine_state);
1217            let _ = working_set.add_file("child.nu", &[]);
1218            working_set.render()
1219        };
1220
1221        engine_state.merge_delta(delta)?;
1222
1223        assert_eq!(engine_state.num_files(), 2);
1224        assert_eq!(&*engine_state.files[0].name, "test.nu");
1225        assert_eq!(&*engine_state.files[1].name, "child.nu");
1226
1227        Ok(())
1228    }
1229
1230    #[test]
1231    fn list_variables() -> Result<(), Utf8Error> {
1232        let varname = "something";
1233        let varname_with_sigil = "$".to_owned() + varname;
1234        let engine_state = EngineState::new();
1235        let mut working_set = StateWorkingSet::new(&engine_state);
1236        working_set.add_variable(
1237            varname.as_bytes().into(),
1238            Span { start: 0, end: 1 },
1239            Type::Int,
1240            false,
1241        );
1242        let variables = working_set
1243            .list_variables()
1244            .into_iter()
1245            .map(from_utf8)
1246            .collect::<Result<Vec<&str>, Utf8Error>>()?;
1247        assert_eq!(variables, vec![varname_with_sigil]);
1248        Ok(())
1249    }
1250
1251    #[test]
1252    fn get_plugin_config() {
1253        let mut engine_state = EngineState::new();
1254
1255        assert!(
1256            engine_state.get_plugin_config("example").is_none(),
1257            "Unexpected plugin configuration"
1258        );
1259
1260        let mut plugins = HashMap::new();
1261        plugins.insert("example".into(), Value::string("value", Span::test_data()));
1262
1263        let mut config = Config::clone(engine_state.get_config());
1264        config.plugins = plugins;
1265
1266        engine_state.set_config(config);
1267
1268        assert!(
1269            engine_state.get_plugin_config("example").is_some(),
1270            "Plugin configuration not found"
1271        );
1272    }
1273}
1274
1275#[cfg(test)]
1276mod test_cwd {
1277    //! Here're the test cases we need to cover:
1278    //!
1279    //! `EngineState::cwd()` computes the result from `self.env_vars["PWD"]` and
1280    //! optionally `stack.env_vars["PWD"]`.
1281    //!
1282    //! PWD may be unset in either `env_vars`.
1283    //! PWD should NOT be an empty string.
1284    //! PWD should NOT be a non-string value.
1285    //! PWD should NOT be a relative path.
1286    //! PWD should NOT contain trailing slashes.
1287    //! PWD may point to a directory or a symlink to directory.
1288    //! PWD should NOT point to a file or a symlink to file.
1289    //! PWD should NOT point to non-existent entities in the filesystem.
1290
1291    use crate::{
1292        Value,
1293        engine::{EngineState, Stack},
1294    };
1295    use nu_path::{AbsolutePath, Path, assert_path_eq};
1296    use tempfile::{NamedTempFile, TempDir};
1297
1298    /// Creates a symlink. Works on both Unix and Windows.
1299    #[cfg(any(unix, windows))]
1300    fn symlink(
1301        original: impl AsRef<AbsolutePath>,
1302        link: impl AsRef<AbsolutePath>,
1303    ) -> std::io::Result<()> {
1304        let original = original.as_ref();
1305        let link = link.as_ref();
1306
1307        #[cfg(unix)]
1308        {
1309            std::os::unix::fs::symlink(original, link)
1310        }
1311        #[cfg(windows)]
1312        {
1313            if original.is_dir() {
1314                std::os::windows::fs::symlink_dir(original, link)
1315            } else {
1316                std::os::windows::fs::symlink_file(original, link)
1317            }
1318        }
1319    }
1320
1321    /// Create an engine state initialized with the given PWD.
1322    fn engine_state_with_pwd(path: impl AsRef<Path>) -> EngineState {
1323        let mut engine_state = EngineState::new();
1324        engine_state.add_env_var(
1325            "PWD".into(),
1326            Value::test_string(path.as_ref().to_str().unwrap()),
1327        );
1328        engine_state
1329    }
1330
1331    /// Create a stack initialized with the given PWD.
1332    fn stack_with_pwd(path: impl AsRef<Path>) -> Stack {
1333        let mut stack = Stack::new();
1334        stack.add_env_var(
1335            "PWD".into(),
1336            Value::test_string(path.as_ref().to_str().unwrap()),
1337        );
1338        stack
1339    }
1340
1341    #[test]
1342    fn pwd_not_set() {
1343        let engine_state = EngineState::new();
1344        engine_state.cwd(None).unwrap_err();
1345    }
1346
1347    #[test]
1348    fn pwd_is_empty_string() {
1349        let engine_state = engine_state_with_pwd("");
1350        engine_state.cwd(None).unwrap_err();
1351    }
1352
1353    #[test]
1354    fn pwd_is_non_string_value() {
1355        let mut engine_state = EngineState::new();
1356        engine_state.add_env_var("PWD".into(), Value::test_glob("*"));
1357        engine_state.cwd(None).unwrap_err();
1358    }
1359
1360    #[test]
1361    fn pwd_is_relative_path() {
1362        let engine_state = engine_state_with_pwd("./foo");
1363
1364        engine_state.cwd(None).unwrap_err();
1365    }
1366
1367    #[test]
1368    fn pwd_has_trailing_slash() {
1369        let dir = TempDir::new().unwrap();
1370        let engine_state = engine_state_with_pwd(dir.path().join(""));
1371
1372        engine_state.cwd(None).unwrap_err();
1373    }
1374
1375    #[test]
1376    fn pwd_points_to_root() {
1377        #[cfg(windows)]
1378        let root = Path::new(r"C:\");
1379        #[cfg(not(windows))]
1380        let root = Path::new("/");
1381
1382        let engine_state = engine_state_with_pwd(root);
1383        let cwd = engine_state.cwd(None).unwrap();
1384        assert_path_eq!(cwd, root);
1385    }
1386
1387    #[test]
1388    fn pwd_points_to_normal_file() {
1389        let file = NamedTempFile::new().unwrap();
1390        let engine_state = engine_state_with_pwd(file.path());
1391
1392        engine_state.cwd(None).unwrap_err();
1393    }
1394
1395    #[test]
1396    fn pwd_points_to_normal_directory() {
1397        let dir = TempDir::new().unwrap();
1398        let engine_state = engine_state_with_pwd(dir.path());
1399
1400        let cwd = engine_state.cwd(None).unwrap();
1401        assert_path_eq!(cwd, dir.path());
1402    }
1403
1404    #[test]
1405    fn pwd_points_to_symlink_to_file() {
1406        let file = NamedTempFile::new().unwrap();
1407        let temp_file = AbsolutePath::try_new(file.path()).unwrap();
1408        let dir = TempDir::new().unwrap();
1409        let temp = AbsolutePath::try_new(dir.path()).unwrap();
1410
1411        let link = temp.join("link");
1412        symlink(temp_file, &link).unwrap();
1413        let engine_state = engine_state_with_pwd(&link);
1414
1415        engine_state.cwd(None).unwrap_err();
1416    }
1417
1418    #[test]
1419    fn pwd_points_to_symlink_to_directory() {
1420        let dir = TempDir::new().unwrap();
1421        let temp = AbsolutePath::try_new(dir.path()).unwrap();
1422
1423        let link = temp.join("link");
1424        symlink(temp, &link).unwrap();
1425        let engine_state = engine_state_with_pwd(&link);
1426
1427        let cwd = engine_state.cwd(None).unwrap();
1428        assert_path_eq!(cwd, link);
1429    }
1430
1431    #[test]
1432    fn pwd_points_to_broken_symlink() {
1433        let dir = TempDir::new().unwrap();
1434        let temp = AbsolutePath::try_new(dir.path()).unwrap();
1435        let other_dir = TempDir::new().unwrap();
1436        let other_temp = AbsolutePath::try_new(other_dir.path()).unwrap();
1437
1438        let link = temp.join("link");
1439        symlink(other_temp, &link).unwrap();
1440        let engine_state = engine_state_with_pwd(&link);
1441
1442        drop(other_dir);
1443        engine_state.cwd(None).unwrap_err();
1444    }
1445
1446    #[test]
1447    fn pwd_points_to_nonexistent_entity() {
1448        let engine_state = engine_state_with_pwd(TempDir::new().unwrap().path());
1449
1450        engine_state.cwd(None).unwrap_err();
1451    }
1452
1453    #[test]
1454    fn stack_pwd_not_set() {
1455        let dir = TempDir::new().unwrap();
1456        let engine_state = engine_state_with_pwd(dir.path());
1457        let stack = Stack::new();
1458
1459        let cwd = engine_state.cwd(Some(&stack)).unwrap();
1460        assert_eq!(cwd, dir.path());
1461    }
1462
1463    #[test]
1464    fn stack_pwd_is_empty_string() {
1465        let dir = TempDir::new().unwrap();
1466        let engine_state = engine_state_with_pwd(dir.path());
1467        let stack = stack_with_pwd("");
1468
1469        engine_state.cwd(Some(&stack)).unwrap_err();
1470    }
1471
1472    #[test]
1473    fn stack_pwd_points_to_normal_directory() {
1474        let dir1 = TempDir::new().unwrap();
1475        let dir2 = TempDir::new().unwrap();
1476        let engine_state = engine_state_with_pwd(dir1.path());
1477        let stack = stack_with_pwd(dir2.path());
1478
1479        let cwd = engine_state.cwd(Some(&stack)).unwrap();
1480        assert_path_eq!(cwd, dir2.path());
1481    }
1482
1483    #[test]
1484    fn stack_pwd_points_to_normal_directory_with_symlink_components() {
1485        let dir = TempDir::new().unwrap();
1486        let temp = AbsolutePath::try_new(dir.path()).unwrap();
1487
1488        // `/tmp/dir/link` points to `/tmp/dir`, then we set PWD to `/tmp/dir/link/foo`
1489        let link = temp.join("link");
1490        symlink(temp, &link).unwrap();
1491        let foo = link.join("foo");
1492        std::fs::create_dir(temp.join("foo")).unwrap();
1493        let engine_state = EngineState::new();
1494        let stack = stack_with_pwd(&foo);
1495
1496        let cwd = engine_state.cwd(Some(&stack)).unwrap();
1497        assert_path_eq!(cwd, foo);
1498    }
1499}