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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
// 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,
    ConstValue,
    Constant,
    DefinitionStatement,
    Expression,
    ExpressionNode,
    FromAst,
    Node,
    PartialType,
    Scope,
    Span,
    Statement,
    Type,
    Variable,
};

use std::cell::Cell;

#[derive(Clone)]
pub struct VariableRef<'a> {
    pub parent: Cell<Option<&'a Expression<'a>>>,
    pub span: Option<Span>,
    pub variable: &'a Variable<'a>,
}

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

impl<'a> ExpressionNode<'a> for VariableRef<'a> {
    fn set_parent(&self, parent: &'a Expression<'a>) {
        self.parent.replace(Some(parent));
    }

    fn get_parent(&self) -> Option<&'a Expression<'a>> {
        self.parent.get()
    }

    fn enforce_parents(&self, _expr: &'a Expression<'a>) {}

    fn get_type(&self) -> Option<Type<'a>> {
        Some(self.variable.borrow().type_.clone())
    }

    fn is_mut_ref(&self) -> bool {
        self.variable.borrow().mutable
    }

    // todo: we can use use hacky ssa here to catch more cases, or just enforce ssa before asg generation finished
    fn const_value(&self) -> Option<ConstValue> {
        let variable = self.variable.borrow();
        if variable.mutable || variable.assignments.len() != 1 {
            return None;
        }
        let assignment = variable.assignments.get(0).unwrap();
        match &*assignment {
            Statement::Definition(DefinitionStatement { variables, value, .. }) => {
                if variables.len() == 1 {
                    let defined_variable = variables.get(0).unwrap().borrow();
                    assert_eq!(variable.id, defined_variable.id);

                    value.get().const_value()
                } else {
                    for (i, defined_variable) in variables.iter().enumerate() {
                        let defined_variable = defined_variable.borrow();
                        if defined_variable.id == variable.id {
                            match value.get().const_value() {
                                Some(ConstValue::Tuple(values)) => return values.get(i).cloned(),
                                None => return None,
                                _ => (),
                            }
                        }
                    }
                    panic!("no corresponding tuple variable found during const destructuring (corrupt asg?)");
                }
            }
            _ => None, //todo unroll loops during asg phase
        }
    }

    fn is_consty(&self) -> bool {
        let variable = self.variable.borrow();
        if variable.const_ {
            return true;
        }
        if variable.mutable || variable.assignments.len() != 1 {
            return false;
        }
        let assignment = variable.assignments.get(0).unwrap();

        match &*assignment {
            Statement::Definition(DefinitionStatement { variables, value, .. }) => {
                if variables.len() == 1 {
                    let defined_variable = variables.get(0).unwrap().borrow();
                    assert_eq!(variable.id, defined_variable.id);

                    value.get().is_consty()
                } else {
                    for defined_variable in variables.iter() {
                        let defined_variable = defined_variable.borrow();
                        if defined_variable.id == variable.id {
                            return value.get().is_consty();
                        }
                    }
                    panic!("no corresponding tuple variable found during const destructuring (corrupt asg?)");
                }
            }
            Statement::Iteration(_) => true,
            _ => false,
        }
    }
}

impl<'a> FromAst<'a, leo_ast::Identifier> for &'a Expression<'a> {
    fn from_ast(
        scope: &'a Scope<'a>,
        value: &leo_ast::Identifier,
        expected_type: Option<PartialType<'a>>,
    ) -> Result<&'a Expression<'a>, AsgConvertError> {
        let variable = if value.name.as_ref() == "input" {
            if let Some(input) = scope.resolve_input() {
                input.container
            } else {
                return Err(AsgConvertError::InternalError(
                    "attempted to reference input when none is in scope".to_string(),
                ));
            }
        } else {
            match scope.resolve_variable(&value.name) {
                Some(v) => v,
                None => {
                    if value.name.starts_with("aleo1") {
                        return Ok(scope.context.alloc_expression(Expression::Constant(Constant {
                            parent: Cell::new(None),
                            span: Some(value.span.clone()),
                            value: ConstValue::Address(value.name.clone()),
                        })));
                    }
                    return Err(AsgConvertError::unresolved_reference(&value.name, &value.span));
                }
            }
        };

        let variable_ref = VariableRef {
            parent: Cell::new(None),
            span: Some(value.span.clone()),
            variable,
        };
        let expression = scope.context.alloc_expression(Expression::VariableRef(variable_ref));

        if let Some(expected_type) = expected_type {
            let type_ = expression
                .get_type()
                .ok_or_else(|| AsgConvertError::unresolved_reference(&value.name, &value.span))?;
            if !expected_type.matches(&type_) {
                return Err(AsgConvertError::unexpected_type(
                    &expected_type.to_string(),
                    Some(&*type_.to_string()),
                    &value.span,
                ));
            }
        }

        let mut variable_ref = variable.borrow_mut();
        variable_ref.references.push(expression);

        Ok(expression)
    }
}

impl<'a> Into<leo_ast::Identifier> for &VariableRef<'a> {
    fn into(self) -> leo_ast::Identifier {
        self.variable.borrow().name.clone()
    }
}