1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.

// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.

use crate::{
    AsgConvertError,
    Expression,
    ExpressionNode,
    FromAst,
    InnerVariable,
    Node,
    PartialType,
    Scope,
    Span,
    Statement,
    Type,
    Variable,
};

use std::cell::{Cell, RefCell};

#[derive(Clone)]
pub struct DefinitionStatement<'a> {
    pub parent: Cell<Option<&'a Statement<'a>>>,
    pub span: Option<Span>,
    pub variables: Vec<&'a Variable<'a>>,
    pub value: Cell<&'a Expression<'a>>,
}

impl<'a> Node for DefinitionStatement<'a> {
    fn span(&self) -> Option<&Span> {
        self.span.as_ref()
    }
}

impl<'a> FromAst<'a, leo_ast::DefinitionStatement> for &'a Statement<'a> {
    fn from_ast(
        scope: &'a Scope<'a>,
        statement: &leo_ast::DefinitionStatement,
        _expected_type: Option<PartialType<'a>>,
    ) -> Result<Self, AsgConvertError> {
        let type_ = statement
            .type_
            .as_ref()
            .map(|x| scope.resolve_ast_type(&x))
            .transpose()?;

        let value = <&Expression<'a>>::from_ast(scope, &statement.value, type_.clone().map(Into::into))?;

        let type_ = type_.or_else(|| value.get_type());

        let mut output_types = vec![];

        let mut variables = vec![];
        if statement.variable_names.is_empty() {
            return Err(AsgConvertError::illegal_ast_structure(
                "cannot have 0 variable names in destructuring tuple",
            ));
        }
        if statement.variable_names.len() == 1 {
            // any return type is fine
            output_types.push(type_);
        } else {
            // tuple destructure
            match type_.as_ref() {
                Some(Type::Tuple(sub_types)) if sub_types.len() == statement.variable_names.len() => {
                    output_types.extend(sub_types.clone().into_iter().map(Some).collect::<Vec<_>>());
                }
                type_ => {
                    return Err(AsgConvertError::unexpected_type(
                        &*format!("{}-ary tuple", statement.variable_names.len()),
                        type_.map(|x| x.to_string()).as_deref(),
                        &statement.span,
                    ));
                }
            }
        }

        for (variable, type_) in statement.variable_names.iter().zip(output_types.into_iter()) {
            variables.push(&*scope.context.alloc_variable(RefCell::new(InnerVariable {
                id: scope.context.get_id(),
                name: variable.identifier.clone(),
                type_:
                    type_.ok_or_else(|| AsgConvertError::unresolved_type(&variable.identifier.name, &statement.span))?,
                mutable: variable.mutable,
                const_: false,
                declaration: crate::VariableDeclaration::Definition,
                references: vec![],
                assignments: vec![],
            })));
        }

        for variable in variables.iter() {
            scope
                .variables
                .borrow_mut()
                .insert(variable.borrow().name.name.to_string(), *variable);
        }

        let statement = scope
            .context
            .alloc_statement(Statement::Definition(DefinitionStatement {
                parent: Cell::new(None),
                span: Some(statement.span.clone()),
                variables: variables.clone(),
                value: Cell::new(value),
            }));

        for variable in variables {
            variable.borrow_mut().assignments.push(statement);
        }

        Ok(statement)
    }
}

impl<'a> Into<leo_ast::DefinitionStatement> for &DefinitionStatement<'a> {
    fn into(self) -> leo_ast::DefinitionStatement {
        assert!(!self.variables.is_empty());

        let mut variable_names = vec![];
        let mut type_ = None::<leo_ast::Type>;
        for variable in self.variables.iter() {
            let variable = variable.borrow();
            variable_names.push(leo_ast::VariableName {
                mutable: variable.mutable,
                identifier: variable.name.clone(),
                span: variable.name.span.clone(),
            });
            if type_.is_none() {
                type_ = Some((&variable.type_.clone()).into());
            }
        }

        leo_ast::DefinitionStatement {
            declaration_type: leo_ast::Declare::Let,
            variable_names,
            type_,
            value: self.value.get().into(),
            span: self.span.clone().unwrap_or_default(),
        }
    }
}