/ compiler / ast / src / expressions / cast.rs
cast.rs
 1  // Copyright (C) 2019-2025 ADnet Contributors
 2  // This file is part of the ADL library.
 3  
 4  // The ADL library 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  // The ADL library 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 the ADL library. If not, see <https://www.gnu.org/licenses/>.
16  
17  use super::*;
18  
19  use crate::Type;
20  
21  /// A cast expression, e.g. `42u8 as u16`.
22  #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
23  pub struct CastExpression {
24      /// The expression to be casted, e.g.`42u8` in `42u8 as u16`.
25      pub expression: Expression,
26      /// The type to be casted to, e.g. `u16` in `42u8 as u16`.
27      pub type_: Type,
28      /// Span of the entire cast `42u8 as u16`.
29      pub span: Span,
30      /// The ID of the node.
31      pub id: NodeID,
32  }
33  
34  impl fmt::Display for CastExpression {
35      fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
36          if self.expression.precedence() < 12 {
37              write!(f, "({})", self.expression)?;
38          } else {
39              write!(f, "{}", self.expression)?;
40          }
41          write!(f, " as {}", self.type_)
42      }
43  }
44  
45  impl From<CastExpression> for Expression {
46      fn from(value: CastExpression) -> Self {
47          Expression::Cast(Box::new(value))
48      }
49  }
50  
51  crate::simple_node_impl!(CastExpression);