1use crate::{
2 BlockId, Category, Config, DeclId, FileId, GetSpan, Handlers, HistoryConfig, JobId, Module,
3 ModuleId, OverlayId, ShellError, SignalAction, Signals, Signature, Span, SpanId, Type, Value,
4 VarId, VirtualPathId,
5 ast::Block,
6 cli_error::ReportLog,
7 debugger::{Debugger, NoopDebugger},
8 engine::{
9 CachedFile, Command, CommandType, DEFAULT_OVERLAY_NAME, EnvVars, OverlayFrame, ScopeFrame,
10 Stack, StateDelta, Variable, Visibility,
11 description::{Doccomments, build_desc},
12 },
13 eval_const::create_nu_constant,
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}
50
51pub struct IsDebugging(AtomicBool);
52
53impl IsDebugging {
54 pub fn new(val: bool) -> Self {
55 IsDebugging(AtomicBool::new(val))
56 }
57}
58
59impl Clone for IsDebugging {
60 fn clone(&self) -> Self {
61 IsDebugging(AtomicBool::new(self.0.load(Ordering::Relaxed)))
62 }
63}
64
65#[derive(Clone)]
83pub struct EngineState {
84 files: Vec<CachedFile>,
85 pub(super) virtual_paths: Vec<(String, VirtualPath)>,
86 vars: Vec<Variable>,
87 decls: Arc<Vec<Box<dyn Command + 'static>>>,
88 pub(super) blocks: Arc<Vec<Arc<Block>>>,
92 pub(super) modules: Arc<Vec<Arc<Module>>>,
93 pub spans: Vec<Span>,
94 doccomments: Doccomments,
95 pub scope: ScopeFrame,
96 signals: Signals,
97 pub signal_handlers: Option<Handlers>,
98 pub env_vars: Arc<EnvVars>,
99 pub previous_env_vars: Arc<HashMap<String, Value>>,
100 pub config: Arc<Config>,
101 pub pipeline_externals_state: Arc<(AtomicU32, AtomicU32)>,
102 pub repl_state: Arc<Mutex<ReplState>>,
103 pub table_decl_id: Option<DeclId>,
104 #[cfg(feature = "plugin")]
105 pub plugin_path: Option<PathBuf>,
106 #[cfg(feature = "plugin")]
107 plugins: Vec<Arc<dyn RegisteredPlugin>>,
108 config_path: HashMap<String, PathBuf>,
109 pub history_enabled: bool,
110 pub history_session_id: i64,
111 pub file: Option<PathBuf>,
113 pub regex_cache: Arc<Mutex<LruCache<String, Regex>>>,
114 pub is_interactive: bool,
115 pub is_login: bool,
116 startup_time: i64,
117 is_debugging: IsDebugging,
118 pub debugger: Arc<Mutex<Box<dyn Debugger>>>,
119 pub report_log: Arc<Mutex<ReportLog>>,
120
121 pub jobs: Arc<Mutex<Jobs>>,
122
123 pub current_job: CurrentJob,
125
126 pub root_job_sender: Sender<Mail>,
127
128 pub exit_warning_given: Arc<AtomicBool>,
135}
136
137const REGEX_CACHE_SIZE: usize = 100; pub const NU_VARIABLE_ID: VarId = VarId::new(0);
141pub const IN_VARIABLE_ID: VarId = VarId::new(1);
142pub const ENV_VARIABLE_ID: VarId = VarId::new(2);
143pub const UNKNOWN_SPAN_ID: SpanId = SpanId::new(0);
147
148impl EngineState {
149 pub fn new() -> Self {
150 let (send, recv) = channel::<Mail>();
151
152 Self {
153 files: vec![],
154 virtual_paths: vec![],
155 vars: vec![
156 Variable::new(Span::new(0, 0), Type::Any, false),
157 Variable::new(Span::new(0, 0), Type::Any, false),
158 Variable::new(Span::new(0, 0), Type::Any, false),
159 Variable::new(Span::new(0, 0), Type::Any, false),
160 Variable::new(Span::new(0, 0), Type::Any, false),
161 ],
162 decls: Arc::new(vec![]),
163 blocks: Arc::new(vec![]),
164 modules: Arc::new(vec![Arc::new(Module::new(
165 DEFAULT_OVERLAY_NAME.as_bytes().to_vec(),
166 ))]),
167 spans: vec![Span::unknown()],
168 doccomments: Doccomments::new(),
169 scope: ScopeFrame::with_empty_overlay(
171 DEFAULT_OVERLAY_NAME.as_bytes().to_vec(),
172 ModuleId::new(0),
173 false,
174 ),
175 signal_handlers: None,
176 signals: Signals::empty(),
177 env_vars: Arc::new(
178 [(DEFAULT_OVERLAY_NAME.to_string(), HashMap::new())]
179 .into_iter()
180 .collect(),
181 ),
182 previous_env_vars: Arc::new(HashMap::new()),
183 config: Arc::new(Config::default()),
184 pipeline_externals_state: Arc::new((AtomicU32::new(0), AtomicU32::new(0))),
185 repl_state: Arc::new(Mutex::new(ReplState {
186 buffer: "".to_string(),
187 cursor_pos: 0,
188 })),
189 table_decl_id: None,
190 #[cfg(feature = "plugin")]
191 plugin_path: None,
192 #[cfg(feature = "plugin")]
193 plugins: vec![],
194 config_path: HashMap::new(),
195 history_enabled: true,
196 history_session_id: 0,
197 file: None,
198 regex_cache: Arc::new(Mutex::new(LruCache::new(
199 NonZeroUsize::new(REGEX_CACHE_SIZE).expect("tried to create cache of size zero"),
200 ))),
201 is_interactive: false,
202 is_login: false,
203 startup_time: -1,
204 is_debugging: IsDebugging::new(false),
205 debugger: Arc::new(Mutex::new(Box::new(NoopDebugger))),
206 report_log: Arc::default(),
207 jobs: Arc::new(Mutex::new(Jobs::default())),
208 current_job: CurrentJob {
209 id: JobId::new(0),
210 background_thread_job: None,
211 mailbox: Arc::new(Mutex::new(Mailbox::new(recv))),
212 },
213 root_job_sender: send,
214 exit_warning_given: Arc::new(AtomicBool::new(false)),
215 }
216 }
217
218 pub fn signals(&self) -> &Signals {
219 &self.signals
220 }
221
222 pub fn reset_signals(&mut self) {
223 self.signals.reset();
224 if let Some(ref handlers) = self.signal_handlers {
225 handlers.run(SignalAction::Reset);
226 }
227 }
228
229 pub fn set_signals(&mut self, signals: Signals) {
230 self.signals = signals;
231 }
232
233 pub fn merge_delta(&mut self, mut delta: StateDelta) -> Result<(), ShellError> {
241 self.files.extend(delta.files);
243 self.virtual_paths.extend(delta.virtual_paths);
244 self.vars.extend(delta.vars);
245 self.spans.extend(delta.spans);
246 self.doccomments.merge_with(delta.doccomments);
247
248 if !delta.decls.is_empty() {
250 Arc::make_mut(&mut self.decls).extend(delta.decls);
251 }
252 if !delta.blocks.is_empty() {
253 Arc::make_mut(&mut self.blocks).extend(delta.blocks);
254 }
255 if !delta.modules.is_empty() {
256 Arc::make_mut(&mut self.modules).extend(delta.modules);
257 }
258
259 let first = delta.scope.remove(0);
260
261 for (delta_name, delta_overlay) in first.clone().overlays {
262 if let Some((_, existing_overlay)) = self
263 .scope
264 .overlays
265 .iter_mut()
266 .find(|(name, _)| name == &delta_name)
267 {
268 for item in delta_overlay.decls.into_iter() {
270 existing_overlay.decls.insert(item.0, item.1);
271 }
272 for item in delta_overlay.vars.into_iter() {
273 existing_overlay.vars.insert(item.0, item.1);
274 }
275 for item in delta_overlay.modules.into_iter() {
276 existing_overlay.modules.insert(item.0, item.1);
277 }
278
279 existing_overlay
280 .visibility
281 .merge_with(delta_overlay.visibility);
282 } else {
283 self.scope.overlays.push((delta_name, delta_overlay));
285 }
286 }
287
288 let mut activated_ids = self.translate_overlay_ids(&first);
289
290 let mut removed_ids = vec![];
291
292 for name in &first.removed_overlays {
293 if let Some(overlay_id) = self.find_overlay(name) {
294 removed_ids.push(overlay_id);
295 }
296 }
297
298 self.scope
300 .active_overlays
301 .retain(|id| !removed_ids.contains(id));
302
303 self.scope
305 .active_overlays
306 .retain(|id| !activated_ids.contains(id));
307 self.scope.active_overlays.append(&mut activated_ids);
308
309 #[cfg(feature = "plugin")]
310 if !delta.plugins.is_empty() {
311 for plugin in std::mem::take(&mut delta.plugins) {
312 if let Some(handlers) = &self.signal_handlers {
314 plugin.clone().configure_signal_handler(handlers)?;
315 }
316
317 if let Some(existing) = self
319 .plugins
320 .iter_mut()
321 .find(|p| p.identity().name() == plugin.identity().name())
322 {
323 existing.stop()?;
325 *existing = plugin;
326 } else {
327 self.plugins.push(plugin);
328 }
329 }
330 }
331
332 #[cfg(feature = "plugin")]
333 if !delta.plugin_registry_items.is_empty() {
334 if self.plugin_path.is_some() {
336 self.update_plugin_file(std::mem::take(&mut delta.plugin_registry_items))?;
337 }
338 }
339
340 Ok(())
341 }
342
343 pub fn merge_env(&mut self, stack: &mut Stack) -> Result<(), ShellError> {
345 for mut scope in stack.env_vars.drain(..) {
346 for (overlay_name, mut env) in Arc::make_mut(&mut scope).drain() {
347 if let Some(env_vars) = Arc::make_mut(&mut self.env_vars).get_mut(&overlay_name) {
348 env_vars.extend(env.drain());
350 } else {
351 Arc::make_mut(&mut self.env_vars).insert(overlay_name, env);
353 }
354 }
355 }
356
357 let cwd = self.cwd(Some(stack))?;
358 std::env::set_current_dir(cwd).map_err(|err| {
359 IoError::new_internal(err, "Could not set current dir", crate::location!())
360 })?;
361
362 if let Some(config) = stack.config.take() {
363 self.config = config;
365
366 #[cfg(feature = "plugin")]
368 self.update_plugin_gc_configs(&self.config.plugin_gc);
369 }
370
371 Ok(())
372 }
373
374 pub fn active_overlay_ids<'a, 'b>(
375 &'b self,
376 removed_overlays: &'a [Vec<u8>],
377 ) -> impl DoubleEndedIterator<Item = &'b OverlayId> + 'a
378 where
379 'b: 'a,
380 {
381 self.scope.active_overlays.iter().filter(|id| {
382 !removed_overlays
383 .iter()
384 .any(|name| name == self.get_overlay_name(**id))
385 })
386 }
387
388 pub fn active_overlays<'a, 'b>(
389 &'b self,
390 removed_overlays: &'a [Vec<u8>],
391 ) -> impl DoubleEndedIterator<Item = &'b OverlayFrame> + 'a
392 where
393 'b: 'a,
394 {
395 self.active_overlay_ids(removed_overlays)
396 .map(|id| self.get_overlay(*id))
397 }
398
399 pub fn active_overlay_names<'a, 'b>(
400 &'b self,
401 removed_overlays: &'a [Vec<u8>],
402 ) -> impl DoubleEndedIterator<Item = &'b [u8]> + 'a
403 where
404 'b: 'a,
405 {
406 self.active_overlay_ids(removed_overlays)
407 .map(|id| self.get_overlay_name(*id))
408 }
409
410 fn translate_overlay_ids(&self, other: &ScopeFrame) -> Vec<OverlayId> {
412 let other_names = other.active_overlays.iter().map(|other_id| {
413 &other
414 .overlays
415 .get(other_id.get())
416 .expect("internal error: missing overlay")
417 .0
418 });
419
420 other_names
421 .map(|other_name| {
422 self.find_overlay(other_name)
423 .expect("internal error: missing overlay")
424 })
425 .collect()
426 }
427
428 pub fn last_overlay_name(&self, removed_overlays: &[Vec<u8>]) -> &[u8] {
429 self.active_overlay_names(removed_overlays)
430 .last()
431 .expect("internal error: no active overlays")
432 }
433
434 pub fn last_overlay(&self, removed_overlays: &[Vec<u8>]) -> &OverlayFrame {
435 self.active_overlay_ids(removed_overlays)
436 .last()
437 .map(|id| self.get_overlay(*id))
438 .expect("internal error: no active overlays")
439 }
440
441 pub fn get_overlay_name(&self, overlay_id: OverlayId) -> &[u8] {
442 &self
443 .scope
444 .overlays
445 .get(overlay_id.get())
446 .expect("internal error: missing overlay")
447 .0
448 }
449
450 pub fn get_overlay(&self, overlay_id: OverlayId) -> &OverlayFrame {
451 &self
452 .scope
453 .overlays
454 .get(overlay_id.get())
455 .expect("internal error: missing overlay")
456 .1
457 }
458
459 pub fn render_env_vars(&self) -> HashMap<&str, &Value> {
460 let mut result: HashMap<&str, &Value> = HashMap::new();
461
462 for overlay_name in self.active_overlay_names(&[]) {
463 let name = String::from_utf8_lossy(overlay_name);
464 if let Some(env_vars) = self.env_vars.get(name.as_ref()) {
465 result.extend(env_vars.iter().map(|(k, v)| (k.as_str(), v)));
466 }
467 }
468
469 result
470 }
471
472 pub fn add_env_var(&mut self, name: String, val: Value) {
473 let overlay_name = String::from_utf8_lossy(self.last_overlay_name(&[])).to_string();
474
475 if let Some(env_vars) = Arc::make_mut(&mut self.env_vars).get_mut(&overlay_name) {
476 env_vars.insert(name, val);
477 } else {
478 Arc::make_mut(&mut self.env_vars)
479 .insert(overlay_name, [(name, val)].into_iter().collect());
480 }
481 }
482
483 pub fn get_env_var(&self, name: &str) -> Option<&Value> {
484 for overlay_id in self.scope.active_overlays.iter().rev() {
485 let overlay_name = String::from_utf8_lossy(self.get_overlay_name(*overlay_id));
486 if let Some(env_vars) = self.env_vars.get(overlay_name.as_ref()) {
487 if let Some(val) = env_vars.get(name) {
488 return Some(val);
489 }
490 }
491 }
492
493 None
494 }
495
496 pub fn get_env_var_insensitive(&self, name: &str) -> Option<(&String, &Value)> {
501 for overlay_id in self.scope.active_overlays.iter().rev() {
502 let overlay_name = String::from_utf8_lossy(self.get_overlay_name(*overlay_id));
503 if let Some(env_vars) = self.env_vars.get(overlay_name.as_ref()) {
504 if let Some(v) = env_vars.iter().find(|(k, _)| k.eq_ignore_case(name)) {
505 return Some((v.0, v.1));
506 }
507 }
508 }
509
510 None
511 }
512
513 #[cfg(feature = "plugin")]
514 pub fn plugins(&self) -> &[Arc<dyn RegisteredPlugin>] {
515 &self.plugins
516 }
517
518 #[cfg(feature = "plugin")]
519 fn update_plugin_file(&self, updated_items: Vec<PluginRegistryItem>) -> Result<(), ShellError> {
520 use std::fs::File;
522
523 let plugin_path = self
524 .plugin_path
525 .as_ref()
526 .ok_or_else(|| ShellError::GenericError {
527 error: "Plugin file path not set".into(),
528 msg: "".into(),
529 span: None,
530 help: Some("you may be running nu with --no-config-file".into()),
531 inner: vec![],
532 })?;
533
534 let mut contents = match File::open(plugin_path.as_path()) {
536 Ok(mut plugin_file) => PluginRegistryFile::read_from(&mut plugin_file, None),
537 Err(err) => {
538 if err.kind() == std::io::ErrorKind::NotFound {
539 Ok(PluginRegistryFile::default())
540 } else {
541 Err(ShellError::Io(IoError::new_internal_with_path(
542 err,
543 "Failed to open plugin file",
544 crate::location!(),
545 PathBuf::from(plugin_path),
546 )))
547 }
548 }
549 }?;
550
551 for item in updated_items {
553 contents.upsert_plugin(item);
554 }
555
556 let plugin_file = File::create(plugin_path.as_path()).map_err(|err| {
558 IoError::new_internal_with_path(
559 err,
560 "Failed to write plugin file",
561 crate::location!(),
562 PathBuf::from(plugin_path),
563 )
564 })?;
565
566 contents.write_to(plugin_file, None)
567 }
568
569 #[cfg(feature = "plugin")]
571 fn update_plugin_gc_configs(&self, plugin_gc: &crate::PluginGcConfigs) {
572 for plugin in &self.plugins {
573 plugin.set_gc_config(plugin_gc.get(plugin.identity().name()));
574 }
575 }
576
577 pub fn num_files(&self) -> usize {
578 self.files.len()
579 }
580
581 pub fn num_virtual_paths(&self) -> usize {
582 self.virtual_paths.len()
583 }
584
585 pub fn num_vars(&self) -> usize {
586 self.vars.len()
587 }
588
589 pub fn num_decls(&self) -> usize {
590 self.decls.len()
591 }
592
593 pub fn num_blocks(&self) -> usize {
594 self.blocks.len()
595 }
596
597 pub fn num_modules(&self) -> usize {
598 self.modules.len()
599 }
600
601 pub fn num_spans(&self) -> usize {
602 self.spans.len()
603 }
604 pub fn print_vars(&self) {
605 for var in self.vars.iter().enumerate() {
606 println!("var{}: {:?}", var.0, var.1);
607 }
608 }
609
610 pub fn print_decls(&self) {
611 for decl in self.decls.iter().enumerate() {
612 println!("decl{}: {:?}", decl.0, decl.1.signature());
613 }
614 }
615
616 pub fn print_blocks(&self) {
617 for block in self.blocks.iter().enumerate() {
618 println!("block{}: {:?}", block.0, block.1);
619 }
620 }
621
622 pub fn print_contents(&self) {
623 for cached_file in self.files.iter() {
624 let string = String::from_utf8_lossy(&cached_file.content);
625 println!("{string}");
626 }
627 }
628
629 pub fn find_decl(&self, name: &[u8], removed_overlays: &[Vec<u8>]) -> Option<DeclId> {
633 let mut visibility: Visibility = Visibility::new();
634
635 for overlay_frame in self.active_overlays(removed_overlays).rev() {
636 visibility.append(&overlay_frame.visibility);
637
638 if let Some(decl_id) = overlay_frame.get_decl(name) {
639 if visibility.is_decl_id_visible(&decl_id) {
640 return Some(decl_id);
641 }
642 }
643 }
644
645 None
646 }
647
648 pub fn find_decl_name(&self, decl_id: DeclId, removed_overlays: &[Vec<u8>]) -> Option<&[u8]> {
652 let mut visibility: Visibility = Visibility::new();
653
654 for overlay_frame in self.active_overlays(removed_overlays).rev() {
655 visibility.append(&overlay_frame.visibility);
656
657 if visibility.is_decl_id_visible(&decl_id) {
658 for (name, id) in overlay_frame.decls.iter() {
659 if id == &decl_id {
660 return Some(name);
661 }
662 }
663 }
664 }
665
666 None
667 }
668
669 pub fn find_overlay(&self, name: &[u8]) -> Option<OverlayId> {
673 self.scope.find_overlay(name)
674 }
675
676 pub fn find_active_overlay(&self, name: &[u8]) -> Option<OverlayId> {
680 self.scope.find_active_overlay(name)
681 }
682
683 pub fn find_module(&self, name: &[u8], removed_overlays: &[Vec<u8>]) -> Option<ModuleId> {
687 for overlay_frame in self.active_overlays(removed_overlays).rev() {
688 if let Some(module_id) = overlay_frame.modules.get(name) {
689 return Some(*module_id);
690 }
691 }
692
693 None
694 }
695
696 pub fn get_module_comments(&self, module_id: ModuleId) -> Option<&[Span]> {
697 self.doccomments.get_module_comments(module_id)
698 }
699
700 #[cfg(feature = "plugin")]
701 pub fn plugin_decls(&self) -> impl Iterator<Item = &Box<dyn Command + 'static>> {
702 let mut unique_plugin_decls = HashMap::new();
703
704 for decl in self.decls.iter().filter(|d| d.is_plugin()) {
706 unique_plugin_decls.insert(decl.name(), decl);
707 }
708
709 let mut plugin_decls: Vec<(&str, &Box<dyn Command>)> =
710 unique_plugin_decls.into_iter().collect();
711
712 plugin_decls.sort_by(|a, b| a.0.cmp(b.0));
714 plugin_decls.into_iter().map(|(_, decl)| decl)
715 }
716
717 pub fn which_module_has_decl(
718 &self,
719 decl_name: &[u8],
720 removed_overlays: &[Vec<u8>],
721 ) -> Option<&[u8]> {
722 for overlay_frame in self.active_overlays(removed_overlays).rev() {
723 for (module_name, module_id) in overlay_frame.modules.iter() {
724 let module = self.get_module(*module_id);
725 if module.has_decl(decl_name) {
726 return Some(module_name);
727 }
728 }
729 }
730
731 None
732 }
733
734 pub fn find_commands_by_predicate(
735 &self,
736 mut predicate: impl FnMut(&[u8]) -> bool,
737 ignore_deprecated: bool,
738 ) -> Vec<(DeclId, Vec<u8>, Option<String>, CommandType)> {
739 let mut output = vec![];
740
741 for overlay_frame in self.active_overlays(&[]).rev() {
742 for (name, decl_id) in &overlay_frame.decls {
743 if overlay_frame.visibility.is_decl_id_visible(decl_id) && predicate(name) {
744 let command = self.get_decl(*decl_id);
745 if ignore_deprecated && command.signature().category == Category::Removed {
746 continue;
747 }
748 output.push((
749 *decl_id,
750 name.clone(),
751 Some(command.description().to_string()),
752 command.command_type(),
753 ));
754 }
755 }
756 }
757
758 output
759 }
760
761 pub fn get_span_contents(&self, span: Span) -> &[u8] {
762 for file in &self.files {
763 if file.covered_span.contains_span(span) {
764 return &file.content
765 [(span.start - file.covered_span.start)..(span.end - file.covered_span.start)];
766 }
767 }
768 &[0u8; 0]
769 }
770
771 pub fn get_config(&self) -> &Arc<Config> {
776 &self.config
777 }
778
779 pub fn set_config(&mut self, conf: impl Into<Arc<Config>>) {
780 let conf = conf.into();
781
782 #[cfg(feature = "plugin")]
783 if conf.plugin_gc != self.config.plugin_gc {
784 self.update_plugin_gc_configs(&conf.plugin_gc);
786 }
787
788 self.config = conf;
789 }
790
791 pub fn get_plugin_config(&self, plugin: &str) -> Option<&Value> {
796 self.config.plugins.get(plugin)
797 }
798
799 pub fn history_config(&self) -> Option<HistoryConfig> {
801 self.history_enabled.then(|| self.config.history)
802 }
803
804 pub fn get_var(&self, var_id: VarId) -> &Variable {
805 self.vars
806 .get(var_id.get())
807 .expect("internal error: missing variable")
808 }
809
810 pub fn get_constant(&self, var_id: VarId) -> Option<&Value> {
811 let var = self.get_var(var_id);
812 var.const_val.as_ref()
813 }
814
815 pub fn generate_nu_constant(&mut self) {
816 self.vars[NU_VARIABLE_ID.get()].const_val = Some(create_nu_constant(self, Span::unknown()));
817 }
818
819 pub fn get_decl(&self, decl_id: DeclId) -> &dyn Command {
820 self.decls
821 .get(decl_id.get())
822 .expect("internal error: missing declaration")
823 .as_ref()
824 }
825
826 pub fn get_decls_sorted(&self, include_hidden: bool) -> Vec<(Vec<u8>, DeclId)> {
828 let mut decls_map = HashMap::new();
829
830 for overlay_frame in self.active_overlays(&[]) {
831 let new_decls = if include_hidden {
832 overlay_frame.decls.clone()
833 } else {
834 overlay_frame
835 .decls
836 .clone()
837 .into_iter()
838 .filter(|(_, id)| overlay_frame.visibility.is_decl_id_visible(id))
839 .collect()
840 };
841
842 decls_map.extend(new_decls);
843 }
844
845 let mut decls: Vec<(Vec<u8>, DeclId)> = decls_map.into_iter().collect();
846
847 decls.sort_by(|a, b| a.0.cmp(&b.0));
848 decls
849 }
850
851 pub fn get_signature(&self, decl: &dyn Command) -> Signature {
852 if let Some(block_id) = decl.block_id() {
853 *self.blocks[block_id.get()].signature.clone()
854 } else {
855 decl.signature()
856 }
857 }
858
859 pub fn get_signatures_and_declids(&self, include_hidden: bool) -> Vec<(Signature, DeclId)> {
861 self.get_decls_sorted(include_hidden)
862 .into_iter()
863 .map(|(_, id)| {
864 let decl = self.get_decl(id);
865
866 (self.get_signature(decl).update_from_command(decl), id)
867 })
868 .collect()
869 }
870
871 pub fn get_block(&self, block_id: BlockId) -> &Arc<Block> {
872 self.blocks
873 .get(block_id.get())
874 .expect("internal error: missing block")
875 }
876
877 pub fn try_get_block(&self, block_id: BlockId) -> Option<&Arc<Block>> {
883 self.blocks.get(block_id.get())
884 }
885
886 pub fn get_module(&self, module_id: ModuleId) -> &Module {
887 self.modules
888 .get(module_id.get())
889 .expect("internal error: missing module")
890 }
891
892 pub fn get_virtual_path(&self, virtual_path_id: VirtualPathId) -> &(String, VirtualPath) {
893 self.virtual_paths
894 .get(virtual_path_id.get())
895 .expect("internal error: missing virtual path")
896 }
897
898 pub fn next_span_start(&self) -> usize {
899 if let Some(cached_file) = self.files.last() {
900 cached_file.covered_span.end
901 } else {
902 0
903 }
904 }
905
906 pub fn files(
907 &self,
908 ) -> impl DoubleEndedIterator<Item = &CachedFile> + ExactSizeIterator<Item = &CachedFile> {
909 self.files.iter()
910 }
911
912 pub fn add_file(&mut self, filename: Arc<str>, content: Arc<[u8]>) -> FileId {
913 let next_span_start = self.next_span_start();
914 let next_span_end = next_span_start + content.len();
915
916 let covered_span = Span::new(next_span_start, next_span_end);
917
918 self.files.push(CachedFile {
919 name: filename,
920 content,
921 covered_span,
922 });
923
924 FileId::new(self.num_files() - 1)
925 }
926
927 pub fn set_config_path(&mut self, key: &str, val: PathBuf) {
928 self.config_path.insert(key.to_string(), val);
929 }
930
931 pub fn get_config_path(&self, key: &str) -> Option<&PathBuf> {
932 self.config_path.get(key)
933 }
934
935 pub fn build_desc(&self, spans: &[Span]) -> (String, String) {
936 let comment_lines: Vec<&[u8]> = spans
937 .iter()
938 .map(|span| self.get_span_contents(*span))
939 .collect();
940 build_desc(&comment_lines)
941 }
942
943 pub fn build_module_desc(&self, module_id: ModuleId) -> Option<(String, String)> {
944 self.get_module_comments(module_id)
945 .map(|comment_spans| self.build_desc(comment_spans))
946 }
947
948 #[deprecated(since = "0.92.3", note = "please use `EngineState::cwd()` instead")]
952 pub fn current_work_dir(&self) -> String {
953 self.cwd(None)
954 .map(|path| path.to_string_lossy().to_string())
955 .unwrap_or_default()
956 }
957
958 pub fn cwd(&self, stack: Option<&Stack>) -> Result<AbsolutePathBuf, ShellError> {
965 fn error(msg: &str, cwd: impl AsRef<nu_path::Path>) -> ShellError {
967 ShellError::GenericError {
968 error: msg.into(),
969 msg: format!("$env.PWD = {}", cwd.as_ref().display()),
970 span: None,
971 help: Some("Use `cd` to reset $env.PWD into a good state".into()),
972 inner: vec![],
973 }
974 }
975
976 let pwd = if let Some(stack) = stack {
978 stack.get_env_var(self, "PWD")
979 } else {
980 self.get_env_var("PWD")
981 };
982
983 let pwd = pwd.ok_or_else(|| error("$env.PWD not found", ""))?;
984
985 if let Ok(pwd) = pwd.as_str() {
986 let path = AbsolutePathBuf::try_from(pwd)
987 .map_err(|_| error("$env.PWD is not an absolute path", pwd))?;
988
989 if path.parent().is_some() && nu_path::has_trailing_slash(path.as_ref()) {
992 Err(error("$env.PWD contains trailing slashes", &path))
993 } else if !path.exists() {
994 Err(error("$env.PWD points to a non-existent directory", &path))
995 } else if !path.is_dir() {
996 Err(error("$env.PWD points to a non-directory", &path))
997 } else {
998 Ok(path)
999 }
1000 } else {
1001 Err(error("$env.PWD is not a string", format!("{pwd:?}")))
1002 }
1003 }
1004
1005 pub fn cwd_as_string(&self, stack: Option<&Stack>) -> Result<String, ShellError> {
1007 let cwd = self.cwd(stack)?;
1008 cwd.into_os_string()
1009 .into_string()
1010 .map_err(|err| ShellError::NonUtf8Custom {
1011 msg: format!(
1012 "The current working directory is not a valid utf-8 string: {:?}",
1013 err
1014 ),
1015 span: Span::unknown(),
1016 })
1017 }
1018
1019 pub fn get_file_contents(&self) -> &[CachedFile] {
1021 &self.files
1022 }
1023
1024 pub fn get_startup_time(&self) -> i64 {
1025 self.startup_time
1026 }
1027
1028 pub fn set_startup_time(&mut self, startup_time: i64) {
1029 self.startup_time = startup_time;
1030 }
1031
1032 pub fn activate_debugger(
1033 &self,
1034 debugger: Box<dyn Debugger>,
1035 ) -> Result<(), PoisonDebuggerError> {
1036 let mut locked_debugger = self.debugger.lock()?;
1037 *locked_debugger = debugger;
1038 locked_debugger.activate();
1039 self.is_debugging.0.store(true, Ordering::Relaxed);
1040 Ok(())
1041 }
1042
1043 pub fn deactivate_debugger(&self) -> Result<Box<dyn Debugger>, PoisonDebuggerError> {
1044 let mut locked_debugger = self.debugger.lock()?;
1045 locked_debugger.deactivate();
1046 let ret = std::mem::replace(&mut *locked_debugger, Box::new(NoopDebugger));
1047 self.is_debugging.0.store(false, Ordering::Relaxed);
1048 Ok(ret)
1049 }
1050
1051 pub fn is_debugging(&self) -> bool {
1052 self.is_debugging.0.load(Ordering::Relaxed)
1053 }
1054
1055 pub fn recover_from_panic(&mut self) {
1056 if Mutex::is_poisoned(&self.repl_state) {
1057 self.repl_state = Arc::new(Mutex::new(ReplState {
1058 buffer: "".to_string(),
1059 cursor_pos: 0,
1060 }));
1061 }
1062 if Mutex::is_poisoned(&self.jobs) {
1063 self.jobs = Arc::new(Mutex::new(Jobs::default()));
1064 }
1065 if Mutex::is_poisoned(&self.regex_cache) {
1066 self.regex_cache = Arc::new(Mutex::new(LruCache::new(
1067 NonZeroUsize::new(REGEX_CACHE_SIZE).expect("tried to create cache of size zero"),
1068 )));
1069 }
1070 }
1071
1072 pub fn add_span(&mut self, span: Span) -> SpanId {
1074 self.spans.push(span);
1075 SpanId::new(self.num_spans() - 1)
1076 }
1077
1078 pub fn find_span_id(&self, span: Span) -> Option<SpanId> {
1080 self.spans
1081 .iter()
1082 .position(|sp| sp == &span)
1083 .map(SpanId::new)
1084 }
1085
1086 pub fn is_background_job(&self) -> bool {
1088 self.current_job.background_thread_job.is_some()
1089 }
1090
1091 pub fn current_thread_job(&self) -> Option<&ThreadJob> {
1093 self.current_job.background_thread_job.as_ref()
1094 }
1095}
1096
1097impl GetSpan for &EngineState {
1098 fn get_span(&self, span_id: SpanId) -> Span {
1100 *self
1101 .spans
1102 .get(span_id.get())
1103 .expect("internal error: missing span")
1104 }
1105}
1106
1107impl Default for EngineState {
1108 fn default() -> Self {
1109 Self::new()
1110 }
1111}
1112
1113#[cfg(test)]
1114mod engine_state_tests {
1115 use crate::engine::StateWorkingSet;
1116 use std::str::{Utf8Error, from_utf8};
1117
1118 use super::*;
1119
1120 #[test]
1121 fn add_file_gives_id() {
1122 let engine_state = EngineState::new();
1123 let mut engine_state = StateWorkingSet::new(&engine_state);
1124 let id = engine_state.add_file("test.nu".into(), &[]);
1125
1126 assert_eq!(id, FileId::new(0));
1127 }
1128
1129 #[test]
1130 fn add_file_gives_id_including_parent() {
1131 let mut engine_state = EngineState::new();
1132 let parent_id = engine_state.add_file("test.nu".into(), Arc::new([]));
1133
1134 let mut working_set = StateWorkingSet::new(&engine_state);
1135 let working_set_id = working_set.add_file("child.nu".into(), &[]);
1136
1137 assert_eq!(parent_id, FileId::new(0));
1138 assert_eq!(working_set_id, FileId::new(1));
1139 }
1140
1141 #[test]
1142 fn merge_states() -> Result<(), ShellError> {
1143 let mut engine_state = EngineState::new();
1144 engine_state.add_file("test.nu".into(), Arc::new([]));
1145
1146 let delta = {
1147 let mut working_set = StateWorkingSet::new(&engine_state);
1148 let _ = working_set.add_file("child.nu".into(), &[]);
1149 working_set.render()
1150 };
1151
1152 engine_state.merge_delta(delta)?;
1153
1154 assert_eq!(engine_state.num_files(), 2);
1155 assert_eq!(&*engine_state.files[0].name, "test.nu");
1156 assert_eq!(&*engine_state.files[1].name, "child.nu");
1157
1158 Ok(())
1159 }
1160
1161 #[test]
1162 fn list_variables() -> Result<(), Utf8Error> {
1163 let varname = "something";
1164 let varname_with_sigil = "$".to_owned() + varname;
1165 let engine_state = EngineState::new();
1166 let mut working_set = StateWorkingSet::new(&engine_state);
1167 working_set.add_variable(
1168 varname.as_bytes().into(),
1169 Span { start: 0, end: 1 },
1170 Type::Int,
1171 false,
1172 );
1173 let variables = working_set
1174 .list_variables()
1175 .into_iter()
1176 .map(from_utf8)
1177 .collect::<Result<Vec<&str>, Utf8Error>>()?;
1178 assert_eq!(variables, vec![varname_with_sigil]);
1179 Ok(())
1180 }
1181
1182 #[test]
1183 fn get_plugin_config() {
1184 let mut engine_state = EngineState::new();
1185
1186 assert!(
1187 engine_state.get_plugin_config("example").is_none(),
1188 "Unexpected plugin configuration"
1189 );
1190
1191 let mut plugins = HashMap::new();
1192 plugins.insert("example".into(), Value::string("value", Span::test_data()));
1193
1194 let mut config = Config::clone(engine_state.get_config());
1195 config.plugins = plugins;
1196
1197 engine_state.set_config(config);
1198
1199 assert!(
1200 engine_state.get_plugin_config("example").is_some(),
1201 "Plugin configuration not found"
1202 );
1203 }
1204}
1205
1206#[cfg(test)]
1207mod test_cwd {
1208 use crate::{
1223 Value,
1224 engine::{EngineState, Stack},
1225 };
1226 use nu_path::{AbsolutePath, Path, assert_path_eq};
1227 use tempfile::{NamedTempFile, TempDir};
1228
1229 #[cfg(any(unix, windows))]
1231 fn symlink(
1232 original: impl AsRef<AbsolutePath>,
1233 link: impl AsRef<AbsolutePath>,
1234 ) -> std::io::Result<()> {
1235 let original = original.as_ref();
1236 let link = link.as_ref();
1237
1238 #[cfg(unix)]
1239 {
1240 std::os::unix::fs::symlink(original, link)
1241 }
1242 #[cfg(windows)]
1243 {
1244 if original.is_dir() {
1245 std::os::windows::fs::symlink_dir(original, link)
1246 } else {
1247 std::os::windows::fs::symlink_file(original, link)
1248 }
1249 }
1250 }
1251
1252 fn engine_state_with_pwd(path: impl AsRef<Path>) -> EngineState {
1254 let mut engine_state = EngineState::new();
1255 engine_state.add_env_var(
1256 "PWD".into(),
1257 Value::test_string(path.as_ref().to_str().unwrap()),
1258 );
1259 engine_state
1260 }
1261
1262 fn stack_with_pwd(path: impl AsRef<Path>) -> Stack {
1264 let mut stack = Stack::new();
1265 stack.add_env_var(
1266 "PWD".into(),
1267 Value::test_string(path.as_ref().to_str().unwrap()),
1268 );
1269 stack
1270 }
1271
1272 #[test]
1273 fn pwd_not_set() {
1274 let engine_state = EngineState::new();
1275 engine_state.cwd(None).unwrap_err();
1276 }
1277
1278 #[test]
1279 fn pwd_is_empty_string() {
1280 let engine_state = engine_state_with_pwd("");
1281 engine_state.cwd(None).unwrap_err();
1282 }
1283
1284 #[test]
1285 fn pwd_is_non_string_value() {
1286 let mut engine_state = EngineState::new();
1287 engine_state.add_env_var("PWD".into(), Value::test_glob("*"));
1288 engine_state.cwd(None).unwrap_err();
1289 }
1290
1291 #[test]
1292 fn pwd_is_relative_path() {
1293 let engine_state = engine_state_with_pwd("./foo");
1294
1295 engine_state.cwd(None).unwrap_err();
1296 }
1297
1298 #[test]
1299 fn pwd_has_trailing_slash() {
1300 let dir = TempDir::new().unwrap();
1301 let engine_state = engine_state_with_pwd(dir.path().join(""));
1302
1303 engine_state.cwd(None).unwrap_err();
1304 }
1305
1306 #[test]
1307 fn pwd_points_to_root() {
1308 #[cfg(windows)]
1309 let root = Path::new(r"C:\");
1310 #[cfg(not(windows))]
1311 let root = Path::new("/");
1312
1313 let engine_state = engine_state_with_pwd(root);
1314 let cwd = engine_state.cwd(None).unwrap();
1315 assert_path_eq!(cwd, root);
1316 }
1317
1318 #[test]
1319 fn pwd_points_to_normal_file() {
1320 let file = NamedTempFile::new().unwrap();
1321 let engine_state = engine_state_with_pwd(file.path());
1322
1323 engine_state.cwd(None).unwrap_err();
1324 }
1325
1326 #[test]
1327 fn pwd_points_to_normal_directory() {
1328 let dir = TempDir::new().unwrap();
1329 let engine_state = engine_state_with_pwd(dir.path());
1330
1331 let cwd = engine_state.cwd(None).unwrap();
1332 assert_path_eq!(cwd, dir.path());
1333 }
1334
1335 #[test]
1336 fn pwd_points_to_symlink_to_file() {
1337 let file = NamedTempFile::new().unwrap();
1338 let temp_file = AbsolutePath::try_new(file.path()).unwrap();
1339 let dir = TempDir::new().unwrap();
1340 let temp = AbsolutePath::try_new(dir.path()).unwrap();
1341
1342 let link = temp.join("link");
1343 symlink(temp_file, &link).unwrap();
1344 let engine_state = engine_state_with_pwd(&link);
1345
1346 engine_state.cwd(None).unwrap_err();
1347 }
1348
1349 #[test]
1350 fn pwd_points_to_symlink_to_directory() {
1351 let dir = TempDir::new().unwrap();
1352 let temp = AbsolutePath::try_new(dir.path()).unwrap();
1353
1354 let link = temp.join("link");
1355 symlink(temp, &link).unwrap();
1356 let engine_state = engine_state_with_pwd(&link);
1357
1358 let cwd = engine_state.cwd(None).unwrap();
1359 assert_path_eq!(cwd, link);
1360 }
1361
1362 #[test]
1363 fn pwd_points_to_broken_symlink() {
1364 let dir = TempDir::new().unwrap();
1365 let temp = AbsolutePath::try_new(dir.path()).unwrap();
1366 let other_dir = TempDir::new().unwrap();
1367 let other_temp = AbsolutePath::try_new(other_dir.path()).unwrap();
1368
1369 let link = temp.join("link");
1370 symlink(other_temp, &link).unwrap();
1371 let engine_state = engine_state_with_pwd(&link);
1372
1373 drop(other_dir);
1374 engine_state.cwd(None).unwrap_err();
1375 }
1376
1377 #[test]
1378 fn pwd_points_to_nonexistent_entity() {
1379 let engine_state = engine_state_with_pwd(TempDir::new().unwrap().path());
1380
1381 engine_state.cwd(None).unwrap_err();
1382 }
1383
1384 #[test]
1385 fn stack_pwd_not_set() {
1386 let dir = TempDir::new().unwrap();
1387 let engine_state = engine_state_with_pwd(dir.path());
1388 let stack = Stack::new();
1389
1390 let cwd = engine_state.cwd(Some(&stack)).unwrap();
1391 assert_eq!(cwd, dir.path());
1392 }
1393
1394 #[test]
1395 fn stack_pwd_is_empty_string() {
1396 let dir = TempDir::new().unwrap();
1397 let engine_state = engine_state_with_pwd(dir.path());
1398 let stack = stack_with_pwd("");
1399
1400 engine_state.cwd(Some(&stack)).unwrap_err();
1401 }
1402
1403 #[test]
1404 fn stack_pwd_points_to_normal_directory() {
1405 let dir1 = TempDir::new().unwrap();
1406 let dir2 = TempDir::new().unwrap();
1407 let engine_state = engine_state_with_pwd(dir1.path());
1408 let stack = stack_with_pwd(dir2.path());
1409
1410 let cwd = engine_state.cwd(Some(&stack)).unwrap();
1411 assert_path_eq!(cwd, dir2.path());
1412 }
1413
1414 #[test]
1415 fn stack_pwd_points_to_normal_directory_with_symlink_components() {
1416 let dir = TempDir::new().unwrap();
1417 let temp = AbsolutePath::try_new(dir.path()).unwrap();
1418
1419 let link = temp.join("link");
1421 symlink(temp, &link).unwrap();
1422 let foo = link.join("foo");
1423 std::fs::create_dir(temp.join("foo")).unwrap();
1424 let engine_state = EngineState::new();
1425 let stack = stack_with_pwd(&foo);
1426
1427 let cwd = engine_state.cwd(Some(&stack)).unwrap();
1428 assert_path_eq!(cwd, foo);
1429 }
1430}