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 pub cursor_pos: usize,
49 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#[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 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 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 pub current_job: CurrentJob,
128
129 pub root_job_sender: Sender<Mail>,
130
131 pub exit_warning_given: Arc<AtomicBool>,
138}
139
140const REGEX_CACHE_SIZE: usize = 100; pub 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);
146pub 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 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 pub fn merge_delta(&mut self, mut delta: StateDelta) -> Result<(), ShellError> {
246 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 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 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 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 self.scope
305 .active_overlays
306 .retain(|id| !removed_ids.contains(id));
307
308 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 if let Some(handlers) = &self.signal_handlers {
319 plugin.clone().configure_signal_handler(handlers)?;
320 }
321
322 if let Some(existing) = self
324 .plugins
325 .iter_mut()
326 .find(|p| p.identity().name() == plugin.identity().name())
327 {
328 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 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 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 env_vars.extend(env.drain());
355 } else {
356 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 self.config = config;
370
371 #[cfg(feature = "plugin")]
373 self.update_plugin_gc_configs(&self.config.plugin_gc);
374 }
375
376 Ok(())
377 }
378
379 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 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 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 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 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 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 for item in updated_items {
575 contents.upsert_plugin(item);
576 }
577
578 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 #[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 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 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 pub fn find_overlay(&self, name: &[u8]) -> Option<OverlayId> {
695 self.scope.find_overlay(name)
696 }
697
698 pub fn find_active_overlay(&self, name: &[u8]) -> Option<OverlayId> {
702 self.scope.find_active_overlay(name)
703 }
704
705 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 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 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 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 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 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 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 self.update_plugin_gc_configs(&conf.plugin_gc);
816 }
817
818 self.config = conf;
819 }
820
821 pub fn get_plugin_config(&self, plugin: &str) -> Option<&Value> {
826 self.config.plugins.get(plugin)
827 }
828
829 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 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 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 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 #[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 pub fn cwd(&self, stack: Option<&Stack>) -> Result<AbsolutePathBuf, ShellError> {
995 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 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 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 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 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 pub fn add_span(&mut self, span: Span) -> SpanId {
1102 self.spans.push(span);
1103 SpanId::new(self.num_spans() - 1)
1104 }
1105
1106 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 pub fn is_background_job(&self) -> bool {
1116 self.current_job.background_thread_job.is_some()
1117 }
1118
1119 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 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 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 #[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 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 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 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}