Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

how can we handle inner statement? #267

Open
github-actions bot opened this issue Oct 15, 2023 · 1 comment
Open

how can we handle inner statement? #267

github-actions bot opened this issue Oct 15, 2023 · 1 comment
Assignees
Labels

Comments

@github-actions
Copy link

https://api.github.com/KisaragiEffective/origlang/blob/114c0a77603f4c713b4dd76a58969cad56027da9/package/origlang-compiler/src/type_check.rs#L299

    }
}

fn helper(
    expr: TypedExpression, element_binding: &AtomicPattern, checker: &TypeChecker,
) -> Result<Vec<TypedStatement>, TypeCheckError> {
    match element_binding {
        AtomicPattern::Discard => {
            Ok(vec![TypedStatement::EvalAndForget {
                expression: expr,
            }])
        },
        AtomicPattern::Bind(identifier) => {
            checker.ctx.borrow_mut().add_known_variable(identifier.clone(), expr.actual_type());

            Ok(vec![TypedStatement::VariableDeclaration {
                identifier: identifier.clone(),
                expression: expr,
            }])
        }
        AtomicPattern::Tuple(tp) => {
            desugar(tp.clone(), expr, checker)
        }
    }
}

fn desugar(
    outer_destruction: Vec<AtomicPattern>, rhs: TypedExpression, checker: &TypeChecker,
) -> Result<Vec<TypedStatement>, TypeCheckError> {
    debug!("check: {outer_destruction:?} = {rhs:?}");

    match rhs {
        TypedExpression::Variable { ident, tp } => {
            match tp {
                Type::Tuple(tuple_element_types) => {
                    let tuple_element_types = tuple_element_types.0;
                    if outer_destruction.len() == tuple_element_types.len() {
                        desugar(outer_destruction, TypedExpression::Tuple {
                            expressions: tuple_element_types.clone().into_iter().enumerate().map(|(i, _)| TypedExpression::ExtractTuple {
                                expr: Box::new(
                                    TypedExpression::Variable { ident: ident.clone(), tp: Type::tuple(tuple_element_types.clone()) }
                                ),
                                index: i,
                            }).collect(),
                        }, checker)
                    } else {
                        debug!("tuple arity mismatch");
                        Err(TypeCheckError::UnsatisfiablePattern {
                            pattern: AtomicPattern::Tuple(outer_destruction),
                            expression: TypedExpression::Variable { ident, tp: Type::tuple(tuple_element_types.clone()) },
                            expr_type: Type::tuple(tuple_element_types.clone()),
                        })
                    }
                }
                other => {
                    debug!("non-tuple expression");
                    Err(TypeCheckError::UnsatisfiablePattern {
                        pattern: AtomicPattern::Tuple(outer_destruction),
                        expression: TypedExpression::Variable { ident, tp: other.clone() },
                        expr_type: other,
                    })
                }
            }
        }
        TypedExpression::Block { inner, final_expression, return_type } => {
            // TODO: how can we handle inner statement?
            desugar(outer_destruction, *final_expression, checker)
        }
        TypedExpression::Tuple { expressions } => {
            let m = outer_destruction.into_iter().enumerate().map(|(i, element_binding)| {
                helper(expressions[i].clone(), &element_binding, checker)
            }).collect::<Vec<Result<Vec<TypedStatement>, TypeCheckError>>>();

            let mut k = vec![];

            for mx in m {
                match mx {
                    Ok(y) => {
                        k.extend(y);
                    }
                    Err(x) => return Err(x)
                }
            }

            Ok(k)
        }
        TypedExpression::ExtractTuple { expr, index } => {
            let expr = *expr;

            enum K {
                RecurseSimply(TypedExpression),
                InsertTemporary(TypedExpression),
            }
            let expr = match expr {
                TypedExpression::If { condition, then, els, return_type } => {
                    K::RecurseSimply(TypedExpression::If { condition, then, els, return_type: return_type.as_tuple().expect("oops 15").0[index].clone() })
                }
                TypedExpression::Block { inner, final_expression, return_type } => {
                    K::RecurseSimply(TypedExpression::Block { inner, final_expression, return_type: return_type.as_tuple().expect("oops 4").0[index].clone() })
                }
                TypedExpression::Tuple { expressions } => {
                    K::RecurseSimply(expressions[index].clone())
                }
                TypedExpression::Variable { .. } => {
                    K::InsertTemporary(expr)
                }
                other => K::RecurseSimply(other),
            };

            match expr {
                K::RecurseSimply(expr) => {
                    debug!("recurse");
                    desugar(outer_destruction, expr, checker)
                }
                K::InsertTemporary(expr) => {
                    let new_ident = checker.make_fresh_identifier();
                    let tp = expr.actual_type().as_tuple().expect("oh").0[index].clone();
                    let v = TypedExpression::Variable {
                        ident: new_ident.clone(), tp: tp.clone()
                    };

                    checker.ctx.borrow_mut().add_known_variable(new_ident.clone(), tp.clone());
                    let v = desugar(outer_destruction, v, checker)?;
                    let mut r = VecDeque::from(v);

                    r.push_front(TypedStatement::VariableDeclaration {
                        identifier: new_ident.clone(),
                        expression: TypedExpression::ExtractTuple {
                            expr: Box::new(expr),
                            index
                        },
                    });

                    Ok(r.into_iter().collect::<Vec<_>>())
                }
            }
        }
        other => {
            debug!("unsupported expression");
            Err(TypeCheckError::UnsatisfiablePattern {
                pattern: AtomicPattern::Tuple(outer_destruction),
                expr_type: other.actual_type(),
                expression: other,
            })
        }
    }
}

impl TryIntoTypeCheckedForm for Statement {
    type Success = Vec<TypedStatement>;
    type Err = TypeCheckError;

    fn type_check(self, checker: &TypeChecker) -> Result<Self::Success, Self::Err> {
        match self {
            Self::Print { expression } => checker.check(expression).map(|e| vec![TypedStatement::Print { expression: e }]),
            Self::VariableDeclaration { pattern, expression, type_annotation } => {
                let checked = checker.check(expression)?;
                return if let Some(type_name) = type_annotation {
@KisaragiEffective
Copy link
Owner

We don't have to care intermediates because it does not affect the type of entire block.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant