yash-builtin 0.16.0

Implementation of the built-in utilities of yash
Documentation
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
// This file is part of yash, an extended POSIX shell.
// Copyright (C) 2023 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/>.

//! Defines the behavior of the unset built-in.

use crate::common::report::prepare_report_message_and_divert;
use thiserror::Error;
use yash_env::Env;
use yash_env::semantics::ExitStatus;
use yash_env::semantics::Field;
use yash_env::source::Location;
use yash_env::source::pretty::{Report, ReportType, Span, SpanRole, add_span};
#[cfg(doc)]
use yash_env::system::Concurrent;
use yash_env::system::Fcntl;
use yash_env::system::Isatty;
use yash_env::system::Write;
use yash_env::variable::Scope::Global;

/// Error returned by [`unset_variables`].
#[derive(Clone, Debug, Eq, Error, PartialEq)]
pub struct UnsetVariablesError<'a> {
    /// The name of the read-only variable
    pub name: &'a Field,
    /// The location where the variable was made read-only
    pub read_only_location: Location,
}

impl std::fmt::Display for UnsetVariablesError<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let error = yash_env::variable::UnsetError {
            name: &self.name.value,
            read_only_location: &self.read_only_location,
        };
        error.fmt(f)
    }
}

impl UnsetVariablesError<'_> {
    /// Converts the error to a report.
    pub fn to_report(&self) -> Report<'_> {
        let mut report = Report::new();
        report.r#type = ReportType::Error;
        report.title = "cannot unset variable".into();
        add_span(
            &self.name.origin.code,
            Span {
                range: self.name.origin.byte_range(),
                role: SpanRole::Primary {
                    label: format!("read-only variable `{}`", self.name).into(),
                },
            },
            &mut report.snippets,
        );
        add_span(
            &self.read_only_location.code,
            Span {
                range: self.read_only_location.byte_range(),
                role: SpanRole::Supplementary {
                    label: format!("variable `{}` was made read-only here", self.name).into(),
                },
            },
            &mut report.snippets,
        );
        report
    }
}

impl<'a> From<&'a UnsetVariablesError<'_>> for Report<'a> {
    #[inline]
    fn from(error: &'a UnsetVariablesError<'_>) -> Self {
        error.to_report()
    }
}

/// Unsets shell variables.
///
/// This function tries to unset all the variables named by `names`. Any error
/// unsetting a variable is reported in the returned vector and the function
/// continues to unset the remaining variables. The returned vector is empty if
/// all the variables are unset successfully.
///
/// TODO Allow unsetting local variables only.
pub fn unset_variables<'a, S>(
    env: &mut Env<S>,
    names: &'a [Field],
) -> Vec<UnsetVariablesError<'a>> {
    let mut errors = Vec::new();
    for name in names {
        match env.variables.unset(&name.value, Global) {
            Ok(_) => (),
            Err(error) => errors.push(UnsetVariablesError {
                name,
                read_only_location: error.read_only_location.clone(),
            }),
        }
    }
    errors
}

/// Creates a message that describes the errors.
///
/// See [`prepare_report_message_and_divert`] for the second return value.
#[deprecated(
    note = "use `merge_reports` and `prepare_report_message_and_divert` directly",
    since = "0.11.0"
)]
#[must_use = "returned message should be printed"]
pub fn unset_variables_error_message<S>(
    env: &Env<S>,
    errors: &[UnsetVariablesError],
) -> (String, yash_env::semantics::Result)
where
    S: Fcntl + Isatty + Write,
{
    let mut report = Report::new();
    report.r#type = ReportType::Error;
    report.title = "cannot unset variable".into();
    for error in errors {
        add_span(
            &error.name.origin.code,
            Span {
                range: error.name.origin.byte_range(),
                role: SpanRole::Primary {
                    label: error.to_string().into(),
                },
            },
            &mut report.snippets,
        );
        add_span(
            &error.read_only_location.code,
            Span {
                range: error.read_only_location.byte_range(),
                role: SpanRole::Supplementary {
                    label: format!("variable `{}` was made read-only here", error.name).into(),
                },
            },
            &mut report.snippets,
        );
    }
    prepare_report_message_and_divert(env, report)
}

/// Prints an error message to the standard error.
///
/// This function constructs a message with [`unset_variables_error_message`]
/// and prints it with [`Concurrent::print_error`].
#[deprecated(
    note = "use `merge_reports` and `report_failure` directly",
    since = "0.11.0"
)]
pub async fn report_variables_error<S>(
    env: &mut Env<S>,
    errors: &[UnsetVariablesError<'_>],
) -> crate::Result
where
    S: Fcntl + Isatty + Write,
{
    #[allow(deprecated)]
    let (message, divert) = unset_variables_error_message(env, errors);
    env.system.print_error(&message).await;
    crate::Result::with_exit_status_and_divert(ExitStatus::FAILURE, divert)
}

/// Error returned by [`unset_functions`].
#[derive(Clone, Debug, Eq, Error, PartialEq)]
#[error("cannot unset read-only function `{name}`")]
pub struct UnsetFunctionsError<'a> {
    /// The name of the function
    pub name: &'a Field,
    /// The location where the function was made read-only
    pub read_only_location: Location,
}

impl UnsetFunctionsError<'_> {
    /// Converts the error to a report.
    #[must_use]
    pub fn to_report(&self) -> Report<'_> {
        let mut report = Report::new();
        report.r#type = ReportType::Error;
        report.title = "cannot unset function".into();
        add_span(
            &self.name.origin.code,
            Span {
                range: self.name.origin.byte_range(),
                role: SpanRole::Primary {
                    label: format!("read-only function `{}`", self.name).into(),
                },
            },
            &mut report.snippets,
        );
        add_span(
            &self.read_only_location.code,
            Span {
                range: self.read_only_location.byte_range(),
                role: SpanRole::Supplementary {
                    label: format!("function `{}` was made read-only here", self.name).into(),
                },
            },
            &mut report.snippets,
        );
        report
    }
}

impl<'a> From<&'a UnsetFunctionsError<'_>> for Report<'a> {
    #[inline]
    fn from(error: &'a UnsetFunctionsError<'_>) -> Self {
        error.to_report()
    }
}

/// Unsets shell functions.
///
/// This function tries to unset all the functions named by `names`. Any error
/// unsetting a function is reported in the returned vector and the function
/// continues to unset the remaining functions. The returned vector is empty if
/// all the functions are unset successfully.
pub fn unset_functions<'a, S>(
    env: &mut Env<S>,
    names: &'a [Field],
) -> Vec<UnsetFunctionsError<'a>> {
    let mut errors = Vec::new();
    for name in names {
        match env.functions.unset(&name.value) {
            Ok(_) => (),
            Err(error) => errors.push(UnsetFunctionsError {
                name,
                read_only_location: error.existing.read_only_location.clone().unwrap(),
            }),
        }
    }
    errors
}

/// Creates a message that describes the errors.
///
/// See [`prepare_report_message_and_divert`] for the second return value.
#[deprecated(
    note = "use `merge_reports` and `prepare_report_message_and_divert` directly",
    since = "0.11.0"
)]
#[must_use = "returned message should be printed"]
pub fn unset_functions_error_message<S>(
    env: &mut Env<S>,
    errors: &[UnsetFunctionsError<'_>],
) -> (String, yash_env::semantics::Result)
where
    S: Fcntl + Isatty + Write,
{
    let mut report = Report::new();
    report.r#type = ReportType::Error;
    report.title = "cannot unset function".into();
    for error in errors {
        add_span(
            &error.name.origin.code,
            Span {
                range: error.name.origin.byte_range(),
                role: SpanRole::Primary {
                    label: error.to_string().into(),
                },
            },
            &mut report.snippets,
        );
        add_span(
            &error.read_only_location.code,
            Span {
                range: error.read_only_location.byte_range(),
                role: SpanRole::Supplementary {
                    label: format!("function `{}` was made read-only here", error.name).into(),
                },
            },
            &mut report.snippets,
        );
    }
    prepare_report_message_and_divert(env, report)
}

/// Prints an error message to the standard error.
///
/// This function constructs a message with [`unset_functions_error_message`]
/// and prints it with [`Concurrent::print_error`].
#[deprecated(
    note = "use `merge_reports` and `report_failure` directly",
    since = "0.11.0"
)]
pub async fn report_functions_error<S>(
    env: &mut Env<S>,
    errors: &[UnsetFunctionsError<'_>],
) -> crate::Result
where
    S: Fcntl + Isatty + Write,
{
    #[allow(deprecated)]
    let (message, divert) = unset_functions_error_message(env, errors);
    env.system.print_error(&message).await;
    crate::Result::with_exit_status_and_divert(ExitStatus::FAILURE, divert)
}

#[cfg(test)]
mod tests {
    use super::*;
    use assert_matches::assert_matches;
    use yash_env::function::Function;
    use yash_env::source::Location;
    use yash_env::variable::Value;

    #[test]
    fn unsetting_one_variable() {
        let mut env = Env::new_virtual();
        env.get_or_create_variable("foo", Global)
            .assign("FOO", None)
            .unwrap();
        env.get_or_create_variable("bar", Global)
            .assign("BAR", None)
            .unwrap();
        env.get_or_create_variable("baz", Global)
            .assign("BAZ", None)
            .unwrap();
        let names = Field::dummies(["bar"]);

        let errors = unset_variables(&mut env, &names);
        assert_eq!(errors, []);
        assert_eq!(
            env.variables.get("foo").unwrap().value,
            Some(Value::scalar("FOO")),
        );
        assert_eq!(env.variables.get("bar"), None);
        assert_eq!(
            env.variables.get("baz").unwrap().value,
            Some(Value::scalar("BAZ")),
        );
    }

    #[test]
    fn unsetting_many_variables() {
        let mut env = Env::new_virtual();
        env.get_or_create_variable("foo", Global)
            .assign("FOO", None)
            .unwrap();
        env.get_or_create_variable("bar", Global)
            .assign("BAR", None)
            .unwrap();
        env.get_or_create_variable("baz", Global)
            .assign("BAZ", None)
            .unwrap();
        let names = Field::dummies(["bar", "foo", "baz"]);

        let errors = unset_variables(&mut env, &names);
        assert_eq!(errors, []);
        assert_eq!(env.variables.get("foo"), None);
        assert_eq!(env.variables.get("bar"), None);
        assert_eq!(env.variables.get("baz"), None);
    }

    #[test]
    fn unsetting_readonly_variables() {
        let mut env = Env::new_virtual();
        let mut a = env.get_or_create_variable("a", Global);
        a.assign("A", None).unwrap();
        let mut b = env.get_or_create_variable("b", Global);
        b.assign("B", None).unwrap();
        let location_b = Location::dummy("readonly b");
        b.make_read_only(location_b.clone());
        let mut c = env.get_or_create_variable("c", Global);
        c.assign("C", None).unwrap();
        let location_c = Location::dummy("readonly c");
        c.make_read_only(location_c.clone());
        let mut d = env.get_or_create_variable("d", Global);
        d.assign("D", None).unwrap();
        let names = Field::dummies(["a", "b", "c", "d"]);

        let errors = unset_variables(&mut env, &names);
        assert_matches!(&errors[..], [e1, e2] => {
            assert_eq!(e1.name, &Field::dummy("b"));
            assert_eq!(e1.read_only_location, location_b);
            assert_eq!(e2.name, &Field::dummy("c"));
            assert_eq!(e2.read_only_location, location_c);
        });
        assert_eq!(env.variables.get("a"), None);
        assert_eq!(
            env.variables.get("b").unwrap().value,
            Some(Value::scalar("B")),
        );
        assert_eq!(
            env.variables.get("c").unwrap().value,
            Some(Value::scalar("C")),
        );
        assert_eq!(env.variables.get("d"), None);
    }

    fn dummy_function<S>(name: &str) -> Function<S> {
        let body = yash_env::test_helper::function::FunctionBodyStub::rc_dyn();
        Function::new(name, body, Location::dummy(name))
    }

    #[test]
    fn unsetting_one_function() {
        let mut env = Env::new_virtual();
        env.functions.define(dummy_function("foo")).unwrap();
        env.functions.define(dummy_function("bar")).unwrap();
        env.functions.define(dummy_function("baz")).unwrap();
        let names = Field::dummies(["foo"]);

        let errors = unset_functions(&mut env, &names);
        assert_eq!(errors, []);
        assert_eq!(env.functions.get("foo"), None);
        assert_eq!(env.functions.get("bar").unwrap().name, "bar");
        assert_eq!(env.functions.get("baz").unwrap().name, "baz");
    }

    #[test]
    fn unsetting_many_functions() {
        let mut env = Env::new_virtual();
        env.functions.define(dummy_function("foo")).unwrap();
        env.functions.define(dummy_function("bar")).unwrap();
        env.functions.define(dummy_function("baz")).unwrap();
        let names = Field::dummies(["bar", "foo", "baz"]);

        let errors = unset_functions(&mut env, &names);
        assert_eq!(errors, []);
        assert_eq!(env.functions.get("foo"), None);
        assert_eq!(env.functions.get("bar"), None);
        assert_eq!(env.functions.get("baz"), None);
    }

    #[test]
    fn unsetting_readonly_function() {
        let mut env = Env::new_virtual();
        env.functions.define(dummy_function("a")).unwrap();
        let location_b = Location::dummy("readonly b");
        env.functions
            .define(dummy_function("b").make_read_only(location_b.clone()))
            .unwrap();
        let location_c = Location::dummy("readonly c");
        env.functions
            .define(dummy_function("c").make_read_only(location_c.clone()))
            .unwrap();
        env.functions.define(dummy_function("d")).unwrap();
        let names = Field::dummies(["a", "b", "c", "d"]);

        let errors = unset_functions(&mut env, &names);
        assert_matches!(&errors[..], [e1, e2] => {
            assert_eq!(e1.name, &Field::dummy("b"));
            assert_eq!(e1.read_only_location, location_b);
            assert_eq!(e2.name, &Field::dummy("c"));
            assert_eq!(e2.read_only_location, location_c);
        });
        assert_eq!(env.functions.get("a"), None);
        assert_eq!(env.functions.get("b").unwrap().name, "b");
        assert_eq!(env.functions.get("c").unwrap().name, "c");
        assert_eq!(env.functions.get("d"), None);
    }

    // TODO unsetting_global_variable_hidden_by_local_variable: should unset the both
    // TODO unsetting_readonly_global_variable_hidden_by_local_variable: should unset the local only
}