Skip to main content

leo_ast/expressions/
composite_init.rs

1// Copyright (C) 2019-2026 Provable Inc.
2// This file is part of the Leo library.
3
4// The Leo 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 Leo 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 Leo library. If not, see <https://www.gnu.org/licenses/>.
16
17use super::*;
18use crate::Identifier;
19
20use itertools::Itertools as _;
21
22/// An initializer for a single field / variable of a composite initializer expression.
23/// That is, in `Foo { bar: 42, baz }`, this is either `bar: 42`, or `baz`.
24#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
25pub struct CompositeFieldInitializer {
26    /// The name of the field / variable to be initialized.
27    pub identifier: Identifier,
28    /// The expression to initialize the field with.
29    /// When `None`, a binding, in scope, with the name will be used instead.
30    pub expression: Option<Expression>,
31    /// The span of the node.
32    pub span: Span,
33    /// The ID of the node.
34    pub id: NodeID,
35}
36
37crate::simple_node_impl!(CompositeFieldInitializer);
38
39impl fmt::Display for CompositeFieldInitializer {
40    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
41        if let Some(expr) = &self.expression {
42            write!(f, "{}: {expr}", self.identifier)
43        } else {
44            write!(f, "{}", self.identifier)
45        }
46    }
47}
48
49/// A composite initialization expression, e.g., `Foo { bar: 42, baz }`.
50#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
51pub struct CompositeExpression {
52    /// A path to a composite type to initialize.
53    pub path: Path,
54    /// Expressions for the const arguments passed to the composite's const parameters.
55    pub const_arguments: Vec<Expression>,
56    /// Initializer expressions for each of the fields in the composite.
57    ///
58    /// N.B. Any functions or member constants in the composite definition
59    /// are excluded from this list.
60    pub members: Vec<CompositeFieldInitializer>,
61    /// The base expression of a struct update, e.g. `other` in `Foo { bar: 42, ..other }`.
62    ///
63    /// When `Some`, any field of the composite not present in `members` is copied from `base`.
64    /// This is lowered away during static single assignment, so later passes always see `None`.
65    pub base: Option<Box<Expression>>,
66    /// A span from `name` to `}`.
67    pub span: Span,
68    /// The ID of the node.
69    pub id: NodeID,
70}
71
72impl fmt::Display for CompositeExpression {
73    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
74        write!(f, "{}", self.path)?;
75        if !self.const_arguments.is_empty() {
76            write!(f, "::[{}]", self.const_arguments.iter().format(", "))?;
77        }
78        write!(f, " {{")?;
79
80        if !self.members.is_empty() {
81            write!(f, " ")?;
82        }
83        write!(f, "{}", self.members.iter().format(", "))?;
84        if let Some(base) = &self.base {
85            let separator = if self.members.is_empty() { " " } else { ", " };
86            write!(f, "{separator}..{base} ")?;
87        } else if !self.members.is_empty() {
88            write!(f, " ")?;
89        }
90        write!(f, "}}")
91    }
92}
93
94impl From<CompositeExpression> for Expression {
95    fn from(value: CompositeExpression) -> Self {
96        Expression::Composite(value)
97    }
98}
99
100crate::simple_node_impl!(CompositeExpression);