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
// This file is part of yash, an extended POSIX shell.
// Copyright (C) 2021 WATANABE Yuki
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

use super::Context;
use super::VariableSet;
use crate::Env;
use std::ops::Deref;
use std::ops::DerefMut;

/// RAII-style guard for temporarily retaining a variable context.
///
/// The guard object is created by [`VariableSet::push_context`].
#[derive(Debug)]
#[must_use = "You must retain ContextGuard to keep the context alive"]
pub struct ContextGuard<'a> {
    stack: &'a mut VariableSet,
}

impl VariableSet {
    /// Pushes a new context to this variable set.
    ///
    /// This function returns a scope guard that will pop the context when dropped.
    /// The guard provides a mutable reference to the variable set, allowing
    /// variables to be added or modified within the context.
    ///
    /// Note that the guard does not provide access to the whole environment
    /// that contains the variable set. If you need access to the environment,
    /// use [`Env::push_context`] instead.
    #[inline]
    pub fn push_context(&mut self, context: Context) -> ContextGuard<'_> {
        self.push_context_impl(context);
        ContextGuard { stack: self }
    }

    /// Pops the topmost context from the variable set.
    #[inline]
    pub fn pop_context(guard: ContextGuard<'_>) {
        drop(guard)
    }
}

/// When the guard is dropped, the context that was pushed when creating the
/// guard is [popped](VariableSet::pop_context).
impl std::ops::Drop for ContextGuard<'_> {
    #[inline]
    fn drop(&mut self) {
        self.stack.pop_context_impl()
    }
}

impl std::ops::Deref for ContextGuard<'_> {
    type Target = VariableSet;
    #[inline]
    fn deref(&self) -> &VariableSet {
        self.stack
    }
}

impl std::ops::DerefMut for ContextGuard<'_> {
    #[inline]
    fn deref_mut(&mut self) -> &mut VariableSet {
        self.stack
    }
}

/// RAII-style guard that makes sure a context is popped properly
///
/// The guard object is created by [`Env::push_context`].
#[derive(Debug)]
#[must_use = "The context is popped when the guard is dropped"]
pub struct EnvContextGuard<'a> {
    env: &'a mut Env,
}

impl Env {
    /// Pushes a new context to the variable set.
    ///
    /// This function is equivalent to
    /// `self.variables.push_context(context_type)`, but returns an
    /// `EnvContextGuard` that allows re-borrowing the `Env`.
    #[inline]
    pub fn push_context(&mut self, context: Context) -> EnvContextGuard<'_> {
        self.variables.push_context_impl(context);
        EnvContextGuard { env: self }
    }

    /// Pops the topmost context from the variable set.
    #[inline]
    pub fn pop_context(guard: EnvContextGuard<'_>) {
        drop(guard)
    }
}

/// When the guard is dropped, the context that was pushed when creating the
/// guard is [popped](VariableSet::pop_context).
impl Drop for EnvContextGuard<'_> {
    #[inline]
    fn drop(&mut self) {
        self.env.variables.pop_context_impl()
    }
}

impl Deref for EnvContextGuard<'_> {
    type Target = Env;
    #[inline]
    fn deref(&self) -> &Env {
        self.env
    }
}

impl DerefMut for EnvContextGuard<'_> {
    #[inline]
    fn deref_mut(&mut self) -> &mut Env {
        self.env
    }
}

#[cfg(test)]
mod tests {
    use super::super::Scope;
    use super::super::Value;
    use super::*;

    #[test]
    fn scope_guard() {
        let mut env = Env::new_virtual();
        let mut guard = env.variables.push_context(Context::default());
        guard
            .get_or_new("foo", Scope::Global)
            .assign("", None)
            .unwrap();
        guard
            .get_or_new("bar", Scope::Local)
            .assign("", None)
            .unwrap();
        VariableSet::pop_context(guard);

        let variable = env.variables.get("foo").unwrap();
        assert_eq!(variable.value, Some(Value::scalar("")));
        assert_eq!(env.variables.get("bar"), None);
    }

    #[test]
    fn env_scope_guard() {
        let mut env = Env::new_virtual();
        let mut guard = env.push_context(Context::default());
        guard
            .variables
            .get_or_new("foo", Scope::Global)
            .assign("", None)
            .unwrap();
        guard
            .variables
            .get_or_new("bar", Scope::Local)
            .assign("", None)
            .unwrap();
        Env::pop_context(guard);

        let variable = env.variables.get("foo").unwrap();
        assert_eq!(variable.value, Some(Value::scalar("")));
        assert_eq!(env.variables.get("bar"), None);
    }
}