yash_env/
builtin.rs

1// This file is part of yash, an extended POSIX shell.
2// Copyright (C) 2021 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//! Type definitions for built-in utilities
18//!
19//! This module provides data types for defining built-in utilities.
20//!
21//! Note that concrete implementations of built-ins are not included in the
22//! `yash_env` crate. For implementations of specific built-ins like `cd` and
23//! `export`, see the `yash_builtin` crate.
24
25use crate::Env;
26#[cfg(doc)]
27use crate::semantics::Divert;
28use crate::semantics::ExitStatus;
29use crate::semantics::Field;
30use std::fmt::Debug;
31use std::pin::Pin;
32
33/// Types of built-in utilities
34#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
35pub enum Type {
36    /// Special built-in
37    ///
38    /// Special built-in utilities are built-ins that are defined in [POSIX XCU
39    /// section 2.15](https://pubs.opengroup.org/onlinepubs/9799919799/utilities/V3_chap02.html#tag_19_15).
40    ///
41    /// They are treated differently from other built-ins.
42    /// Especially, special built-ins are found in the first stage of command
43    /// search without the `$PATH` search and cannot be overridden by functions
44    /// or external utilities.
45    /// Many errors in special built-ins force the shell to exit.
46    Special,
47
48    /// Standard utility that can be used without `$PATH` search
49    ///
50    /// Mandatory built-ins are utilities that are listed in [POSIX XCU section
51    /// 1.7](https://pubs.opengroup.org/onlinepubs/9799919799/utilities/V3_chap01.html#tag_18_07).
52    /// In POSIX, they are called "intrinsic utilities".
53    ///
54    /// Like special built-ins, mandatory built-ins are not subject to `$PATH`
55    /// in command search; They are always found regardless of whether there is
56    /// a corresponding external utility in `$PATH`. However, mandatory
57    /// built-ins can still be overridden by functions.
58    ///
59    /// We call them "mandatory" because POSIX effectively requires them to be
60    /// built into the shell.
61    Mandatory,
62
63    /// Non-portable built-in that can be used without `$PATH` search
64    ///
65    /// Elective built-ins are built-ins that are listed in step 1b of [Command
66    /// Search and Execution](https://pubs.opengroup.org/onlinepubs/9799919799/utilities/V3_chap02.html#tag_19_09_01_04)
67    /// in POSIX XCU section 2.9.1.4.
68    /// They are very similar to mandatory built-ins, but their behavior is not
69    /// specified by POSIX, so they are not portable. They cannot be used when
70    /// the (TODO TBD) option is set. <!-- An option that disables non-portable
71    /// behavior would make elective built-ins unusable even if found. An option
72    /// that disables non-conforming behavior would not affect elective
73    /// built-ins. -->
74    ///
75    /// We call them "elective" because it is up to the shell whether to
76    /// implement them.
77    Elective,
78
79    /// Non-conforming extension
80    ///
81    /// Extension built-ins are non-conformant extensions to the POSIX shell.
82    /// Like elective built-ins, they can be executed without `$PATH` search
83    /// finding a corresponding external utility. However, since this behavior
84    /// does not conform to [Command
85    /// Search and Execution](https://pubs.opengroup.org/onlinepubs/9799919799/utilities/V3_chap02.html#tag_19_09_01_04)
86    /// in POSIX XCU section 2.9.1.4, they cannot be used when the (TODO TBD)
87    /// option is set. <!-- An option that disables non-conforming behavior
88    /// would make extension built-ins regarded as non-existing utilities. An
89    /// option that disables non-portable behavior would make extension
90    /// built-ins unusable even if found. -->
91    Extension,
92
93    /// Built-in that works like a standalone utility
94    ///
95    /// A substitutive built-in is a built-in that is executed instead of an
96    /// external utility to minimize invocation overhead. Since a substitutive
97    /// built-in behaves just as if it were an external utility, it must be
98    /// found in `$PATH` in order to be executed.
99    Substitutive,
100}
101
102/// Result of built-in utility execution
103///
104/// The result type contains an exit status and optional flags that may affect
105/// the behavior of the shell following the built-in execution.
106#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
107#[must_use]
108pub struct Result {
109    exit_status: ExitStatus,
110    divert: crate::semantics::Result,
111    should_retain_redirs: bool,
112}
113
114impl Result {
115    /// Creates a new result.
116    pub const fn new(exit_status: ExitStatus) -> Self {
117        Self {
118            exit_status,
119            divert: crate::semantics::Result::Continue(()),
120            should_retain_redirs: false,
121        }
122    }
123
124    /// Creates a new result with a [`Divert`].
125    #[inline]
126    pub const fn with_exit_status_and_divert(
127        exit_status: ExitStatus,
128        divert: crate::semantics::Result,
129    ) -> Self {
130        Self {
131            exit_status,
132            divert,
133            should_retain_redirs: false,
134        }
135    }
136
137    /// Returns the exit status of this result.
138    ///
139    /// The return value is the argument to the previous invocation of
140    /// [`new`](Self::new) or [`set_exit_status`](Self::set_exit_status).
141    #[inline]
142    #[must_use]
143    pub const fn exit_status(&self) -> ExitStatus {
144        self.exit_status
145    }
146
147    /// Sets the exit status of this result.
148    ///
149    /// See [`exit_status`](Self::exit_status()).
150    #[inline]
151    pub fn set_exit_status(&mut self, exit_status: ExitStatus) {
152        self.exit_status = exit_status
153    }
154
155    /// Returns an optional [`Divert`] to be taken.
156    ///
157    /// The return value is the argument to the previous invocation of
158    /// [`set_divert`](Self::set_divert). The default is `Continue(())`.
159    #[inline]
160    #[must_use]
161    pub const fn divert(&self) -> crate::semantics::Result {
162        self.divert
163    }
164
165    /// Sets a [`Divert`].
166    ///
167    /// See [`divert`](Self::divert()).
168    #[inline]
169    pub fn set_divert(&mut self, divert: crate::semantics::Result) {
170        self.divert = divert;
171    }
172
173    /// Tests whether the caller should retain redirections.
174    ///
175    /// Usually, the shell reverts redirections applied to a built-in after
176    /// executing it. However, redirections applied to a successful `exec`
177    /// built-in should persist. To make it happen, the `exec` built-in calls
178    /// [`retain_redirs`](Self::retain_redirs), and this function returns true.
179    /// In that case, the caller of the built-in should take appropriate actions
180    /// to preserve the effect of the redirections.
181    #[inline]
182    pub const fn should_retain_redirs(&self) -> bool {
183        self.should_retain_redirs
184    }
185
186    /// Flags that redirections applied to the built-in should persist.
187    ///
188    /// Calling this function makes
189    /// [`should_retain_redirs`](Self::should_retain_redirs) return true.
190    /// [`clear_redirs`](Self::clear_redirs) cancels the effect of this
191    /// function.
192    #[inline]
193    pub fn retain_redirs(&mut self) {
194        self.should_retain_redirs = true;
195    }
196
197    /// Cancels the effect of [`retain_redirs`](Self::retain_redirs).
198    #[inline]
199    pub fn clear_redirs(&mut self) {
200        self.should_retain_redirs = false;
201    }
202
203    /// Merges two results by taking the maximum of each field.
204    pub fn max(self, other: Self) -> Self {
205        use std::ops::ControlFlow::{Break, Continue};
206        let divert = match (self.divert, other.divert) {
207            (Continue(()), other) => other,
208            (other, Continue(())) => other,
209            (Break(left), Break(right)) => Break(left.max(right)),
210        };
211
212        Self {
213            exit_status: self.exit_status.max(other.exit_status),
214            divert,
215            should_retain_redirs: self.should_retain_redirs.max(other.should_retain_redirs),
216        }
217    }
218}
219
220impl Default for Result {
221    #[inline]
222    fn default() -> Self {
223        Self::new(ExitStatus::default())
224    }
225}
226
227impl From<ExitStatus> for Result {
228    #[inline]
229    fn from(exit_status: ExitStatus) -> Self {
230        Self::new(exit_status)
231    }
232}
233
234/// Type of functions that implement the behavior of a built-in
235///
236/// The function takes two arguments.
237/// The first is an environment in which the built-in is executed.
238/// The second is arguments to the built-in
239/// (not including the leading command name word).
240pub type Main = fn(&mut Env, Vec<Field>) -> Pin<Box<dyn Future<Output = Result> + '_>>;
241
242/// Built-in utility definition
243#[derive(Clone, Copy, Eq, Hash, PartialEq)]
244#[non_exhaustive]
245pub struct Builtin {
246    /// Type of the built-in
247    pub r#type: Type,
248
249    /// Function that implements the behavior of the built-in
250    pub execute: Main,
251
252    /// Whether the built-in is a declaration utility
253    ///
254    /// The [`yash_syntax::decl_util::Glossary`] implementation for [`Env`] uses
255    /// this field to determine whether a command name is a declaration utility.
256    /// See the [method description] for the value this field should have.
257    ///
258    /// [method description]: yash_syntax::decl_util::Glossary::is_declaration_utility
259    pub is_declaration_utility: Option<bool>,
260}
261
262impl Debug for Builtin {
263    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
264        f.debug_struct("Builtin")
265            .field("type", &self.r#type)
266            .field("is_declaration_utility", &self.is_declaration_utility)
267            .finish_non_exhaustive()
268    }
269}
270
271impl Builtin {
272    /// Creates a new built-in utility definition.
273    ///
274    /// The `type` and `execute` fields are set to the given arguments.
275    /// The `is_declaration_utility` field is set to `Some(false)`, indicating
276    /// that the built-in is not a declaration utility.
277    pub const fn new(r#type: Type, execute: Main) -> Self {
278        Self {
279            r#type,
280            execute,
281            is_declaration_utility: Some(false),
282        }
283    }
284}