yash_arith/env.rs
1// This file is part of yash, an extended POSIX shell.
2// Copyright (C) 2022 WATANABE Yuki
3//
4// This program is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// This program is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13//
14// You should have received a copy of the GNU General Public License
15// along with this program. If not, see <https://www.gnu.org/licenses/>.
16
17//! Variable environment
18
19use std::collections::{BTreeMap, HashMap};
20use std::convert::Infallible;
21use std::ops::Range;
22
23/// Interface for accessing variables during evaluation
24///
25/// This crate does not implement any mechanism for storing variables. The
26/// caller of [`eval`](crate::eval()) must provide an implementation of this
27/// trait, which is used to access variables that appear in the evaluated
28/// expression.
29pub trait Env {
30 /// Object returned on a variable access error
31 type GetVariableError;
32
33 /// Object returned on an assignment error
34 type AssignVariableError;
35
36 /// Returns the value of the specified variable.
37 ///
38 /// This function must return:
39 ///
40 /// - `Ok(Some(v))` if the variable is defined and has the value `v`,
41 /// - `Ok(None)` if the variable is not defined, or
42 /// - `Err(error)` if an error occurs.
43 fn get_variable(&self, name: &str) -> Result<Option<&str>, Self::GetVariableError>;
44
45 /// Assigns a new value to the specified variable.
46 ///
47 /// The `location` parameter is the index range to the evaluated expression
48 /// where the assignment appears.
49 fn assign_variable(
50 &mut self,
51 name: &str,
52 value: String,
53 location: Range<usize>,
54 ) -> Result<(), Self::AssignVariableError>;
55}
56
57impl Env for HashMap<String, String> {
58 type GetVariableError = Infallible;
59 type AssignVariableError = Infallible;
60
61 fn get_variable(&self, name: &str) -> Result<Option<&str>, Infallible> {
62 Ok(self.get(name).map(String::as_str))
63 }
64
65 fn assign_variable(
66 &mut self,
67 name: &str,
68 value: String,
69 _location: Range<usize>,
70 ) -> Result<(), Infallible> {
71 self.insert(name.to_owned(), value);
72 Ok(())
73 }
74}
75
76impl Env for BTreeMap<String, String> {
77 type GetVariableError = Infallible;
78 type AssignVariableError = Infallible;
79
80 fn get_variable(&self, name: &str) -> Result<Option<&str>, Infallible> {
81 Ok(self.get(name).map(String::as_str))
82 }
83
84 fn assign_variable(
85 &mut self,
86 name: &str,
87 value: String,
88 _location: Range<usize>,
89 ) -> Result<(), Infallible> {
90 self.insert(name.to_owned(), value);
91 Ok(())
92 }
93}