yash_syntax/
syntax.rs

1// This file is part of yash, an extended POSIX shell.
2// Copyright (C) 2020 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//! Shell command language syntax
18//!
19//! This module contains types that represent abstract syntax trees (ASTs) of
20//! the shell language.
21//!
22//! ## Syntactic elements
23//!
24//! The AST type that represents the whole shell script is [`List`], which is a
25//! vector of [`Item`]s. An `Item` is a possibly asynchronous [`AndOrList`],
26//! which is a sequence of conditionally executed [`Pipeline`]s. A `Pipeline` is
27//! a sequence of [`Command`]s separated by `|`.
28//!
29//! There are several types of `Command`s, namely [`SimpleCommand`],
30//! [`CompoundCommand`] and [`FunctionDefinition`], where `CompoundCommand` in
31//! turn comes in many variants.
32//!
33//! ## Lexical elements
34//!
35//! Tokens that make up commands may contain quotations and expansions. A
36//! [`Word`], a sequence of [`WordUnit`]s, represents such a token that appears
37//! in a simple command and some kinds of other commands.
38//!
39//! In some contexts, tilde expansion and single- and double-quotes are not
40//! recognized while other kinds of expansions are allowed. Such part is
41//! represented as [`Text`], a sequence of [`TextUnit`]s.
42//!
43//! ## Parsing
44//!
45//! Most AST types defined in this module implement the [`FromStr`] trait, which
46//! means you can easily get an AST out of source code by calling `parse` on a
47//! `&str`. However, all [location](crate::source::Location)s in ASTs
48//! constructed this way will only have
49//! [unknown source](crate::source::Source::Unknown).
50//!
51//! ```
52//! use std::str::FromStr;
53//! # use yash_syntax::syntax::List;
54//! let list: List = "diff foo bar; echo $?".parse().unwrap();
55//! assert_eq!(list.to_string(), "diff foo bar; echo $?");
56//!
57//! use yash_syntax::source::Source;
58//! # use yash_syntax::syntax::Word;
59//! let word: Word = "foo".parse().unwrap();
60//! assert_eq!(*word.location.code.source, Source::Unknown);
61//! ```
62//!
63//! To include substantial source information in the AST, you need to prepare a
64//! [lexer](crate::parser::lex::Lexer) with source information and then use it
65//! to parse the source code. See the [`parser`](crate::parser) module for
66//! details.
67//!
68//! ## Displaying
69//!
70//! Most AST types support the [`Display`](std::fmt::Display) trait, which
71//! allows you to convert an AST to a source code string. Note that the
72//! `Display` trait implementations always produce single-line source code with
73//! here-document contents omitted. To pretty-format an AST in multiple lines
74//! with here-document contents included, you can use ... TODO TBD.
75
76use crate::parser::lex::Keyword;
77use crate::parser::lex::Operator;
78use crate::parser::lex::TryFromOperatorError;
79use crate::source::Location;
80use std::cell::OnceCell;
81#[cfg(unix)]
82use std::os::unix::io::RawFd;
83use std::rc::Rc;
84use std::str::FromStr;
85
86#[cfg(not(unix))]
87type RawFd = i32;
88
89/// Special parameter
90///
91/// This enum value identifies a special parameter in the shell language.
92/// Each special parameter is a single character that has a special meaning in
93/// the shell language. For example, `@` represents all positional parameters.
94///
95/// See [`ParamType`] for other types of parameters.
96#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
97pub enum SpecialParam {
98    /// `@` (all positional parameters)
99    At,
100    /// `*` (all positional parameters)
101    Asterisk,
102    /// `#` (number of positional parameters)
103    Number,
104    /// `?` (exit status of the last command)
105    Question,
106    /// `-` (active shell options)
107    Hyphen,
108    /// `$` (process ID of the shell)
109    Dollar,
110    /// `!` (process ID of the last asynchronous command)
111    Exclamation,
112    /// `0` (name of the shell or shell script)
113    Zero,
114}
115
116/// Type of a parameter
117///
118/// This enum distinguishes three types of [parameters](Param): named, special and
119/// positional parameters. However, this value does not include the actual
120/// parameter name as a string. The actual name is stored in a separate field in
121/// the AST node that contains this value.
122///
123/// Note the careful use of the term "name" here. In POSIX terminology, a
124/// "name" identifies a named parameter (that is, a variable) and does not
125/// include special or positional parameters. An identifier that refers to any
126/// kind of parameter is called a "parameter".
127#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
128pub enum ParamType {
129    /// Named parameter
130    Variable,
131    /// Special parameter
132    Special(SpecialParam),
133    /// Positional parameter
134    ///
135    /// Positional parameters are indexed starting from 1, so the index of `0`
136    /// always refers to a non-existent parameter. If the string form of a
137    /// positional parameter represents an index that is too large to fit in a
138    /// `usize`, the index should be `usize::MAX`, which is also guaranteed to
139    /// spot a non-existent parameter since a `Vec` cannot have more than
140    /// `isize::MAX` elements.
141    Positional(usize),
142}
143
144/// Parameter
145///
146/// A parameter is an identifier that appears in a parameter expansion
147/// ([`TextUnit::RawParam`] and [`BracedParam`]). There are three
148/// [types](ParamType) of parameters depending on the character category of the
149/// identifier.
150#[derive(Clone, Debug, Eq, Hash, PartialEq)]
151pub struct Param {
152    /// Literal representation of the parameter name
153    ///
154    /// This is the raw string form of the parameter as it appears in the source
155    /// code. Examples include `foo`, `@`, `#`, `0`, and `12`.
156    pub id: String,
157
158    /// Type of the parameter
159    ///
160    /// This precomputed value is used to optimize the evaluation of parameter
161    /// expansions by avoiding the need to parse the `id` field every time.
162    ///
163    /// It is your responsibility to ensure that the `type` field is consistent
164    /// with the `id` field. For example, if the `id` field is `"@"`, the `type`
165    /// field must be `Special(At)`. The [parser](crate::parser) ensures this
166    /// invariant when it constructs a `Param` value.
167    pub r#type: ParamType,
168}
169
170// TODO Consider implementing FromStr for Param
171
172/// Flag that specifies how the value is substituted in a [switch](Switch)
173#[derive(Clone, Copy, Debug, Eq, PartialEq)]
174pub enum SwitchType {
175    /// Alter an existing value, if any. (`+`)
176    Alter,
177    /// Substitute a missing value with a default. (`-`)
178    Default,
179    /// Assign a default to the variable if the value is missing. (`=`)
180    Assign,
181    /// Error out if the value is missing. (`?`)
182    Error,
183}
184
185/// Condition that triggers a [switch](Switch)
186///
187/// In the lexical grammar of the shell language, a switch condition is an
188/// optional colon that precedes a switch type.
189#[derive(Clone, Copy, Debug, Eq, PartialEq)]
190pub enum SwitchCondition {
191    /// Without a colon, the switch is triggered if the parameter is unset.
192    Unset,
193    /// With a colon, the switch is triggered if the parameter is unset or
194    /// empty.
195    UnsetOrEmpty,
196}
197
198/// Parameter expansion [modifier](Modifier) that conditionally substitutes the
199/// value being expanded
200///
201/// Examples of switches include `+foo`, `:-bar` and `:=baz`.
202///
203/// A switch is composed of a [condition](SwitchCondition) (an optional `:`), a
204/// [type](SwitchType) (one of `+`, `-`, `=` and `?`) and a [word](Word).
205#[derive(Clone, Debug, Eq, PartialEq)]
206pub struct Switch {
207    /// How the value is substituted
208    pub r#type: SwitchType,
209    /// Condition that determines whether the value is substituted or not
210    pub condition: SwitchCondition,
211    /// Word that substitutes the parameter value
212    pub word: Word,
213}
214
215/// Flag that specifies which side of the expanded value is removed in a
216/// [trim](Trim)
217#[derive(Clone, Copy, Debug, Eq, PartialEq)]
218pub enum TrimSide {
219    /// Beginning of the value
220    Prefix,
221    /// End of the value
222    Suffix,
223}
224
225/// Flag that specifies pattern matching strategy in a [trim](Trim)
226#[derive(Clone, Copy, Debug, Eq, PartialEq)]
227pub enum TrimLength {
228    /// Match as small number of characters as possible.
229    Shortest,
230    /// Match as large number of characters as possible.
231    Longest,
232}
233
234/// Parameter expansion [modifier](Modifier) that removes the beginning or end
235/// of the value being expanded
236///
237/// Examples of trims include `#foo`, `##bar` and `%%baz*`.
238///
239/// A trim is composed of a side, length and pattern.
240#[derive(Clone, Debug, Eq, PartialEq)]
241pub struct Trim {
242    /// Which side of the value should be removed?
243    pub side: TrimSide,
244    /// How long the pattern should match?
245    pub length: TrimLength,
246    /// Pattern to be matched with the expanded value.
247    pub pattern: Word,
248}
249
250/// Attribute that modifies a parameter expansion
251#[derive(Clone, Debug, Eq, PartialEq)]
252pub enum Modifier {
253    /// No modifier
254    None,
255    /// `#` prefix (`${#foo}`)
256    Length,
257    /// `+`, `-`, `=` or `?` suffix, optionally with `:` (`${foo:-bar}`)
258    Switch(Switch),
259    /// `#`, `##`, `%` or `%%` suffix
260    Trim(Trim),
261    // TODO Subst
262}
263
264/// Parameter expansion enclosed in braces
265///
266/// This struct is used only for parameter expansions that are enclosed braces.
267/// Expansions that are not enclosed in braces are directly encoded with
268/// [`TextUnit::RawParam`].
269#[derive(Clone, Debug, Eq, PartialEq)]
270pub struct BracedParam {
271    // TODO recursive expansion
272    /// Parameter to be expanded
273    pub param: Param,
274    // TODO index
275    /// Modifier
276    pub modifier: Modifier,
277    /// Position of this parameter expansion in the source code
278    pub location: Location,
279}
280
281/// Element of [`TextUnit::Backquote`]
282#[derive(Clone, Copy, Debug, Eq, PartialEq)]
283pub enum BackquoteUnit {
284    /// Literal single character
285    Literal(char),
286    /// Backslash-escaped single character
287    Backslashed(char),
288}
289
290/// Element of a [Text], i.e., something that can be expanded
291#[derive(Clone, Debug, Eq, PartialEq)]
292pub enum TextUnit {
293    /// Literal single character
294    Literal(char),
295    /// Backslash-escaped single character
296    Backslashed(char),
297    /// Parameter expansion that is not enclosed in braces
298    RawParam {
299        /// Parameter to be expanded
300        param: Param,
301        /// Position of this parameter expansion in the source code
302        location: Location,
303    },
304    /// Parameter expansion that is enclosed in braces
305    BracedParam(BracedParam),
306    /// Command substitution of the form `$(...)`
307    CommandSubst {
308        /// Command string that will be parsed and executed when the command
309        /// substitution is expanded
310        ///
311        /// This value is reference-counted so that the shell does not have to
312        /// clone the entire string when it is passed to a subshell to execute
313        /// the command substitution.
314        content: Rc<str>,
315        /// Position of this command substitution in the source code
316        location: Location,
317    },
318    /// Command substitution of the form `` `...` ``
319    Backquote {
320        /// Command string that will be parsed and executed when the command
321        /// substitution is expanded
322        content: Vec<BackquoteUnit>,
323        /// Position of this command substitution in the source code
324        location: Location,
325    },
326    /// Arithmetic expansion
327    Arith {
328        /// Expression that is to be evaluated
329        content: Text,
330        /// Position of this arithmetic expansion in the source code
331        location: Location,
332    },
333}
334
335pub use TextUnit::*;
336
337/// String that may contain some expansions
338///
339/// A text is a sequence of [text unit](TextUnit)s, which may contain some kinds
340/// of expansions.
341#[derive(Clone, Debug, Default, Eq, PartialEq)]
342pub struct Text(pub Vec<TextUnit>);
343
344/// Element of an [`EscapedString`].
345#[derive(Clone, Debug, Eq, PartialEq)]
346pub enum EscapeUnit {
347    /// Literal single character
348    Literal(char),
349    /// Backslash-escaped double-quote character (`\"`)
350    DoubleQuote,
351    /// Backslash-escaped single-quote character (`\'`)
352    SingleQuote,
353    /// Backslash-escaped backslash character (`\\`)
354    Backslash,
355    /// Backslash-escaped question mark character (`\?`)
356    Question,
357    /// Backslash notation for the bell character (`\a`, ASCII 7)
358    Alert,
359    /// Backslash notation for the backspace character (`\b`, ASCII 8)
360    Backspace,
361    /// Backslash notation for the escape character (`\e`, ASCII 27)
362    Escape,
363    /// Backslash notation for the form feed character (`\f`, ASCII 12)
364    FormFeed,
365    /// Backslash notation for the newline character (`\n`, ASCII 10)
366    Newline,
367    /// Backslash notation for the carriage return character (`\r`, ASCII 13)
368    CarriageReturn,
369    /// Backslash notation for the horizontal tab character (`\t`, ASCII 9)
370    Tab,
371    /// Backslash notation for the vertical tab character (`\v`, ASCII 11)
372    VerticalTab,
373    /// Control character notation (`\c...`)
374    ///
375    /// The associated value is the control character represented by the
376    /// following character in the input.
377    Control(u8),
378    /// Single-byte octal notation (`\OOO`)
379    ///
380    /// The associated value is the byte represented by the three octal digits
381    /// following the backslash.
382    Octal(u8),
383    /// Single-byte hexadecimal notation (`\xHH`)
384    ///
385    /// The associated value is the byte represented by the two hexadecimal
386    /// digits following the `x`.
387    Hex(u8),
388    /// Unicode notation (`\uHHHH` or `\UHHHHHHHH`)
389    ///
390    /// The associated value is the Unicode scalar value represented by the four
391    /// or eight hexadecimal digits following the `u` or `U`.
392    Unicode(char),
393}
394
395/// String that may contain some escapes
396///
397/// An escaped string is a sequence of [escape unit](EscapeUnit)s, which may
398/// contain some kinds of escapes. This type is used for the value of a
399/// [dollar-single-quoted string](WordUnit::DollarSingleQuote).
400#[derive(Clone, Debug, Default, Eq, PartialEq)]
401pub struct EscapedString(pub Vec<EscapeUnit>);
402
403/// Element of a [Word], i.e., text with quotes and tilde expansion
404#[derive(Clone, Debug, Eq, PartialEq)]
405pub enum WordUnit {
406    /// Unquoted [`TextUnit`] as a word unit
407    Unquoted(TextUnit),
408    /// String surrounded with a pair of single quotations
409    SingleQuote(String),
410    /// Text surrounded with a pair of double quotations
411    DoubleQuote(Text),
412    /// String surrounded with a pair of single quotations and preceded by a dollar sign
413    DollarSingleQuote(EscapedString),
414    /// Tilde expansion
415    ///
416    /// The `String` value does not contain the initial tilde.
417    Tilde(String),
418}
419
420pub use WordUnit::*;
421
422/// Token that may involve expansions and quotes
423///
424/// A word is a sequence of [word unit](WordUnit)s. It depends on context whether
425/// an empty word is valid or not. It is your responsibility to ensure a word is
426/// non-empty in a context where it cannot.
427///
428/// The difference between words and [text](Text)s is that only words can contain
429/// single- and double-quotes and tilde expansions. Compare [`WordUnit`] and [`TextUnit`].
430#[derive(Clone, Debug, Eq, PartialEq)]
431pub struct Word {
432    /// Word units that constitute the word
433    pub units: Vec<WordUnit>,
434    /// Position of the word in the source code
435    pub location: Location,
436}
437
438/// Value of an [assignment](Assign)
439#[derive(Clone, Debug, Eq, PartialEq)]
440pub enum Value {
441    /// Scalar value, a possibly empty word
442    ///
443    /// Note: Because a scalar assignment value is created from a normal command
444    /// word, the location of the word in the scalar value refers to the entire
445    /// assignment word rather than the assigned value.
446    Scalar(Word),
447
448    /// Array, possibly empty list of non-empty words
449    ///
450    /// Array assignment is a POSIXly non-portable extension.
451    Array(Vec<Word>),
452}
453
454pub use Value::*;
455
456/// Assignment word
457#[derive(Clone, Debug, Eq, PartialEq)]
458pub struct Assign {
459    /// Name of the variable to assign to
460    ///
461    /// In the valid assignment syntax, the name must not be empty.
462    pub name: String,
463    /// Value assigned to the variable
464    pub value: Value,
465    /// Location of the assignment word
466    pub location: Location,
467}
468
469/// File descriptor
470///
471/// This is the `newtype` pattern applied to [`RawFd`], which is merely a type
472/// alias.
473#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
474pub struct Fd(pub RawFd);
475
476impl Fd {
477    /// File descriptor for the standard input
478    pub const STDIN: Fd = Fd(0);
479    /// File descriptor for the standard output
480    pub const STDOUT: Fd = Fd(1);
481    /// File descriptor for the standard error
482    pub const STDERR: Fd = Fd(2);
483}
484
485/// Redirection operators
486///
487/// This enum defines the redirection operator types except here-document and
488/// process redirection.
489#[derive(Clone, Copy, Debug, Eq, PartialEq)]
490pub enum RedirOp {
491    /// `<` (open a file for input)
492    FileIn,
493    /// `<>` (open a file for input and output)
494    FileInOut,
495    /// `>` (open a file for output; truncate or fail if existing)
496    FileOut,
497    /// `>>` (open a file for output; append if existing)
498    FileAppend,
499    /// `>|` (open a file for output; always truncate if existing)
500    FileClobber,
501    /// `<&` (copy or close a file descriptor for input)
502    FdIn,
503    /// `>&` (copy or close a file descriptor for output)
504    FdOut,
505    /// `>>|` (open a pipe, one end for input and the other output)
506    Pipe,
507    /// `<<<` (here-string)
508    String,
509}
510
511/// Here-document
512#[derive(Clone, Debug, Eq, PartialEq)]
513pub struct HereDoc {
514    /// Token that marks the end of the content of the here-document
515    pub delimiter: Word,
516
517    /// Whether leading tab characters should be removed from each line of the
518    /// here-document content
519    ///
520    /// This value is `true` for the `<<-` operator and `false` for `<<`.
521    pub remove_tabs: bool,
522
523    /// Content of the here-document
524    ///
525    /// The content ends with a newline unless it is empty. If the delimiter is
526    /// quoted, the content must be all literal. If `remove_tabs` is `true`,
527    /// each content line does not start with tabs as they are removed when
528    /// parsed.
529    ///
530    /// This value is wrapped in `OnceCell` because the here-doc content is
531    /// parsed separately from the here-doc operator. When the operator is
532    /// parsed, the `HereDoc` instance is created with an empty content. The
533    /// content is filled to the cell when it is parsed later. When accessing
534    /// the parsed content, you can safely unwrap the cell.
535    pub content: OnceCell<Text>,
536}
537
538/// Part of a redirection that defines the nature of the resulting file descriptor
539#[derive(Clone, Debug, Eq, PartialEq)]
540pub enum RedirBody {
541    /// Normal redirection
542    Normal { operator: RedirOp, operand: Word },
543    /// Here-document
544    HereDoc(Rc<HereDoc>),
545    // TODO process redirection
546}
547
548impl RedirBody {
549    /// Returns the operand word of the redirection.
550    pub fn operand(&self) -> &Word {
551        match self {
552            RedirBody::Normal { operand, .. } => operand,
553            RedirBody::HereDoc(here_doc) => &here_doc.delimiter,
554        }
555    }
556}
557
558/// Redirection
559#[derive(Clone, Debug, Eq, PartialEq)]
560pub struct Redir {
561    /// File descriptor that is modified by this redirection
562    pub fd: Option<Fd>,
563    /// Nature of the resulting file descriptor
564    pub body: RedirBody,
565}
566
567impl Redir {
568    /// Computes the file descriptor that is modified by this redirection.
569    ///
570    /// If `self.fd` is `Some(_)`, the `RawFd` value is returned intact. Otherwise,
571    /// the default file descriptor is selected depending on the type of `self.body`.
572    pub fn fd_or_default(&self) -> Fd {
573        use RedirOp::*;
574        self.fd.unwrap_or(match self.body {
575            RedirBody::Normal { operator, .. } => match operator {
576                FileIn | FileInOut | FdIn | String => Fd::STDIN,
577                FileOut | FileAppend | FileClobber | FdOut | Pipe => Fd::STDOUT,
578            },
579            RedirBody::HereDoc { .. } => Fd::STDIN,
580        })
581    }
582}
583
584/// Command that involves assignments, redirections, and word expansions
585///
586/// In the shell language syntax, a valid simple command must contain at least one of assignments,
587/// redirections, and words. The parser must not produce a completely empty simple command.
588#[derive(Clone, Debug, Eq, PartialEq)]
589pub struct SimpleCommand {
590    pub assigns: Vec<Assign>,
591    pub words: Vec<Word>,
592    pub redirs: Rc<Vec<Redir>>,
593}
594
595impl SimpleCommand {
596    /// Returns true if the simple command does not contain any assignments,
597    /// words, or redirections.
598    pub fn is_empty(&self) -> bool {
599        self.assigns.is_empty() && self.words.is_empty() && self.redirs.is_empty()
600    }
601
602    /// Returns true if the simple command contains only one word.
603    pub fn is_one_word(&self) -> bool {
604        self.assigns.is_empty() && self.words.len() == 1 && self.redirs.is_empty()
605    }
606
607    /// Tests whether the first word of the simple command is a keyword.
608    #[must_use]
609    fn first_word_is_keyword(&self) -> bool {
610        let Some(word) = self.words.first() else {
611            return false;
612        };
613        let Some(literal) = word.to_string_if_literal() else {
614            return false;
615        };
616        literal.parse::<Keyword>().is_ok()
617    }
618}
619
620/// `elif-then` clause
621#[derive(Clone, Debug, Eq, PartialEq)]
622pub struct ElifThen {
623    pub condition: List,
624    pub body: List,
625}
626
627/// Symbol that terminates the body of a case branch and determines what to do
628/// after executing it
629#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
630pub enum CaseContinuation {
631    /// `;;` (terminate the case construct)
632    #[default]
633    Break,
634    /// `;&` (unconditionally execute the body of the next case branch)
635    FallThrough,
636    /// `;|` or `;;&` (resume with the next case branch, performing pattern matching again)
637    Continue,
638}
639
640/// Branch item of a `case` compound command
641#[derive(Clone, Debug, Eq, PartialEq)]
642pub struct CaseItem {
643    /// Array of patterns that are matched against the main word of the case
644    /// compound command to decide if the body of this item should be executed
645    ///
646    /// A syntactically valid case item must have at least one pattern.
647    pub patterns: Vec<Word>,
648    /// Commands that are executed if any of the patterns matched
649    pub body: List,
650    /// What to do after executing the body of this item
651    pub continuation: CaseContinuation,
652}
653
654/// Command that contains other commands
655#[derive(Clone, Debug, Eq, PartialEq)]
656pub enum CompoundCommand {
657    /// List as a command
658    Grouping(List),
659    /// Command for executing commands in a subshell
660    Subshell { body: Rc<List>, location: Location },
661    /// For loop
662    For {
663        name: Word,
664        values: Option<Vec<Word>>,
665        body: List,
666    },
667    /// While loop
668    While { condition: List, body: List },
669    /// Until loop
670    Until { condition: List, body: List },
671    /// If conditional construct
672    If {
673        condition: List,
674        body: List,
675        elifs: Vec<ElifThen>,
676        r#else: Option<List>,
677    },
678    /// Case conditional construct
679    Case { subject: Word, items: Vec<CaseItem> },
680    // TODO [[ ]]
681}
682
683/// Compound command with redirections
684#[derive(Clone, Debug, Eq, PartialEq)]
685pub struct FullCompoundCommand {
686    /// The main part
687    pub command: CompoundCommand,
688    /// Redirections
689    pub redirs: Vec<Redir>,
690}
691
692/// Function definition command
693#[derive(Clone, Debug, Eq, PartialEq)]
694pub struct FunctionDefinition {
695    /// Whether the function definition command starts with the `function` reserved word
696    pub has_keyword: bool,
697    /// Function name
698    pub name: Word,
699    /// Function body
700    pub body: Rc<FullCompoundCommand>,
701}
702
703/// Element of a pipe sequence
704#[derive(Clone, Debug, Eq, PartialEq)]
705pub enum Command {
706    /// Simple command
707    Simple(SimpleCommand),
708    /// Compound command
709    Compound(FullCompoundCommand),
710    /// Function definition command
711    Function(FunctionDefinition),
712}
713
714/// Commands separated by `|`
715#[derive(Clone, Debug, Eq, PartialEq)]
716pub struct Pipeline {
717    /// Elements of the pipeline
718    ///
719    /// A valid pipeline must have at least one command.
720    ///
721    /// The commands are contained in `Rc` to allow executing them
722    /// asynchronously without cloning them.
723    pub commands: Vec<Rc<Command>>,
724    /// Whether the pipeline begins with a `!`
725    pub negation: bool,
726}
727
728/// Condition that decides if a [Pipeline] in an [and-or list](AndOrList) should be executed
729#[derive(Clone, Copy, Debug, Eq, PartialEq)]
730pub enum AndOr {
731    /// `&&`
732    AndThen,
733    /// `||`
734    OrElse,
735}
736
737/// Pipelines separated by `&&` and `||`
738#[derive(Clone, Debug, Eq, PartialEq)]
739pub struct AndOrList {
740    pub first: Pipeline,
741    pub rest: Vec<(AndOr, Pipeline)>,
742}
743
744/// Element of a [List]
745#[derive(Clone, Debug, Eq, PartialEq)]
746pub struct Item {
747    /// Main part of this item
748    ///
749    /// The and-or list is contained in `Rc` to allow executing it
750    /// asynchronously without cloning it.
751    pub and_or: Rc<AndOrList>,
752    /// Location of the `&` operator for this item, if any
753    pub async_flag: Option<Location>,
754}
755
756/// Sequence of [and-or lists](AndOrList) separated by `;` or `&`
757///
758/// It depends on context whether an empty list is a valid syntax.
759#[derive(Clone, Debug, Eq, PartialEq)]
760pub struct List(pub Vec<Item>);
761
762/// Definitions and implementations of the [Unquote] and [MaybeLiteral] traits,
763/// and other conversions between types
764mod conversions;
765/// Implementations of [std::fmt::Display] for the shell language syntax types
766mod impl_display;
767
768pub use conversions::{MaybeLiteral, NotLiteral, NotSpecialParam, Unquote};