1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
use {ExitStatus, Fd, IFS_DEFAULT, STDERR_FILENO};
use error::{CommandError, RuntimeError};
use io::{FileDesc, Permissions};
use spawn::SpawnBoxed;
use std::borrow::{Borrow, Cow};
use std::convert::From;
use std::hash::Hash;
use std::error::Error;
use std::fmt;
use std::io::Result as IoResult;
use std::marker::PhantomData;
use std::path::Path;
use std::sync::Arc;
use std::rc::Rc;
use tokio_core::reactor::Remote;

use env::atomic;
use env::atomic::FnEnv as AtomicFnEnv;
use env::{ArgsEnv, ArgumentsEnvironment, AsyncIoEnvironment, ChangeWorkingDirectoryEnvironment,
          ExecEnv, ExecutableData, ExecutableEnvironment, ExportedVariableEnvironment,
          FileDescEnv, FileDescEnvironment, FnEnv, FunctionEnvironment,
          IsInteractiveEnvironment, LastStatusEnv, LastStatusEnvironment,
          PlatformSpecificAsyncIoEnv, ReportErrorEnvironment, SetArgumentsEnvironment,
          StringWrapper, SubEnvironment, UnsetFunctionEnvironment,
          UnsetVariableEnvironment, VarEnv, VariableEnvironment, VirtualWorkingDirEnv,
          WorkingDirectoryEnvironment};

/// A struct for configuring a new `Env` instance.
///
/// It implements `Default` (via `DefaultEnvConfig` alias) so it is possible
/// to selectively override certain environment modules while retaining the rest
/// of the default implementations.
///
/// ```
/// # extern crate conch_runtime;
/// # extern crate tokio_core;
/// # use std::rc::Rc;
/// # use conch_runtime::env::{ArgsEnv, ArgumentsEnvironment, DefaultEnvConfig, Env, EnvConfig};
/// # fn main() {
/// let lp = tokio_core::reactor::Core::new().unwrap();
/// let env = Env::with_config(EnvConfig {
///     args_env: ArgsEnv::with_name(Rc::new(String::from("my_shell"))),
///     .. DefaultEnvConfig::new(lp.remote(), None).expect("failed to create config")
/// });
///
/// assert_eq!(**env.name(), "my_shell");
/// # }
/// ```
#[derive(Default, Debug, PartialEq, Eq, Clone)]
pub struct EnvConfig<A, IO, FD, L, V, EX, WD, N, ERR> {
    /// Specify if the environment is running in interactive mode.
    pub interactive: bool,
    /// An implementation of `ArgumentsEnvironment` and possibly `SetArgumentsEnvironment`.
    pub args_env: A,
    /// An implementation of `AsyncIoEnvironment`.
    pub async_io_env: IO,
    /// An implementation of `FileDescEnvironment`.
    pub file_desc_env: FD,
    /// An implementation of `LastStatusEnvironment`.
    pub last_status_env: L,
    /// An implementation of `VariableEnvironment`, `UnsetVariableEnvironment`, and
    /// `ExportedVariableEnvironment`.
    pub var_env: V,
    /// An implementation of `ExecutableEnvironment`.
    pub exec_env: EX,
    /// An implementation of `WorkingDirectoryEnvironment`.
    pub working_dir_env: WD,
    /// A marker to indicate the type used for function names.
    pub fn_name: PhantomData<N>,
    /// A marker to indicate the type used for function errors.
    pub fn_error: PhantomData<ERR>,
}

/// A default environment configuration using provided (non-atomic) implementations,
/// and powered by `tokio`.
///
/// Generic over the representation of shell words, variables, function names, etc.
///
/// ```no_run
/// # extern crate conch_runtime;
/// # extern crate tokio_core;
/// # use std::rc::Rc;
/// # use conch_runtime::env::DefaultEnvConfig;
/// # fn main() {
/// // Can be instantiated as follows
/// let lp = tokio_core::reactor::Core::new().unwrap();
///
/// // Fallback to using one thread per CPU
/// let cfg1 = DefaultEnvConfig::<Rc<String>>::new(lp.remote(), None);
/// // Fallback to specific number of threads
/// let cfg2 = DefaultEnvConfig::<Rc<String>>::new(lp.remote(), Some(2));
/// # }
/// ```
pub type DefaultEnvConfig<T> =
    EnvConfig<
        ArgsEnv<T>,
        PlatformSpecificAsyncIoEnv,
        FileDescEnv<Rc<FileDesc>>,
        LastStatusEnv,
        VarEnv<T, T>,
        ExecEnv,
        VirtualWorkingDirEnv,
        T,
        RuntimeError,
    >;

/// A default environment configuration using provided (non-atomic) implementations.
/// and `Rc<String>` to represent shell values.
pub type DefaultEnvConfigRc = DefaultEnvConfig<Rc<String>>;

/// A default environment configuration using provided (atomic) implementations.
///
/// Generic over the representation of shell words, variables, function names, etc.
///
/// ```no_run
/// # extern crate conch_runtime;
/// # extern crate tokio_core;
/// # use std::sync::Arc;
/// # use conch_runtime::env::atomic::DefaultEnvConfig;
/// # fn main() {
/// // Can be instantiated as follows
/// let lp = tokio_core::reactor::Core::new().unwrap();
///
/// // Fallback to using one thread per CPU
/// let cfg1 = DefaultEnvConfig::<Arc<String>>::new_atomic(lp.remote(), None);
/// // Fallback to specific number of threads
/// let cfg2 = DefaultEnvConfig::<Arc<String>>::new_atomic(lp.remote(), Some(2));
/// # }
/// ```
pub type DefaultAtomicEnvConfig<T> =
    EnvConfig<
        atomic::ArgsEnv<T>,
        PlatformSpecificAsyncIoEnv,
        atomic::FileDescEnv<Arc<FileDesc>>,
        LastStatusEnv,
        atomic::VarEnv<T, T>,
        ExecEnv,
        atomic::VirtualWorkingDirEnv,
        T,
        RuntimeError,
    >;

/// A default environment configuration using provided (atomic) implementations.
/// and `Arc<String>` to represent shell values.
pub type DefaultAtomicEnvConfigArc = DefaultAtomicEnvConfig<Arc<String>>;

impl<T> DefaultEnvConfig<T> where T: Eq + Hash + From<String> {
    /// Creates a new `DefaultEnvConfig` using default environment components.
    ///
    /// A `tokio` `Remote` handle is required for performing async IO on
    /// supported platforms. Otherwise, if the platform does not support
    /// (easily) support async IO, a dedicated thread-pool will be used.
    /// If no thread number is specified, one thread per CPU will be used.
    pub fn new(remote: Remote, fallback_num_threads: Option<usize>) -> IoResult<Self> {
        Ok(DefaultEnvConfig {
            interactive: false,
            args_env: ArgsEnv::new(),
            async_io_env: PlatformSpecificAsyncIoEnv::new(remote.clone(), fallback_num_threads),
            file_desc_env: try!(FileDescEnv::with_process_stdio()),
            last_status_env: LastStatusEnv::new(),
            var_env: VarEnv::with_process_env_vars(),
            exec_env: ExecEnv::new(remote),
            working_dir_env: try!(VirtualWorkingDirEnv::with_process_working_dir()),
            fn_name: PhantomData,
            fn_error: PhantomData,
        })
    }
}

impl<T> DefaultAtomicEnvConfig<T> where T: Eq + Hash + From<String> {
    /// Creates a new `atomic::DefaultConfig` using default environment components.
    ///
    /// A `tokio` `Remote` handle is required for performing async IO on
    /// supported platforms. Otherwise, if the platform does not support
    /// (easily) support async IO, a dedicated thread-pool will be used.
    /// If no thread number is specified, one thread per CPU will be used.
    pub fn new_atomic(remote: Remote, fallback_num_threads: Option<usize>) -> IoResult<Self> {
        Ok(DefaultAtomicEnvConfig {
            interactive: false,
            args_env: atomic::ArgsEnv::new(),
            async_io_env: PlatformSpecificAsyncIoEnv::new(remote.clone(), fallback_num_threads),
            file_desc_env: try!(atomic::FileDescEnv::with_process_stdio()),
            last_status_env: LastStatusEnv::new(),
            var_env: atomic::VarEnv::with_process_env_vars(),
            exec_env: ExecEnv::new(remote),
            working_dir_env: try!(atomic::VirtualWorkingDirEnv::with_process_working_dir()),
            fn_name: PhantomData,
            fn_error: PhantomData,
        })
    }
}

macro_rules! impl_env {
    ($(#[$attr:meta])* pub struct $Env:ident, $FnEnv:ident, $Rc:ident, $($extra:tt)*) => {
        $(#[$attr])*
        pub struct $Env<A, IO, FD, L, V, EX, WD, N: Eq + Hash, ERR> {
            /// If the shell is running in interactive mode
            interactive: bool,
            args_env: A,
            async_io_env: IO,
            file_desc_env: FD,
            fn_env: $FnEnv<N, $Rc<SpawnBoxed<$Env<A, IO, FD, L, V, EX, WD, N, ERR>, Error = ERR> $($extra)*>>,
            last_status_env: L,
            var_env: V,
            exec_env: EX,
            working_dir_env: WD,
        }

        impl<A, IO, FD, L, V, EX, WD, N, ERR> $Env<A, IO, FD, L, V, EX, WD, N, ERR>
            where N: Hash + Eq,
        {
            /// Creates an environment using the provided configuration of subcomponents.
            ///
            /// See `EnvConfig` for the kinds of overrides possible. `DefaultEnvConfig`
            /// comes with provided implementations to get you up and running.
            ///
            /// General recommendations:
            ///
            /// * The result of evaluating a shell word will often be copied and reused
            /// in many different places. It's strongly recommened that `Rc` or `Arc`
            /// wrappers (e.g. `Rc<String>`) be used to minimize having to reallocate
            /// and copy the same data.
            /// * Whatever type represents a shell function body needs to be cloned to
            /// get around borrow restrictions and potential recursive executions and
            /// (re-)definitions. Since this type is probably an AST (which may be
            /// arbitrarily large), `Rc` and `Arc` are your friends.
            pub fn with_config(cfg: EnvConfig<A, IO, FD, L, V, EX, WD, N, ERR>) -> Self
                where V: ExportedVariableEnvironment,
                      V::VarName: From<String>,
                      V::Var: Borrow<String> + From<String>,
            {
                let mut env = $Env {
                    interactive: cfg.interactive,
                    args_env: cfg.args_env,
                    async_io_env: cfg.async_io_env,
                    fn_env: $FnEnv::new(),
                    file_desc_env: cfg.file_desc_env,
                    last_status_env: cfg.last_status_env,
                    var_env: cfg.var_env,
                    exec_env: cfg.exec_env,
                    working_dir_env: cfg.working_dir_env,
                };

                let sh_lvl = "SHLVL".to_owned().into();
                let level = env.var(&sh_lvl)
                    .and_then(|lvl| lvl.borrow().parse::<isize>().ok().map(|l| l+1))
                    .unwrap_or(1);

                // FIXME: set/update $PWD, $OLDPWD
                env.set_exported_var(sh_lvl.into(), level.to_string().into(), true);
                env.set_var("IFS".to_owned().into(), IFS_DEFAULT.to_owned().into());
                env
            }
        }

        impl<A, IO, FD, L, V, EX, WD, N, ERR> Clone for $Env<A, IO, FD, L, V, EX, WD, N, ERR>
            where A: Clone,
                  FD: Clone,
                  L: Clone,
                  V: Clone,
                  N: Hash + Eq,
                  IO: Clone,
                  EX: Clone,
                  WD: Clone,
        {
            fn clone(&self) -> Self {
                $Env {
                    interactive: self.interactive,
                    args_env: self.args_env.clone(),
                    async_io_env: self.async_io_env.clone(),
                    file_desc_env: self.file_desc_env.clone(),
                    fn_env: self.fn_env.clone(),
                    last_status_env: self.last_status_env.clone(),
                    var_env: self.var_env.clone(),
                    exec_env: self.exec_env.clone(),
                    working_dir_env: self.working_dir_env.clone(),
                }
            }
        }

        impl<A, IO, FD, L, V, EX, WD, N, ERR> fmt::Debug for $Env<A, IO, FD, L, V, EX, WD, N, ERR>
            where A: fmt::Debug,
                  FD: fmt::Debug,
                  L: fmt::Debug,
                  V: fmt::Debug,
                  N: Hash + Eq + Ord + fmt::Debug,
                  IO: fmt::Debug,
                  EX: fmt::Debug,
                  WD: fmt::Debug,
        {
            fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
                use std::collections::BTreeSet;

                let fn_names: BTreeSet<_> = self.fn_env.fn_names().collect();

                fmt.debug_struct(stringify!($Env))
                    .field("interactive", &self.interactive)
                    .field("args_env", &self.args_env)
                    .field("async_io_env", &self.async_io_env)
                    .field("file_desc_env", &self.file_desc_env)
                    .field("functions", &fn_names)
                    .field("last_status_env", &self.last_status_env)
                    .field("var_env", &self.var_env)
                    .field("exec_env", &self.exec_env)
                    .field("working_dir_env", &self.working_dir_env)
                    .finish()
            }
        }

        impl<A, IO, FD, L, V, EX, WD, N, ERR> From<EnvConfig<A, IO, FD, L, V, EX, WD, N, ERR>>
            for $Env<A, IO, FD, L, V, EX, WD, N, ERR>
            where N: Hash + Eq,
                  V: ExportedVariableEnvironment,
                  V::VarName: From<String>,
                  V::Var: Borrow<String> + From<String>,
        {
            fn from(cfg: EnvConfig<A, IO, FD, L, V, EX, WD, N, ERR>) -> Self {
                Self::with_config(cfg)
            }
        }

        impl<A, IO, FD, L, V, EX, WD, N, ERR> IsInteractiveEnvironment
            for $Env<A, IO, FD, L, V, EX, WD, N, ERR>
            where N: Hash + Eq,
        {
            fn is_interactive(&self) -> bool {
                self.interactive
            }
        }

        impl<A, IO, FD, L, V, EX, WD, N, ERR> SubEnvironment
            for $Env<A, IO, FD, L, V, EX, WD, N, ERR>
            where A: SubEnvironment,
                  FD: SubEnvironment,
                  L: SubEnvironment,
                  V: SubEnvironment,
                  N: Hash + Eq,
                  IO: SubEnvironment,
                  EX: SubEnvironment,
                  WD: SubEnvironment,
        {
            fn sub_env(&self) -> Self {
                $Env {
                    interactive: self.is_interactive(),
                    args_env: self.args_env.sub_env(),
                    async_io_env: self.async_io_env.sub_env(),
                    file_desc_env: self.file_desc_env.sub_env(),
                    fn_env: self.fn_env.sub_env(),
                    last_status_env: self.last_status_env.sub_env(),
                    var_env: self.var_env.sub_env(),
                    exec_env: self.exec_env.sub_env(),
                    working_dir_env: self.working_dir_env.sub_env(),
                }
            }
        }

        impl<A, IO, FD, L, V, EX, WD, N, ERR> ArgumentsEnvironment
            for $Env<A, IO, FD, L, V, EX, WD, N, ERR>
            where A: ArgumentsEnvironment,
                  A::Arg: Clone,
                  N: Hash + Eq,
        {
            type Arg = A::Arg;

            fn name(&self) -> &Self::Arg {
                self.args_env.name()
            }

            fn arg(&self, idx: usize) -> Option<&Self::Arg> {
                self.args_env.arg(idx)
            }

            fn args_len(&self) -> usize {
                self.args_env.args_len()
            }

            fn args(&self) -> Cow<[Self::Arg]> {
                self.args_env.args()
            }
        }

        impl<A, IO, FD, L, V, EX, WD, N, ERR> SetArgumentsEnvironment
            for $Env<A, IO, FD, L, V, EX, WD, N, ERR>
            where A: SetArgumentsEnvironment,
                  N: Hash + Eq,
        {
            type Args = A::Args;

            fn set_args(&mut self, new_args: Self::Args) -> Self::Args {
                self.args_env.set_args(new_args)
            }
        }

        impl<A, IO, FD, L, V, EX, WD, N, ERR> AsyncIoEnvironment
            for $Env<A, IO, FD, L, V, EX, WD, N, ERR>
            where IO: AsyncIoEnvironment,
                  N: Hash + Eq,
        {
            type Read = IO::Read;
            type WriteAll = IO::WriteAll;

            fn read_async(&mut self, fd: FileDesc) -> Self::Read {
                self.async_io_env.read_async(fd)
            }

            fn write_all(&mut self, fd: FileDesc, data: Vec<u8>) -> Self::WriteAll {
                self.async_io_env.write_all(fd, data)
            }

            fn write_all_best_effort(&mut self, fd: FileDesc, data: Vec<u8>) {
                self.async_io_env.write_all_best_effort(fd, data);
            }
        }

        impl<A, IO, FD, L, V, EX, WD, N, ERR> FileDescEnvironment
            for $Env<A, IO, FD, L, V, EX, WD, N, ERR>
            where FD: FileDescEnvironment,
                  N: Hash + Eq,
        {
            type FileHandle = FD::FileHandle;

            fn file_desc(&self, fd: Fd) -> Option<(&Self::FileHandle, Permissions)> {
                self.file_desc_env.file_desc(fd)
            }

            fn set_file_desc(&mut self, fd: Fd, fdes: Self::FileHandle, perms: Permissions) {
                self.file_desc_env.set_file_desc(fd, fdes, perms)
            }

            fn close_file_desc(&mut self, fd: Fd) {
                self.file_desc_env.close_file_desc(fd)
            }
        }

        impl<A, IO, FD, L, V, EX, WD, N, ERR> ReportErrorEnvironment
            for $Env<A, IO, FD, L, V, EX, WD, N, ERR>
            where A: ArgumentsEnvironment,
                  A::Arg: fmt::Display,
                  FD: FileDescEnvironment,
                  FD::FileHandle: Borrow<FileDesc>,
                  N: Hash + Eq,
        {
            fn report_error(&self, err: &Error) {
                use std::io::Write;

                if let Some((fd, _)) = self.file_desc(STDERR_FILENO) {
                    let _ = writeln!(fd.borrow(), "{}: {}", self.name(), err);
                }
            }
        }

        impl<A, IO, FD, L, V, EX, WD, N, ERR> FunctionEnvironment
            for $Env<A, IO, FD, L, V, EX, WD, N, ERR>
            where N: Hash + Eq + Clone,
        {
            type FnName = N;
            type Fn = $Rc<SpawnBoxed<Self, Error = ERR> $($extra)*>;

            fn function(&self, name: &Self::FnName) -> Option<&Self::Fn> {
                self.fn_env.function(name)
            }

            fn set_function(&mut self, name: Self::FnName, func: Self::Fn) {
                self.fn_env.set_function(name, func);
            }

            fn has_function(&self, name: &Self::FnName) -> bool {
                self.fn_env.has_function(name)
            }
        }

        impl<A, IO, FD, L, V, EX, WD, N, ERR> UnsetFunctionEnvironment
            for $Env<A, IO, FD, L, V, EX, WD, N, ERR>
            where N: Hash + Eq + Clone,
        {
            fn unset_function(&mut self, name: &Self::FnName) {
                self.fn_env.unset_function(name);
            }
        }

        impl<A, IO, FD, L, V, EX, WD, N, ERR> LastStatusEnvironment
            for $Env<A, IO, FD, L, V, EX, WD, N, ERR>
            where L: LastStatusEnvironment,
                  N: Hash + Eq,
        {
            fn last_status(&self) -> ExitStatus {
                self.last_status_env.last_status()
            }

            fn set_last_status(&mut self, status: ExitStatus) {
                self.last_status_env.set_last_status(status);
            }
        }

        impl<A, IO, FD, L, V, EX, WD, N, ERR> VariableEnvironment
            for $Env<A, IO, FD, L, V, EX, WD, N, ERR>
            where V: VariableEnvironment,
                  N: Hash + Eq,
        {
            type VarName = V::VarName;
            type Var = V::Var;

            fn var<Q: ?Sized>(&self, name: &Q) -> Option<&Self::Var>
                where Self::VarName: Borrow<Q>, Q: Hash + Eq,
            {
                self.var_env.var(name)
            }

            fn set_var(&mut self, name: Self::VarName, val: Self::Var) {
                self.var_env.set_var(name, val);
            }

            fn env_vars(&self) -> Cow<[(&Self::VarName, &Self::Var)]> {
                self.var_env.env_vars()
            }
        }

        impl<A, IO, FD, L, V, EX, WD, N, ERR> ExportedVariableEnvironment
            for $Env<A, IO, FD, L, V, EX, WD, N, ERR>
            where V: ExportedVariableEnvironment,
                  N: Hash + Eq,
        {
            fn exported_var(&self, name: &Self::VarName) -> Option<(&Self::Var, bool)> {
                self.var_env.exported_var(name)
            }

            fn set_exported_var(&mut self, name: Self::VarName, val: Self::Var, exported: bool) {
                self.var_env.set_exported_var(name, val, exported)
            }
        }

        impl<A, IO, FD, L, V, EX, WD, N, ERR> UnsetVariableEnvironment
            for $Env<A, IO, FD, L, V, EX, WD, N, ERR>
            where V: UnsetVariableEnvironment,
                  N: Hash + Eq,
        {
            fn unset_var<Q: ?Sized>(&mut self, name: &Q)
                where Self::VarName: Borrow<Q>, Q: Hash + Eq
            {
                self.var_env.unset_var(name)
            }
        }

        impl<A, IO, FD, L, V, EX, WD, N, ERR> ExecutableEnvironment
            for $Env<A, IO, FD, L, V, EX, WD, N, ERR>
            where V: UnsetVariableEnvironment,
                  N: Hash + Eq,
                  EX: ExecutableEnvironment,
        {
            type Future = EX::Future;

            fn spawn_executable(&mut self, data: ExecutableData)
                -> Result<Self::Future, CommandError>
            {
                self.exec_env.spawn_executable(data)
            }
        }

        impl<A, IO, FD, L, V, EX, WD, N, ERR> WorkingDirectoryEnvironment
            for $Env<A, IO, FD, L, V, EX, WD, N, ERR>
            where N: Hash + Eq,
                  WD: WorkingDirectoryEnvironment,
        {
            fn path_relative_to_working_dir<'a>(&self, path: Cow<'a, Path>) -> Cow<'a, Path> {
                self.working_dir_env.path_relative_to_working_dir(path)
            }

            fn current_working_dir(&self) -> &Path {
                self.working_dir_env.current_working_dir()
            }
        }

        impl<A, IO, FD, L, V, EX, WD, N, ERR> ChangeWorkingDirectoryEnvironment
            for $Env<A, IO, FD, L, V, EX, WD, N, ERR>
            where N: Hash + Eq,
                  WD: ChangeWorkingDirectoryEnvironment,
        {
            fn change_working_dir<'a>(&mut self, path: Cow<'a, Path>) -> IoResult<()> {
                self.working_dir_env.change_working_dir(path)
            }
        }
    }
}

impl_env!(
    /// A shell environment implementation which delegates work to other
    /// environment implementations.
    ///
    /// Uses `Rc` internally. For a possible `Send` and `Sync` implementation,
    /// see `atomic::Env`.
    pub struct Env,
    FnEnv,
    Rc,
);

impl_env!(
    /// A shell environment implementation which delegates work to other
    /// environment implementations.
    ///
    /// Uses `Arc` internally. If `Send` and `Sync` is not required of the implementation,
    /// see `Env` as a cheaper alternative.
    pub struct AtomicEnv,
    AtomicFnEnv,
    Arc,
    + Send + Sync
);

/// A default environment configured with provided (non-atomic) implementations.
///
/// Generic over the representation of shell words, variables, function names, etc.
///
/// ```no_run
/// # extern crate conch_runtime;
/// # extern crate tokio_core;
/// # use std::rc::Rc;
/// # use conch_runtime::env::DefaultEnv;
/// # use conch_runtime::env::DefaultEnvConfig;
/// # fn main() {
/// // Can be instantiated as follows
/// let lp = tokio_core::reactor::Core::new().unwrap();
///
/// // Fallback to using one thread per CPU
/// let env1 = DefaultEnv::<Rc<String>>::new(lp.remote(), None);
///
/// // Fallback to specific number of threads
/// let env2 = DefaultEnv::<Rc<String>>::new(lp.remote(), Some(2));
/// # }
/// ```
pub type DefaultEnv<T> =
    Env<
        ArgsEnv<T>,
        PlatformSpecificAsyncIoEnv,
        FileDescEnv<Rc<FileDesc>>,
        LastStatusEnv,
        VarEnv<T, T>,
        ExecEnv,
        VirtualWorkingDirEnv,
        T,
        RuntimeError,
    >;

/// A default environment configured with provided (non-atomic) implementations,
/// and `Rc<String>` to represent shell values.
pub type DefaultEnvRc = DefaultEnv<Rc<String>>;

/// A default environment configured with provided (non-atomic) implementations.
///
/// Generic over the representation of shell words, variables, function names, etc.
///
/// ```no_run
/// # extern crate conch_runtime;
/// # extern crate tokio_core;
/// # use std::sync::Arc;
/// # use conch_runtime::env::atomic::DefaultEnv;
/// # use conch_runtime::env::atomic::DefaultEnvConfig;
/// # fn main() {
/// // Can be instantiated as follows
/// let lp = tokio_core::reactor::Core::new().unwrap();
///
/// // Fallback to using one thread per CPU
/// let env1 = DefaultEnv::<Arc<String>>::new_atomic(lp.remote(), None);
///
/// // Fallback to specific number of threads
/// let env2 = DefaultEnv::<Arc<String>>::new_atomic(lp.remote(), Some(2));
/// # }
/// ```
pub type DefaultAtomicEnv<T> =
    AtomicEnv<
        atomic::ArgsEnv<T>,
        PlatformSpecificAsyncIoEnv,
        atomic::FileDescEnv<Arc<FileDesc>>,
        LastStatusEnv,
        atomic::VarEnv<T, T>,
        ExecEnv,
        atomic::VirtualWorkingDirEnv,
        T,
        RuntimeError,
    >;

/// A default environment configured with provided (atomic) implementations,
/// and uses `Arc<String>` to represent shell values.
pub type DefaultAtomicEnvArc = DefaultAtomicEnv<Arc<String>>;

impl<T> DefaultEnv<T> where T: StringWrapper {
    /// Creates a new default environment.
    ///
    /// See the definition of `DefaultEnvConfig` for what configuration will be used.
    pub fn new(remote: Remote, fallback_num_threads: Option<usize>) -> IoResult<Self> {
        DefaultEnvConfig::new(remote, fallback_num_threads).map(Self::with_config)
    }
}

impl<T> DefaultAtomicEnv<T> where T: StringWrapper {
    /// Creates a new default environment.
    ///
    /// See the definition of `atomic::DefaultEnvConfig` for what configuration will be used.
    pub fn new_atomic(remote: Remote, fallback_num_threads: Option<usize>) -> IoResult<Self> {
        DefaultAtomicEnvConfig::new_atomic(remote, fallback_num_threads).map(Self::with_config)
    }
}

#[cfg(test)]
mod tests {
    extern crate tokio_core;
    use env::{DefaultEnvConfigRc, DefaultEnvRc, IsInteractiveEnvironment};

    #[test]
    fn test_env_is_interactive() {
        let lp = tokio_core::reactor::Core::new().unwrap();

        for &interactive in &[true, false] {
            let env = DefaultEnvRc::with_config(DefaultEnvConfigRc {
                interactive: interactive,
                ..DefaultEnvConfigRc::new(lp.remote(), Some(1)).unwrap()
            });
            assert_eq!(env.is_interactive(), interactive);
        }
    }
}